我的表单很简单,我认为上传php很简单,但是当我测试它时,结果很不寻常。我可以上传任何文件和任何大小,它将工作。我以为我写了它来限制某些文件和大小......我哪里出错?
形式:
<form enctype="multipart/form-data" action="upload_file.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
upload_file.php:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok = 1;
$uploaded = $_POST['uploaded'];
//This is our size condition
if ($uploaded_size > 3000){
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type == "text/php"){
echo "No PHP files are allowed for upload.<br>";
$ok = 0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok == 0){
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else{
echo "Sorry, there was a problem uploading your file.";
}
}
答案 0 :(得分:3)
您的代码完全错误。您无处定义$uploaded_size
,$uploaded_type
等等......因此代码归结为:
if ($uploaded_size > 3000 {
相当于
if (0 > 3000) { // undefined variables are typecast to 0
评估为false,因此$ok
保持1
并且不会触发错误。
我强烈建议您阅读处理文件上传的PHP联机帮助页:http://php.net/manual/en/features.file-upload.php
答案 1 :(得分:1)
你需要像
一样使用它 if ($_FILES["file"]["size"] > 3000) ...
或在检查前定义$ uploaded_size = $ _FILES [“file”] [“size”]。同样地,你需要使用$ _FILES [“file”] [“type”]
$uploaded_size = $_FILES["file"]["size"];
$uploaded_type = $_FILES["file"]["type"];
...
答案 2 :(得分:0)
试试这个:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok = 1;
$uploaded = $_POST['uploaded'];
//This is our size condition
if ($uploaded_size > 3000){
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type == "text/php"){
echo "No PHP files are allowed for upload.<br>";
$ok = 0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok == 0){
Echo "Sorry your file was not uploaded";
die();
}
//If everything is ok we try to upload it
else{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else{
echo "Sorry, there was a problem uploading your file.";
die();
}
}
添加die()
函数会告诉代码停止。另外,您的$ uploaded_type和$ uploaded_size var?