在 PHP 中替换文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19146954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:54:09  来源:igfitidea点击:

Replace file in PHP

phpfilereplace

提问by user2406937

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.

我想用 PHP 中的另一个图像文件替换一个图像文件。两者都具有相同的名称(123),但它们位于不同的目录中并且应该具有不同的扩展名。我想用第二张图片替换第一张图片。

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

Is it possible with any function? Thank you.

任何功能都可以吗?谢谢你。

采纳答案by Steven

Moving, deleting, copying etc... are all basic actionsthat 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
  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 copyinstead.

如果您重命名(即移动)它,那么该文件将不再存在于它的起始位置。如果您希望文件保留在两个目录中,则应copy改用。

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 ../)

注意:您可以使用相对 pats(例如./../



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