【问题标题】:I can't get the rename() function in PHP to work (or any of the file modifcation functions for that matter)我无法让 PHP 中的 rename() 函数工作(或任何文件修改函数)
【发布时间】:2020-06-26 01:07:58
【问题描述】:

感谢您的宝贵时间。

所以,我有一个 LAMP 堆栈 Web 服务器,并且想要更改已上传文件的路径。

例如,用户通过前端上传一张图片,PHP代码读取它,将文件重命名为哈希字符串,使图片上传目录中的文件不会重叠且同名,然后指向用户所在行的图片列指向 SQL 表中的新路径。

所以除了重命名文件之外,我已经完成了所有工作。

文件名传入成功(即ball.png)

    $fileName = basename($_FILES["file"]["name"]); //This works, and let's pretend that it is "ball.png" in this example.

    $baseDir = "uploads/profiles"; //This code works as it should.
    $targetPath = $baseDir.$fileName; //This code works as it should.

    $newFileName = $randomString.$fileExtension;
    //The random string variable is generated in a previous function, and it works. Let's pretend that it is "e7635hasf1 in this example."
    //The file extension variable is generated in a previous function, and it works. Let's pretend that it is ".png" in this example.

    rename($targetPath, $newFileName);
    //This is the code that does not work. I've tried changing permissions, doing it in the same directory to simplify things, but can't get rename() to work at all.

    updateTables();
    //This code works as it should. The SQL picture column for the row of the user that uploaded the picture now reads "uploads/profiles/e7635f1.png"

如果有帮助的话,我正在使用 PHP 7。如果我不重命名任何内容(例如,如果我执行 updateTables() 函数并传递“uploads/profiles/ball.png”而不是“uploads/profiles/e7653hasf1.png”),则此代码可以正常工作。这基本上可以确定问题出在 rename() 函数中,因此这是特定的单行代码不起作用。

再次感谢您的宝贵时间。如果您有任何问题,请告诉我。

【问题讨论】:

  • 创建$targetPath时需要/$baseDir$fileName之间。
  • $newFileName 需要一个目录前缀。

标签: php mysql lamp


【解决方案1】:
$targetPath = $baseDir.'/'.$fileName;

$newFileName = $baseDir.'/'.$randomString.$fileExtension;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多