Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8840155
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T10:24:03+00:00 2026-06-14T10:24:03+00:00

Here is my php code to check uploaded file: <?php include(includes/db.php); include(includes/header.php); //========================= //Check

  • 0

Here is my php code to check uploaded file:

<?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");
?>

What I want to is to change the visibility of the user image even if the user has not selected a file to upload. The alerts show up correctly when there is no file selected. But when I give a wrong file, (i.e. a .txt file for instance page still shows "Profile picture visibility updated" instead of the expected result "Invalid file. Only image files are allowed"

What am I doing wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T10:24:05+00:00Added an answer on June 14, 2026 at 10:24 am

    i just tested your code, its messy and i dont believe it will really work, however your not getting the error message because of the following:

    when the file is updated, you use setcookie(..) which I dont believe is the right way to achieve printing out the “success message”, then you reload the page for the user so it loads directly to after if $_FILES and if $_POST check.

    you then check if this cookie exist you print its value and then you try to unset this cookie, and at this point your code fails, because you CAN NOT send headers (setcookie, header(), session()) if anything is printed in the page.

    now if you fixed that it would not work either, because you are submitting the image file and the image privacy $_FILES and $_POST both in the same request, so if $_FILES fails the $_POST request will succeed and it will reload the page and the error variables will be lost.

    I dont know why would you use the header("location:...") function on upload success, you dont want the user to resubmit the data if he reloads the page? its not an issue and not even a security issue if it is for setting cookies with the success msg and displaying them, there are better ways.

    i quickly tweaked your code, test if it works for you, and NOTE this is not the best way to do it the right way, im only providing you this so you can learn the basic structure for handling forms in PHP so you can (must) use them in functions and classes

    <?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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here's my php code: <?php if($user->uid == '1'){ ?> <h3 class=info>Upcoming Games</h3> <!--MY CHANGE
Here is my PHP code.. $input = zergling-light $output = str_replace('-', ' (', $input).);
here is my mysql and php code layout: I have 3 tables tableA stores
So I have some PHP code that looks like: $message = 'Here is the
I am completely stumped. Here is my php (CodeIgniter) code: function mod() { $uid
For example, my goal is to test the code given here: PHP script that
Here is the code I dont know whats wrong with it. <?php //Logout code
I am modifying my PHP network's code to have user roles like wordpress here
<?php while(true){ //code goes here..... } ?> I want to make a PHP web
Here's my code for registerFormOne.php : <html> <head> <title>Registration Form - 1 of 2</title>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.