Jump to content

php mysql image upload issue


PNewCode
Go to solution Solved by PNewCode,

Recommended Posts

Hello

I have a working upload image file to the folder and name of the file to the database. The form also has a place to enter a name of the file to also make a comment on the page.

The problem is that if no file is chosen to upload, then the whole thing stops. Below is what I have and then after that is what I've tried. Any thoughts?
Goal: To allow this form to submit with or without an image. The text field is already put as required in the form

This is what I have (leaving out all the connection to the db stuff and the "insert into" part because thats fine. The issue is only when the no file is chosen)

$allowed_img = array('gif', 'png', 'jpg', 'jpeg');

$img_ext = $_FILES["file"]["name"];

$ext = pathinfo($img_ext, PATHINFO_EXTENSION);  



if (!in_array($ext, $allowed_img)) {
    
if (!in_array($ext, $allowed_img)) {
   echo 'No Image Was Chosen. This Form Did Not Post';

}
 die();
}



     #file name with a random number so that similar dont get replaced
     $pname = rand(1000,10000)."-".$_FILES["file"]["name"];
     $pname = str_replace(" ", "_", $pname);
     #temporary file name to store file
    $tname = $_FILES["file"]["tmp_name"];
    #upload directory path
    $uploads_dir = 'img';
    #TO move the uploaded file to specific location
    move_uploaded_file($tname, $uploads_dir.'/'.$pname);

This is what I've tried

$allowed_img = array('gif', 'png', 'jpg', 'jpeg');

$img_ext = $_FILES["file"]["name"];
$ext = pathinfo($img_ext, PATHINFO_EXTENSION);  


if (!in_array($ext, $allowed_img)) {
    
if (!in_array($ext, $allowed_img)) {
   ($ext = "", $allowed_img = "");

}
 die();
}


///// and I tried ////


$allowed_img = array('gif', 'png', 'jpg', 'jpeg');

$img_ext = $_FILES["file"]["name"];
$ext = pathinfo($img_ext, PATHINFO_EXTENSION);  


if (!in_array($ext = "", $allowed_img = "")) {
    
elseif (!in_array($ext, $allowed_img)) {
echo 'No image file selected';

}
 die();
}




///// and I ALSO tried ////


$allowed_img = array('gif', 'png', 'jpg', 'jpeg');

if $img_ext = $_FILES[""][""]; {
} else {
$img_ext = $_FILES["file"]["name"];
}

$ext = pathinfo($img_ext, PATHINFO_EXTENSION);  

if (!in_array($ext = "", $allowed_img = "")) {

}
 die();
}

//// And about 10+ more variations that I don't remember what I did ////

 

Link to comment
Share on other sites

@ginerjm that's a perfect plan. I couldn't figure out how to do that either so I thought it would be easier to just have it enter in nothing if no file was selected. I couldn't figure out how to do either one. But yes that would be ideal.
I know at one point I almost had it that way but then it wasn't inserting the message field in the db either

Link to comment
Share on other sites

since you must test the ['error'] element of the uploaded file information, before using any of the file data for a correctly uploaded file, you would test the ['error'] value to see if no file was selected - UPLOAD_ERR_NO_FILE (Value: 4), to skip the file processing code.

your post method form processing code should detect if a post method form was submitted, then test if both the $_POST and $_FILES arrays are empty. if they are, this indicates that the total size of the form data exceeded the post_max_size setting. in this case, you would setup a message for the user letting them know that the form data was too large (likely due to the size of the uploaded file) and could not be processed. after you have detected that there is form data, you would test the ['error'] element of the uploaded field information, then proceed based on which value it is. for errors that the user has control over, you would setup and display unique and helpful error messages. for errors that the user doesn't have any control over, you would setup a generic failure message for the user and log the actual error information so that you know what is causing uploads to fail.

  • Like 1
Link to comment
Share on other sites

  • Solution

I figured it out. I was trying to add stuff to the wrong if statement. Instead I just changed the following, and now it works :)

 

 if (isset($_POST["submit"]))
 {
$pname = "";
	 if(!empty($_FILES["file"]["name"])){
     $allowed_img = array('gif', 'png', 'jpg', 'jpeg');

 

Link to comment
Share on other sites

So why do you have this still in your code:

$img_ext = $_FILES["file"]["name"];
$ext = pathinfo($img_ext, PATHINFO_EXTENSION);  
if (!in_array($ext, $allowed_img)) 
{
	if (!in_array($ext, $allowed_img)) 
	{
		($ext = "", $allowed_img = "");
	}
 	die();
}

Not only are you doing an if test twice but the line inside that is clearly error-laden.

($ext = "", $allowed_img = "");

The above line makes no sense and I do believe it should be giving you an error.  And why are you bothering to clear out the allowed extensions array?  That s/b setup at the beginning of your script and left completely alone.

Edited by ginerjm
Link to comment
Share on other sites

1 hour ago, PNewCode said:

I figured it out. I was trying to add stuff to the wrong if statement. Instead I just changed the following, and now it works :)

 

 if (isset($_POST["submit"]))
 {
$pname = "";
	 if(!empty($_FILES["file"]["name"])){
     $allowed_img = array('gif', 'png', 'jpg', 'jpeg');

 

This is taken from my website project ->

 

$file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
$extensions = array("jpeg", "jpg", "png");

if (in_array($file_ext, $extensions, true) === false) {
    $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
}

    /*
     * If no errors save ALL the information to the
     * database table.
     */
    if (empty($errors) === true) {
        // Code that does it....
    }

I know my variable naming isn't exact, but it should give you a basic way in doing it.

I have the GitHub repository -> https://github.com/Strider64/brain-wave-blitz/blob/master/create_cms.php feel free to look around.

Edited by Strider64
  • Like 1
Link to comment
Share on other sites

@ginerjm I get no errors. And I know, that double if looks like it shouldn't belong but if I take one out, it doesn't work at all. Not too sure why you assume what I still had and didn't have, I was just showing what made it work. But for anyone that comes to this wanting to know how to make that work, here's what I have in more length. Don't ask me how or why because I couldn't tell you. I just tinkered with it till it worked lol.

Now the form will submit with or without an image (if the user just wants to post a comment without a picture, they can)

 

 if (isset($_POST["submit"]))
 {
$pname = "";
	 if(!empty($_FILES["file"]["name"])){
     $allowed_img = array('gif', 'png', 'jpg', 'jpeg');

     
      $img_ext = $_FILES["file"]["name"];
      $ext = pathinfo($img_ext, PATHINFO_EXTENSION);
           
           
     if (!in_array($ext, $allowed_img)) {
    
     if (!in_array($ext, $allowed_img)) {
    echo ' ';
}
 die();
}




     #file name with a random number so that similar dont get replaced
     $pname = rand(1000,10000)."-".$_FILES["file"]["name"];
     $pname = str_replace(" ", "_", $pname);
     #temporary file name to store file
    $tname = $_FILES["file"]["tmp_name"];
    #upload directory path
    $uploads_dir = 'img';
    #TO move the uploaded file to specific location
    move_uploaded_file($tname, $uploads_dir.'/'.$pname);


}
}

 

Link to comment
Share on other sites

If you take one out WHAT doesn't work?  Perhaps you could show us what fails (in the proper context of course)

There is absolutely no need for those duplicate statements in any code anywhere.  It's what you are doing elsewhere that is failing you.

Here is how I would amend it:

$allowed_img = array('gif', 'png', 'jpg', 'jpeg');
...
...
...
if (isset($_POST["submit"]))
{
	$pname = "";
	if(!empty($_FILES["file"]["name"]))
	{
		$img_ext = $_FILES["file"]["name"];
		$ext = pathinfo($img_ext, PATHINFO_EXTENSION);
		if (!in_array($ext, $allowed_img))
		{
			echo 'Invalid file';
			die();
		}
		//file name with a random number so that similar dont get replaced
		$pname = rand(1000,10000) . "-" . $_FILES["file"]["name"];
		$pname = str_replace(" ", "_", $pname);
		//temporary file name to store file
		$tname = $_FILES["file"]["tmp_name"];
		//upload directory path
		$uploads_dir = 'img';
		//TO move the uploaded file to specific location
		move_uploaded_file($tname, $uploads_dir.'/'.$pname);
	}
}

Not sure what the rest of the code is doing but this part should not be a problem.

One tip - I would re-order the file name to use the name as the First part with a number appended after an UNDERSCORE, not a minus sign.  And then of course I would check if the filename that you create already exists.  I know you grabbed a random number but that could fail you.

Edited by ginerjm
Link to comment
Share on other sites

@ginerjm My whole page works. There are no errors. Why would I change anything when it's working? The previous post I made shows what works. 

17 hours ago, ginerjm said:

If you take one out WHAT doesn't work?  Perhaps you could show us what fails (in the proper context of course)

If I take out what I said, one of these lines

     if (!in_array($ext, $allowed_img)) {
    
     if (!in_array($ext, $allowed_img)) {

Sorry but I don't see any reason to change it since the page is working as it needs to. If someone else comes along and sees this then they can see what I did to make it work for them too. I think suggesting I change up the coding could just confuse someone new like me
 

Link to comment
Share on other sites

If someone like you thinks that using the same if statement twice is the thing to do, then they are as confused as you are.  IMO, to not want to fix what you are doing (wrongly) is a terrible way to begin your programming career.

Have fun!

Link to comment
Share on other sites

I too am a retired old man.  But I like to fix my programming errors.

As I asked before - how about showing us the code following your 'bad code' that 'doesn't work' so we can fix it for you.  Obviously you don't know what an if statement does.

Link to comment
Share on other sites

@ginerjm I really do appreciate your help but as I posted a few times now, there isn't anything on the page that doesn't work anymore. The page works as it is intended now with the fix that I made on it. There is nothing further to fix at all. That project is completed :) Thank you for the help :) See the one I marked as the solution. It shows all

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.