PHP:在 move_uploaded_file() 之后添加对文件的写权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15262748/
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 08:55:15  来源:igfitidea点击:

PHP : add write permission to file after move_uploaded_file()

phpfile-uploadchmod

提问by Raptor

After an image is uploaded with PHP, I want to make the image file writable in order to add a watermark to it . Here are the codes I used:

使用 PHP 上传图像后,我想让图像文件可写,以便为其添加水印。以下是我使用的代码:

if(isset($_FILES['file_poster']['tmp_name']) && $_FILES['file_poster']['tmp_name'] != '') {
        $random_filename = substr(md5(time()), 0, 9);
        $ext = '.jpg';
        if(strpos(strtolower($_FILES['file_poster']['name']), '.png') > -1) {
            $ext = '.png';
        }

        move_uploaded_file($_FILES['file_poster']['tmp_name'], 'uploads/' .  $random_filename . $ext);
        chmod(ABS_PATH . $random_filename, 0666);
        $random_filename = 'uploads/' .  $random_filename . $ext;

        // add watermark codes omitted
}

After the file is uploaded, the file permission becomes 644. Then I tried to use chmod()to change it to writable ( 666), but the permission doesn't change.

文件上传后,文件权限变为644。然后我尝试使用chmod()将其更改为可写(666),但权限没有改变。

The /uploadsfolder has permission 777. Is there any reason that makes chmod()function fails to change permission? or is there a workaround?

/uploads文件夹具有权限777。是否有任何原因使chmod()功能无法更改权限?或者有解决方法吗?

Note: PHP 5 is used. GD is working properly.

注意:使用 PHP 5。GD 工作正常。

回答by Phil

Looks like you need to swap your last two lines, eg

看起来您需要交换最后两行,例如

$random_filename = 'uploads/' .  $random_filename . $ext;
chmod(ABS_PATH . $random_filename, 0666);

Be very careful when using relative paths such as 'uploads/' . $random_filename . $ext. If the working file is included into another file, the current directory may differ.

使用相对路径时要非常小心,例如'uploads/' . $random_filename . $ext. 如果工作文件包含在另一个文件中,当前目录可能不同。

I would recommend something like this

我会推荐这样的东西

$destFile = __DIR__ . '/uploads/' . $random_filename . $ext;
move_uploaded_file($_FILES['file_poster']['tmp_name'], $destFile);
chmod($destFile, 0666);

where the magic __DIR__constant always contains the absolute path to the parent directory of the file you're actually in.

其中魔术__DIR__常量始终包含您实际所在文件的父目录的绝对路径。