How to make upload form and php action work as single file?

Hi I am have a single image upload script it works when add the action into a different file but when I try to add the whole script in a single file the php doesnt run?

<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post" enctype="multipart/form-data">
   <p>
      <label for="file">Select a file:</label>
       <input type="file" name="userfile" id="file"> <br />
      <input type="submit" value="upload">
   <p>
</form>


<?php
if (isset ($_POST["submit"])) {
   // Configuration - Your Options
      $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
      $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
      $upload_path = './images/'; // The place the files will be uploaded to (currently a 'files' directory).

   $filename = $_FILES["userfile"]["name"]; // Get the name of the file (including file extension).
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.

   // Check if the filetype is allowed, if not DIE and inform the user.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');

   // Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES["userfile"]["tmp_name"]) > $max_filesize)
      die('The file you attempted to upload is too large.');

   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
	
	
	
	
    $filename = time().$ext; // this will give the file current time so avoid files having the same name
   // Upload the file to your specified path.
   if(move_uploaded_file($_FILES["userfile"]["tmp_name"],$upload_path . $filename))
         echo time(). ' Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked.
      else
         echo 'There was an error during the file upload.  Please try again.'; // It failed :(.
}
?>

Did you modify the PHP code when you merged the two scripts together? Because if you separated both HTML and PHP code, then this script will not run. You must have added in the checking of the form submission (with the IF statement); and it is because of this as to why the PHP isn’t being executing. This is due to the fact that you have not named the submit button, so the HTTP POST method is not passing on any information to PHPs $_POST associative array; making a check for any value in $_POST nugatory. Add a name to your submit button so that the $_POST array has a key to identify whether the form has been submitted or not (using isset) and it will function:


<input type="submit" name="submit" value="upload">

On top of what @modernW stated, I want to encourage you to put your PHP code before your html form and using PHP_SELF in forms is a security risk.

Thanks alot guys followed all your advises and its working fine, do you guys think the validation is safe enough or at least average safe to avoid, if not any other tips are welcome.

once again thanks alot

@macaela, I think your validations are fine. However, you might want to consider making your error messages a little more informative. For instance, if the user tries to upload a file that is larger than the size you specify, to your error message you might want to convey to the user what is the acceptable size:

if(filesize($_FILES["userfile"]["tmp_name"]) > $max_filesize)
      die('The file you attempted to upload is too large. It should not be greater than ' . $max_filesize . '.');

Otherwise, you are good to go.

Thanks will do

@ parkerj I tried to add the form above the php script but the problem is that when validate it no longer shows the form just the error message even thou it shows on the same page. is there a fix or should I just keep the form below the script.

If I understand you correctly, instead of die(); do something like this:

$message = 'The file you attempted to upload is too large. It should not be greater than ' . $max_filesize . '.';

Then just above your form add:

<?php echo $message; ?>

If an error occurs, then that message will appear above the form. You can use the $message variable for all of your errors instead of die().

Hi if I do that and add the
<?php echo $message; ?>
I get the classic undefined

like this

<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<h2>Upload an image</h2>

Upload an image: <br /><INPUT type="file" name="userfile">
<br />
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $message; ?>

Just realised if I use the variable message without die the extension type validation fails it upload other files type even thou I’ve validate so it doesnt.

<?php
     include "connection.php"; // find file (connection.php)

if (isset ($_POST["submit"])) { // if post has been set/clicked run the code below
   // Configuration - Your Options
      $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
      $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
      $upload_path = './images/'; // The place the files will be uploaded to (currently a 'files' directory).

   $filename = $_FILES["userfile"]["name"]; // Get the name of the file (including file extension).
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.

   // Check if the filetype is allowed, if not DIE and inform the user.
   if(!in_array($ext,$allowed_filetypes))
      $message = 'The file you attempted to upload is not allowed.';

   // Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES["userfile"]["tmp_name"]) > $max_filesize)
       $message = 'The file you attempted to upload is too large.';

   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!is_writable($upload_path))
        $message = 'You cannot upload to the specified directory, please CHMOD it to 777.';
	
	
	
	
    $filename = time().$ext; // this will give the file current time so avoid files having the same name
   // Upload the file to your specified path.
   if(move_uploaded_file($_FILES["userfile"]["tmp_name"],$upload_path . $filename)){

   $query = "INSERT INTO animals (id,  image)
                    VALUES ('',  '$filename')";

                    mysql_query($query) or

                    die (mysql_error());
					

         echo time(). ' Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>';
		
		 $current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
		 // It worked.
   }
      else
         echo 'There was an error during the file upload.  Please try again.'; // It failed :(.
//http://stackoverflow.com/questions/2666882/how-to-avoid-resending-data-on-refresh-in-php

//scape string http://stackoverflow.com/questions/13034868/form-to-insert-data-in-database-works-but-does-not-show-success-page
		
}
?>

<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<h2>Upload an image</h2>

Upload an image: <br /><INPUT type="file" name="userfile">
<br />
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $message;  ?>

@macaela, this should get you close to where you want to be:

<?php
     include "connection.php"; // find file (connection.php)

if (isset ($_POST["submit"])) { // if post has been set/clicked run the code below
   // Configuration - Your Options
      $name = $_FILES['userfile']['name'];
	  $type = $_FILES['userfile']['type'];
	  $size = $_FILES['userfile']['size'];
	
      $allowed = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
      $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
      $upload_path = './images/'; // The place the files will be uploaded to (currently a 'files' directory).

   $ext = substr($name, strpos($name,'.'), strlen($name)-1); // Get the extension from the filename.
 	
 	$fileType = in_array($ext, $allowed);
   // Check if the filetype is allowed, if not DIE and inform the user.
   if(!$fileType) :
      $message = 'The file you attempted to upload is not allowed.';
   endif;

   // Now check the filesize, if it is too large then DIE and inform the user.
   if($size > $max_filesize) :
       $message = 'The file you attempted to upload is too large.';
   endif;

 	$upload = is_writable($upload_path);
   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!$upload) :
        $message = 'You cannot upload to the specified directory, please CHMOD it to 777.';
   endif;




    $filename = time().$ext; // this will give the file current time so avoid files having the same name
   // Upload the file to your specified path.
   if($fileType && $size < $max_filesize && $upload) {
   if(move_uploaded_file($_FILES["userfile"]["tmp_name"],$upload_path . $filename)) {
   $query = "INSERT INTO animals (id,  image)
                    VALUES ('',  '$filename')";

                    mysql_query($query) or

                    die (mysql_error());


         echo time(). ' Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>';

         $current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
         // It worked.
   }}
      else
         echo 'There was an error during the file upload.  Please try again.'; // It failed :(.
//http://stackoverflow.com/questions/2666882/how-to-avoid-resending-data-on-refresh-in-php

//scape string http://stackoverflow.com/questions/13034868/form-to-insert-data-in-database-works-but-does-not-show-success-page

}
echo $message;
?>

<form name="form" action="upload.php" enctype="multipart/form-data" method="post">
<h2>Upload an image</h2>

Upload an image: <br /><INPUT type="file" name="userfile">
<br />
<input type="submit" name="submit" value="Submit">
</form> 

Hi shows two problem one $message not set
Notice: Undefined variable: message in C:\xampp\htdocs
eusa\upload\index.php on line 62
and second one is when validate it show all three error message when should just show one

here ho wI’ve set it up now

<?php
     include "connection.php"; // find file (connection.php)

if (isset ($_POST["submit"])) { // if post has been set/clicked run the code below
   // Configuration - Your Options
      $name = $_FILES['userfile']['name'];
      $type = $_FILES['userfile']['type'];
      $size = $_FILES['userfile']['size'];

      $allowed = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
      $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
      $upload_path = './images/'; // The place the files will be uploaded to (currently a 'files' directory).

   $ext = substr($name, strpos($name,'.'), strlen($name)-1); // Get the extension from the filename.

     $fileType = in_array($ext, $allowed);
   // Check if the filetype is allowed, if not DIE and inform the user.
   if(!$fileType) :
      $message = 'The file you attempted to upload is not allowed.';
   endif;

   // Now check the filesize, if it is too large then DIE and inform the user.
   if($size > $max_filesize) :
       $message = 'The file you attempted to upload is too large.';
   endif;

     $upload = is_writable($upload_path);
   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!$upload) :
        $message = 'You cannot upload to the specified directory, please CHMOD it to 777.';
   endif;


	
    $filename = time().$ext; // this will give the file current time so avoid files having the same name
   // Upload the file to your specified path.
   if($fileType && $size < $max_filesize && $upload) {
   if(move_uploaded_file($_FILES["userfile"]["tmp_name"],$upload_path . $filename)){

   $query = "INSERT INTO animals (id,  image)
                    VALUES ('',  '$filename')";

                    mysql_query($query) or

                    die (mysql_error());
					

         echo time(). ' Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>';
		
	 $current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
		 // It worked.
   }}
      else
         echo 'There was an error during the file upload.  Please try again.'; // It failed :(.
//http://stackoverflow.com/questions/2666882/how-to-avoid-resending-data-on-refresh-in-php

//scape string http://stackoverflow.com/questions/13034868/form-to-insert-data-in-database-works-but-does-not-show-success-page
		
}
echo $message;
?>

<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<h2>Upload an image</h2>

Upload an image: <br /><INPUT type="file" name="userfile">
<br />
<input type="submit" name="submit" value="Submit">
</form>

hi ok it seems like the only problems is the variable $message when i try to echo is say
Notice: Undefined variable: message in C:\xampp\htdocs
eusa\upload\index.php on line 60
How can I define if is set right at teh bottom of the script?

Sorry, I can’t help with that. In Linux it works great; I am not a Windows expert, so I can’t give direction on how to fix it for Windows. It may need to be converted to an array, but I can’t be sure.

Does on linux if first validation fails doesnt run second one? like

 if(!$fileType) :
      $message = '<br />The file you attempted to upload is not allowed.';
   endif;

// dont run this one if above fails at moment it runs if to validation fails, I cant die or use exit because I still want to show the form when fails

   // Now check the filesize, if it is too large then DIE and inform the user.
   if($size > $max_filesize) :
       $message = 'The file you attempted to upload is too large.';
   endif;

Solved
I had to define the variable message as empty like this
$message = “”;
before the
if (isset ($_POST[“submit”]))
is is there but without any value thanks alot guys

Here the full code working great in case anyone ever bumpe into it

<?php
     include "connection.php"; // find file (connection.php)
 $message = "";
if (isset ($_POST["submit"])) { // if post has been set/clicked run the code below
   // Configuration - Your Options
      $name = $_FILES['userfile']['name']; // get the name of the file
      $type = $_FILES['userfile']['type']; // get the type of the file
      $size = $_FILES['userfile']['size'];  // get the size of the file

      $allowed = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
      $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
      $upload_path = './images/'; // The place the files will be uploaded to (currently a 'files' directory).
   		
   		$ext = substr($name, strpos($name,'.'), strlen($name)-1); // Get the extension from the filename.

     $fileType = in_array($ext, $allowed); // add the files type inside array filetype
	
   // Check if the filetype is allowed, if not DIE and inform the user.
   if(!$fileType) :
      $message = '<br />The file you attempted to upload is not allowed.';
   endif;

   // Now check the filesize, if it is too large then DIE and inform the user.
    if($size > $max_filesize) :
       $message = 'The file you attempted to upload is too large.';
   endif;

     $upload = is_writable($upload_path);
   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!$upload) :
        $message = 'You cannot upload to the specified directory, please CHMOD it to 777.';
   endif;


	
    $filename = time().$ext; // this will give the file current time so avoid files having the same name

  if($fileType && $size < $max_filesize && $upload) {
  // Upload the file to your specified path.
   if(move_uploaded_file($_FILES["userfile"]["tmp_name"],$upload_path . $filename)){

   $query = "INSERT INTO animals (id,  image)
                    VALUES ('',  '$filename')";

                    mysql_query($query) or

                    die (mysql_error());
					

         echo time(). ' Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>';
		
	 $current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
		 // It worked.
   }}
  //    else
   //      echo 'There was an error during the file upload.  Please try again.'; // It failed :(.
//http://stackoverflow.com/questions/2666882/how-to-avoid-resending-data-on-refresh-in-php

//scape string http://stackoverflow.com/questions/13034868/form-to-insert-data-in-database-works-but-does-not-show-success-page
		
}

?>

<form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<h2>Upload an image</h2>

Upload an image: <br /><INPUT type="file" name="userfile">
<br />
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $message;  ?>

Glad you got it working.