2012-11-11 67 views
-1

这里是我的PHP代码来检查上传的文件:如何测试只有一个输入

<?php 
include("includes/db.php"); 
include("includes/header.php"); 

//========================= 
//Check file upload 
if (!empty($_FILES["file"])) { 
    $allowedExts = array("jpg", "jpeg", "gif", "png"); 
    $extension = end(explode(".", $_FILES["file"]["name"])); 
    if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) { 
     if ($_FILES["file"]["size"] > 524288000) { 
      $mtype="error"; 
      $alertc="Image is too large<br/>\n"; 
      $labelc="labeler"; 
      $inputc="er"; 
     } 
     else { 
      $imgname = $arrusrselect[id].md5($arrusrselect[id]).$arrusrselect[id].".jpg"; 
      move_uploaded_file($_FILES["file"]["tmp_name"], "images/user/profile/" . $imgname); 
      setcookie("success", "Profile picture updated<br/>"); 
      $labelc="label"; 
      $inputc="input"; 
      $upusers=$mysqli->query("UPDATE `users` SET `img`='$imgname' WHERE `id`='$arrusrselect[id]'"); 
      $upimg=$mysqli->query("UPDATE `profile_img` SET `visibility`='$_POST[img_pub]' WHERE `id`='$arrusrselect[id]'"); 
      header('Location: '.$_SERVER['REQUEST_URI']); 
     } 
    } 
    else { 
     $mtype="error"; 
     $alertc="Invalid file. Only image files are allowed<br/>\n"; 
     $labelc="labeler"; 
     $inputc="er"; 
    } 
} 
else { 
    $inputc="input"; 
    $labelc="label"; 
if (isset($_POST['img_pub'])) { 
    setcookie("success", "Profile picture visibility updated<br/>"); 
    $upimg=$mysqli->query("UPDATE `profile_img` SET `img`='$imgname', `visibility`='$_POST[img_pub]' WHERE `id`='$arrusrselect[id]'"); 
    header('Location: '.$_SERVER['REQUEST_URI']); 
} 
} 
//check image visibility 



//image check complete 

//checking complete 


$prof_img=$mysqli->query("SELECT `visibility` FROM `profile_img` WHERE `id`='$arrusrselect[id]'"); 
$prof_img_slct = mysqli_fetch_array($prof_img); 
if (($prof_img_slct[visibility]) == "Public") { 
    $imgchecka = "checked='checked'"; 
} 
elseif (($prof_img_slct[visibility]) == "UsersOnly") { 
    $imgcheckb = "checked='checked'"; 
} 
else { 
    $imgcheckc = "checked='checked'"; 
} 

    if (isset($_COOKIE['success'])) { 
     echo "<div id=\"msg\" class=\"success hide\">$_COOKIE[success]</div>\n"; 
     setcookie("success", "", time()-3600); 
    } 
    elseif (isset($mtype)) { 
     echo "<div id=\"msg\" class=\"".$mtype."\">".$alerta.$alertb.$alertc.$alertd.$alerte."</div>\n"; 
    } 

    echo "<form action='test.php' method='post' enctype='multipart/form-data'>\n"; 
    echo "<table class='login'>\n"; 
    echo "<tr><td class='$labelc'>New Profile Picture:</td><td class='input'><input type='file' name='file' class='$inputc' id='file' /></td><td class='input'> <input type='radio' name='img_pub' value='Public' $imgchecka /> </td><td class='input'> <input type='radio' name='img_pub' value='UsersOnly' $imgcheckb /> </td><td class='input'> <input type='radio' name='img_pub' value='Hide' $imgcheckc/> </td></tr>\n"; 
    echo "<tr><td class='label'></td><td class='input'><p class='flag'> Max. size is 500kB. Allowed file types .jpg, .png &amp; .gif </p></td></tr>\n"; 
    echo "<tr><td></td><td><input type='submit' value='Update' /></td></tr>\n"; 
    echo "</table></form>\n"; 

include("includes/footer.php"); 
?> 

我想什么是改变用户图像的可见度,即使用户没有选择要上传的文件。当没有选定文件时,警报正确显示。但是,当我给一个错误的文件(即.txt文件,例如页面仍显示"Profile picture visibility updated"而不是预期的结果"Invalid file. Only image files are allowed"

我在做什么错

+0

你试过用双引号强制转换'(!empty($ _ FILES [file]))'吗? '(!empty($ _ FILES [“file”]))' –

+0

@MohdMoe Yup。但没有运气! :( – Sid

+0

哦,你确定你在回应错误吗?尝试并添加'exit($ alertc);'** AFTER **'$ alertc =“无效的文件,只允许图像文件”;' –

回答

2

我只是测试你的代码,它的乱,我不相信它会真正的工作,但你没有得到,因为下面的错误消息:

当文件被更新时,您使用setcookie(..)哪些我不相信是实现打印出“成功消息”的正确方法,然后您为用户重新加载页面,以便在if $_FILES and if $_POST检查后直接加载。

然后你检查这个cookie是否存在,你打印它的值,然后你尝试取消设置这个cookie,并且此时你的代码失败,因为你不能发送头文件(setcookie,header(),session())if任何东西都印在页面上。

现在

如果你固定的,这将不能工作,因为您所提交的图像文件,并在同一个请求中的图像隐私$_FILES and $_POST两个,所以如果$_FILES失败$_POST请求将成功,并且将刷新页面和错误变量将会丢失。

我不知道你为什么会在上传成功时使用header("location:...")函数,你不希望用户重新提交数据,如果他重新加载页面?它不是一个问题,甚至没有安全问题,如果是用msg设置cookies并显示它们,有更好的方法。

我很快就调整了代码,测试它是否适合你,注意这是不这样做的正确方法最好的方式,我只是提供你这一点,你可以学习的基本结构在处理表单PHP所以你可以(必须)在函数和类中使用它们

<?php 
    /* ADD THE PRIVACY TYPES INTO AN ARRAY, 
     THE USER CAN CHANGE THE VALUE INTO 
     SOMETHIING IS NOT IN YOUR CODE 
     AND SEND IT TO DATABASE 
    */ 
    $pubTypes = array(
     "Public" => 1, 
     "UsersOnly" => 1, 
     "Hide" => 1 
    ); 
    #check if the submit button is clicked; 
    if($_POST['Update']){ 
    #This (if) will check and update both file and privacy radio on each submit 
     #the file validation and upload. 
     #check if the file is not empty; 
     if(!empty($_FILES["file"])) { 
      $allowedExts = array("jpg", "jpeg", "gif", "png"); 
      $extension = end(explode(".", $_FILES["file"]["name"])); 
      if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) { 
      #file type is allowed, continue and check size; 
       if ($_FILES["file"]["size"] > 524288000) { 
        /* 
        $mtype="error"; 
        $alertc="Image is too large<br/>\n"; 
        $labelc="labeler"; 
        $inputc="er"; 
        */ 
        #set upload error/success to an array 
        $fileup = array(
         "error" => 1, 
         "msg" => "Image is too large" 
        ); 
       } 
       else { 
        #file size allowed upload the image and insert the values in the db 
        $imgname = md5(time() - rand(0,999))."-".$arrusrselect["id"].".".$extension; 

        #upload image and detect any error 
        if(move_uploaded_file($_FILES["file"]["tmp_name"], "images/user/profile/" . $imgname)){ 
         #image uploaded successfuly 
         #update the data base 
         if($upusers=$mysqli->query("UPDATE `users` SET `img`='{$imgname}' WHERE `id`='{$arrusrselect['id']}'")){ 
          $fileup = array(
           "success" => 1, 
           "msg" => "Profile picture updated." 
          );       
         }else{ 
          $fileup = array(
           "error" => 1, 
           "msg" => "Error updating the new picture value in the database." 
          ); 
          #AT THIS POINT, you better delete the new image from server. 
          #@unlink("images/user/profile/" . $imgname); 
         }      
        }else{ 
         #image upload ERROR 
         $fileup = array(
          "error" => 1, 
          "msg" => "Error moving the file to the server." 
         );       
        }#endelse 
       }#end if file size allowed 
      }#end if if file type allowed 
      else{ 
      #file type is not allowed 
       $fileup = array(
        "error" => 1, 
        "msg" => "Invalid file. Only image files are allowed" 
       ); 
      } 
     }else{ #file IS EMPTY  
      /*NO need to print erros, because a user may 
      only update his profile privacy only without 
      submitting a new image*/ 
     } 

     /* CHECK PROFILE PRIVACY UPDATE */ 
     if(!empty($pubTypes[$_POST['img_pub']])){ 
      #check if img_pub selected and its in a valid type, update the database. 
      #you have to check the $imgname, because the upload may have returned errors. 
      if($imgname){ 
       $sql = "UPDATE `profile_img` SET `img`='{$imgname}', `visibility`='{$_POST['img_pub']}' WHERE `id`='{$arrusrselect[id]}'"; 
      }else{ 
       $sql = "UPDATE `profile_img` SET `visibility`='{$_POST['img_pub']}' WHERE `id`='{$arrusrselect[id]}'"; 
      } 
      #send the update query 
      if($upimg=$mysqli->query($sql)){ 
       $pubup = array(
        "success" => 1, 
        "msg" => "Profile picture visibility updated" 
       );        
      }else{ 
       $pubup = array(
        "error" => 1, 
        "msg" => "Error updating picture visibility." 
       ); 
      } 

     }else{ 
      #invalid type, do nothing or you can reset the option to the default 
      $pubup = array(
       "error" => 1, 
       "msg" => "Invalid visibility type." 
      ); 
     } 
    }#end of $_POST['Update']; 
    #END OF CHECKING IF THE FORM WAS POST; 

    //get user's image and visibilty settings. 
    $prof_img=$mysqli->query("SELECT * FROM `profile_img` WHERE `id`='{$arrusrselect['id']}'"); 
    $prof_img_data = mysqli_fetch_array($prof_img); 
    $vis = $prof_img_data['visibility']; 
    if($pubTypes[$vis]) {$pubTypes[$vis] = 'checked';} 
    #you can use the image in html 
    $imgname = $prof_img_data['visibility']; 

    # PRINT UPLOAD AND UPDATE RESULT IF ERROR OR SUCCESS 
    #check file upload result, class will be class="file-error" OR class="file-success" 
    if(is_array($fileup)){ 
     echo "<p class='file-{$fileup['result']}'>Image upload: {$fileup['msg']}</p>"; 
    } 
    #check profile visibility result, class will be class="pub-error" OR class="pub-success" 
    if(is_array($pubup)){ 
     echo "<p class='pub-{$pubup['result']}'>Visibility update: {$pubup['msg']}</p>"; 
    }   
?> 
<form action='<?= $_SERVER['PHP_SELF']; ?>' method='post' enctype='multipart/form-data'> 
<table class='login'> 
<tr> 
<td class='<?php $fileup['error'] ? print("errorClass") : '';?>'>New Profile Picture:</td> 
<td class='input'><input type='file' name='file' class='<?php $fileup['error'] ? print("er") : print("inputc");?>' id='file' /></td> 
<?php foreach($pubTypes as $key=>$value){ 
echo "<td class='input'><input type='radio' name='img_pub' value='$key' value=".($value != 1 ? 'checked' :'')." /></td>"; 
}?> 
</tr> 
<tr> 
<td class='label'></td> 
<td class='input'><p class='flag'> Max. size is 500kB. Allowed file types .jpg, .png &amp; .gif </p></td> 
</tr> 

<tr><td></td><td><input type='submit' name='Update' value='Update' /></td></tr> 
</table></form> 
+0

感谢您的支持 – Sid

1

你可以试试下面的代码:

$error = 1; // this flag will decide any error happens or not 
if (!empty($_FILES["file"])) { 
    $allowedExts = array("jpg", "jpeg", "gif", "png"); 
    $extension = end(explode(".", $_FILES["file"]["name"])); 
    if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) { 
     if ($_FILES["file"]["size"] > 524288000) { 
      $error = 0; // this error so make it 0 
      $alertc="Image is too large<br/>\n"; 
     } 
     else { 
      $imgname = $arrusrselect[id].md5($arrusrselect[id]).$arrusrselect[id].".jpg"; 
      move_uploaded_file($_FILES["file"]["tmp_name"], "../images/user/profile/" . $imgname); 
      $upusers=$mysqli->query("UPDATE `users` SET `img`='$imgname' WHERE `id`='$arrusrselect[id]'"); 
     } 
    } 
    else { 
     $alertc="Invalid file. Only image files are allowed"; 
     $error = 0; // this error so make it 0 
    } 
} 
else { 

} 
//check image visibility 

//If all well then, $error will be 1 otherwise 0 so in case of error like invalid file or file too large, following code doesn't execute. 

if (isset($_POST[img_pub]) && $error) { 
    $alertc="Profile picture visibility updated"; 
    $upimgvis=$mysqli->query("UPDATE `profile_img` SET `visibility`='$_POST[img_pub]' WHERE `id`='$arrusrselect[id]'"); 
} 
+0

请检查完整的php有 – Sid

+0

感谢支持 – Sid

1

您可以检查使用" doubl时$alertc是不是做你的知名度的更新。您也访问的弃用方式$_POST[key]数组值应该是$_POST['key']你可以环绕VAR在{$_POST['key']}之前设置当定义字符串时引号。

<?php 
if (!empty($_FILES['file'])) { 
    $allowedExts = array("jpg", "jpeg", "gif", "png"); 
    $extension = end(explode(".", $_FILES["file"]["name"])); 
    if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && in_array($extension, $allowedExts)) { 
     if ($_FILES["file"]["size"] > 524288000) { 
      $alertc="Image is too large<br/>\n"; 
     } 
     else { 
      $imgname = $arrusrselect['id'].md5($arrusrselect['id']).$arrusrselect['id'].".jpg"; 
      move_uploaded_file($_FILES["file"]["tmp_name"], "../images/user/profile/" . $imgname); 
      $upusers = $mysqli->query("UPDATE `users` SET `img`='$imgname' WHERE `id`='{$arrusrselect['id']}'"); 
     } 
    } 
    else { 
     $alertc="Invalid file. Only image files are allowed"; 
    } 
} 

//check image visibility 
if (isset($_POST['img_pub']) && !isset($alertc)) { 
    $alertc="Profile picture visibility updated"; 
    $upimgvis=$mysqli->query("UPDATE `profile_img` SET `visibility`='{$_POST['img_pub']}' WHERE `id`='{$arrusrselect['id']}'"); 
} 
//image check complete 
?> 
+0

请检查编辑好的代码。完整的PHP有 – Sid

+0

感谢支持 – Sid

相关问题