通过PHP上传文件后更改文件权限

15

我为我正在开发的一个网站创建了一个小型CMS,其中有一个表单可以上传图片文件以在网站上使用。它成功地上传文件,但它设置的权限不允许在浏览器中查看该文件。

以下是我当前用于上传文件的PHP代码:

$typepath = $_POST['filetype'];

$target_path = "../../images/uploads/".$typepath."/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "<p>The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded</p>\n<p>To the directory:  <span style=\"font-weight:bold;\">".substr($target_path, 6)."</span></p>";
} else{
    echo "There was an error uploading the file, please try again!";
}

浏览器与文件权限无关。您能否讲述更多真实的故事,最好附带复制粘贴的错误信息?谢谢。 - Your Common Sense
@Col. Shrapnel - 是的,它确实会。如果服务器上的文件没有读取权限,那么浏览器将会收到一个“401未授权”的错误提示。 - Spudley
1
@Spudley,这是403错误。而且仍然是服务器问题,不是浏览器问题。 - Your Common Sense
1个回答

26

PHP手册 chmod http://php.net/manual/en/function.chmod.php

chmod("/somedir/somefile", 0755);

在上下文中;

$typepath = $_POST['filetype'];

$target_path = "../../images/uploads/".$typepath."/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    chmod($target_path, 0755);
    echo "<p>The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded</p>\n<p>To the directory:  <span style=\"font-weight:bold;\">".substr($target_path, 6)."</span></p>";
} else{
    echo "There was an error uploading the file, please try again!";
}

2
请注意:使用chmod 755意味着所有者可以读取、写入和执行。组现在可以读取和写入。"其他人"(任何其他人)可以读取和写入。现在,我假设人们无法进入目录,但如果可以的话,他们可能会在您的文件中注入有害内容。我总是选择chmod 750。 - Berry Langerak
@Max,如果你使用的是644权限,你能删除这些文件吗?难道不需要“执行”权限吗? - StefanNch
它是否会为所有用户设置权限? - Adil Malik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接