PHP File Upload Error

0 Altaf Husain Neva · August 7, 2015
I am trying to learn uploading images via PHP. My code is:

<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$target_dir = "../images/images_channel/";
$target_file = $target_dir . basename($_FILES['image']['name']);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$new_image_name = $target_dir . "abc" . "." . pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["image"]["tmp_name"], $new_image_name)) {
echo "success";
}
else {
echo "fail";
}
}
?>

<form action="" method="POST">
<input type="file" name="image" id="image" />
<input type="submit" value="Submit" />
</form>




I am getting this error:
/images/forum/upload/2015-08-07/58649ce78dd1d61f4d91caca5e340230.png

Post a Reply

Replies

Oldest  Newest  Rating
+1 pwntastic _ · August 10, 2015
Hello, 

In your form tags you have to also include the enctype.

This is how your form tag should look, adding this should resolve that issue: 
0 brad s · August 10, 2015
Just a pointer, if($_SERVER['REQUEST_METHOD'] == "POST") is kind of incorrect. It works, but if you do it the intended way, it's a lot less confusing.


if($_POST){


   //code


}



does the same thing.
Now, when you want to catch a specific 'name' tag from the form, you do


if($_POST['image']){


  //code


}



and now you are looking at just 1 item in the array.
You can get more specific and match a value




$_POST['image'] = 1; //assuming the form $_POST a number 1





if($_POST['image'] == 1){


  //code


}



BUT, many times you will still get a pesky unidentified error because the code is loaded before the user  POST.
So, to get rid of that, we use isset(), but since about PHP 5.5, it is now empty().


$_POST['image'] = 1; 





if(!empty($_POST){


   if($_POST['image'] == 1){


      //code


   }


}
0 Altaf Husain Neva · August 11, 2015
@Joel That solved My Issue..

@Brad Hey thank you for a great information, I'll consider it. I still have doubt in this statement: $_POST['image'] = 1; Can you please explain me in detail that when and for what it is used ? How do it works?
  • 1

PHP

106,994 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators