我正在搜索至少半小时,但我无法弄清楚我的代码有什么问题?
这是:
<?php
$file = $_FILES["file"];
$filename = $_FILES["file"]["name"];
$tempdir = $_FILES["file"]["tmp_name"];
$error = $_FILES["file"]["error"];
$type = $_FILES["file"]["type"];
$size = $_FILES["file"]["size"];
$maxsize = 524288;
$allowedtypes = array("image/png", "image/jpg", "image/jpeg", "image/bmp");
$errormsg = "";
if(!empty($error))
{
switch($error)
{
case '1':
$errormsg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$errormsg = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$errormsg = 'The uploaded file was only partially uploaded';
break;
case '4':
$errormsg = 'No file was uploaded.';
break;
case '6':
$errormsg = 'Missing a temporary folder';
break;
case '7':
$errormsg = 'Failed to write file to disk';
break;
case '8':
$errormsg = 'File upload stopped by extension';
break;
default:
$errormsg = 'No error code avaiable';
}
} elseif(empty($tempdir) || $tempdir == 'none') {
$errormsg = 'No file was uploaded..';
} elseif(!in_array($type, $allowedtypes) || $size > $maxsize) {
$errormsg = 'Either image type not supported or size is extending 512 KB';
} else {
$filename = $_SESSION["username"];
$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$path = 'profile_pictures/' . $filename . "." . $extension;
foreach($ext as $allowedtypes) {
if(file_exists($filename . "." . $ext)) unlink($filename . "." . $ext);
}
move_uploaded_file($tempdir, $path);
//for security reason, we force to remove all uploaded file
@unlink($file);
}
echo $path;
?>
如果我删除了foreach循环,它可以正常工作,但它无法正常工作!
为什么会这样?请帮忙。
答案 0 :(得分:2)
foreach
循环的参数不正确。正确的语法是:
foreach (array_expression as $value) {
statement;
}
$ext
是包含上传文件扩展名的字符串,$allowedtypes
是包含有效扩展名的数组。您正试图遍历字符串。
foreach($ext as $allowedtypes) {
if(file_exists($filename . "." . $ext)) unlink($filename . "." . $ext);
}
应该是:
foreach($allowedtypes as $ext) {
if(file_exists($filename . "." . $ext)) unlink($filename . "." . $ext);
}
注意:我建议你enable error reporting发现这样的错误。它在开发过程中会有所帮助。另外,请勿使用@
- 它会隐藏有用的错误消息。如果您不想向用户显示错误消息,请关闭错误报告并改为记录它们。