Replace file in PHP [closed]

2020-03-02 04:03发布

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

  1. ../images/123.gif
  2. ../images/xxx/123.png

Is it possible with any function? Thank you.

标签: php file replace
1条回答
何必那么认真
2楼-- · 2020-03-02 04:34

Moving, deleting, copying etc... are all basic actions that are needed whenever working with file systems. As such the documentation will undoubtedly have all of the information you need.

  1. http://php.net/rename
  2. http://php.net/copy
  3. http://php.net/unlink

You say that you want to replace the first file with the second.. But you don't mention what you want to happen to the original copy of the second image?

If you rename (i.e. move) it then the file will no longer exist in it's starting location. If you want the file to remain in both directories then 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 are able to use relative pats (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
查看更多
登录 后发表回答