Replace file in PHP

I would like to replace one image file with another in PHP. Both have the same name (123), but they are in a different directory and must have a different extension. I want to replace the first image with the second image.

  • ../images/123.gif
  • ../images/xxx/123.png

Is it possible with any function? Thanks.

+6
source share
1 answer

Move, delete, copy, etc. - all the basic actions that are necessary when working with file systems. Thus, the documentation will undoubtedly contain all the necessary information.

You say you want to replace the first file with the second. But you do not say what you want to do with the original copy of the second image?

If you rename (i.e. move), then the file will no longer be in its original location. If you want the file to remain in both directories, you should use copy instead.

In this case, all you need is:

 rename('/path/to/get/file.from', '/path/to/put/file.to'); 

NOTE. . You can use relative fixes (e.g. ./ and ../ )


Additional code

 rename('/path/to/get/file.b', '/path/to/put/file.b'); unlink('/path/to/remove/file.a'); 

Working example

 rename('../image/new/8.jpg', '../image/8.jpg'); //Moves new (jpg) file to `../image` directory unlink('../image/8.gif'); //Delete old file with gif extension 
+6
source

Source: https://habr.com/ru/post/955151/


All Articles