1

我的表单很简单,我认为上传 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> 

上传文件.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."; 
        } 
    }
4

3 回答 3

3

你的代码是完全错误的。您在任何地方都没有定义$uploaded_size,$uploaded_type等...所以代码归结为:

if ($uploaded_size > 3000 {

相当于

if (0 > 3000) {  // undefined variables are typecast to 0

其评估结果为假,因此$ok保持不变1,不会触发任何错误。

强烈建议您阅读有关处理文件上传的 PHP 手册页:http: //php.net/manual/en/features.file-upload.php

于 2013-04-29T20:16:53.830 回答
1

你需要像这样使用它

     if ($_FILES["file"]["size"] > 3000) ...

或在检查前定义 $uploaded_size = $_FILES["file"]["size"] 。同样,您需要使用 $_FILES["file"]["type"]

     $uploaded_size = $_FILES["file"]["size"];
     $uploaded_type = $_FILES["file"]["type"];
     ...
于 2013-04-29T20:17:41.303 回答
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 在哪里?

于 2013-04-29T20:20:42.680 回答