-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"

我究竟做错了什么?

4

3 回答 3

2

我刚刚测试了您的代码,它很乱,我不相信它会真正起作用,但是由于以下原因,您没有收到错误消息:

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

然后你检查这个cookie是否存在你打印它的值然后你尝试取消设置这个cookie,此时你的代码失败了,因为你不能发送标题(setcookie,header(),session())如果任何东西打印在这页纸。

现在如果你修复了它也不起作用,因为你$_FILES and $_POST在同一个请求中提交图像文件和图像隐私,所以如果$_FILES失败,$_POST请求将成功,它将重新加载页面,错误变量将丢失。

我不知道为什么要header("location:...")在上传成功时使用该功能,如果用户重新加载页面,您不希望用户重新提交数据?如果用于设置带有成功消息的 cookie 并显示它们,这不是问题,甚至不是安全问题,有更好的方法。

我很快调整了你的代码,测试它是否适合你,注意这不是正确的最好方法,我只为你提供这个,所以你可以学习在 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>
于 2012-11-11T23:30:08.453 回答
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]'");
}
于 2012-11-11T13:12:58.863 回答
1

$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
?>
于 2012-11-11T13:13:25.283 回答