-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']{$_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 に答える