SitePoint Sponsor

User Tag List

Results 1 to 17 of 17
  1. #1
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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?

    PHP Code:
    <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($filenamestrpos($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 :(.
    }
    ?>

  2. #2
    SitePoint Enthusiast
    Join Date
    Feb 2012
    Location
    United Kingdom
    Posts
    78
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    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:
    PHP Code:
    <input type="submit" name="submit" value="upload"

  3. #3
    SitePoint Member parkerj's Avatar
    Join Date
    Nov 2010
    Location
    Boston, MA
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  4. #4
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  5. #5
    SitePoint Member parkerj's Avatar
    Join Date
    Nov 2010
    Location
    Boston, MA
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @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:

    PHP Code:
    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.

  6. #6
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks will do

  7. #7
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @ 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.

  8. #8
    SitePoint Member parkerj's Avatar
    Join Date
    Nov 2010
    Location
    Boston, MA
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If I understand you correctly, instead of die(); do something like this:

    PHP Code:
    $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().

  9. #9
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi if I do that and add the
    <?php echo $message; ?>
    I get the classic undefined

    like this

    PHP Code:
    <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?>

  10. #10
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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 Code:
    <?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($filenamestrpos($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;  ?>

  11. #11
    SitePoint Member parkerj's Avatar
    Join Date
    Nov 2010
    Location
    Boston, MA
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @macaela, this should get you close to where you want to be:

    PHP Code:
    <?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($namestrpos($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>

  12. #12
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi shows two problem one $message not set
    Notice: Undefined variable: message in C:\xampp\htdocs\neusa\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 Code:
    <?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($namestrpos($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>

  13. #13
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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\neusa\upload\index.php on line 60
    How can I define if is set right at teh bottom of the script?

  14. #14
    SitePoint Member parkerj's Avatar
    Join Date
    Nov 2010
    Location
    Boston, MA
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  15. #15
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Does on linux if first validation fails doesnt run second one? like
    PHP Code:
     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; 

  16. #16
    SitePoint Addict
    Join Date
    Apr 2010
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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 Code:
    <?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($namestrpos($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;  ?>

  17. #17
    SitePoint Member parkerj's Avatar
    Join Date
    Nov 2010
    Location
    Boston, MA
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Glad you got it working.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •