【发布时间】:2013-12-02 14:19:48
【问题描述】:
我正在使用chmod($path, $mode, bool) 函数,但它没有正确设置权限,所以我现在正在尝试:
$fp = fopen($path, 'w');
fclose($fp);
chmod($path, 0750); //changed to add the zero
return true;
问题是当我使用第一种方法时,它创建的路径正常...类似这样的东西 uploads/2013/name/1/file.pdf(correct) 但permissio0ns 不正确。
当我使用第二种方法时,它会创建一个没有扩展名的文件:uploads/2013/name/1(incorrect) 但权限是正确的...
这是我的代码:
if($_POST["upload"]){
$year = date('Y');
//path to directory
$path = $_SERVER["DOCUMENT_ROOT"] . '/uploads/' . $year . '/' . strtolower(str_replace(' ','',$_POST["username"])) . '/' . $_POST["month"];
//path to file
$target_path = $path . '/' . basename($_FILES['uploadedfile']['name']);
$filename = basename($_FILES['uploadedfile']['name']);
/* $ext = substr($filename, strrpos($filename, '.') + 1); */
if(!is_dir($path) && !file_exists($target_path)) {
mkdir($path, 0750, true);
chmod($path, 0750, true); //changed to add the zero
if(($_FILES["uploadedfile"]["type"] == "application/pdf") && ($_FILES["uploadedfile"]["size"] < 550000)) {
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){
print "<div class='success'>The file " . "<span class='filename'>" . basename( $_FILES['uploadedfile']['name']) . "</span>" . " has been uploaded</div>";
}
} else {
print "<div class='error'>Wrong file format</div>";
}
} else {
print "<div class='error'>File already exists!</div>";
}
}
【问题讨论】:
-
提示:如果您想创建一个空文件,请使用
touch($path)而不是fopen()/fclose() -
为什么
$target_path几乎重复了所有$path逻辑?为什么不只是$target_path = $path . '/' . basename(...)?请注意,$_FILES 中的['type']参数NOT 可靠。它是用户提供的,伪造起来很简单。 -
我不想创建一个空文件,所以我需要摆脱 fopen / fclose。我想为正在上传的文件添加权限,@Michael 代码需要大量清理我只是想让它首先工作。