Results 1 to 19 of 19
  1. #1
    Join Date
    Oct 2005
    Posts
    72

    Creating an 'Upload Image' Form

    Does anyone know how to create a form that will allow users to upload photos to a website?


    If possible, I would like for users to be able to upload additional information such as name, email address etc (just like a regular web form).

  2. #2
    Join Date
    Dec 2004
    Posts
    55
    Well some more info would be helpful...what lang. php, asp, etc? Either way it would be pretty easy to build the form and have it database the information.

  3. #3
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Here's the basics. The trick is in setting the correct "enctype". It's a regular form, so you can add any other fields (like an email field) that you want. As sourcer said, what you do with the form is another matter entirely, depending on your server-side language.

    HTML Code:
    <form id="mainform" enctype="multipart/form-data" action="/path/to/uploadhandler" method="post" >
    <label for="imageupload">Image file:</label>
    <input name="imageupload" id="imageupload" type="file" /><br />
    <input name="submit" id="submit" type="submit" value="submit" </form>

  4. #4
    Join Date
    Oct 2005
    Posts
    72
    I will probably code this in PHP. But I have no idea where to start.. I'm kind of new with PHP and databases.

  5. #5
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Quote Originally Posted by Aristotl3
    I will probably code this in PHP. But I have no idea where to start.. I'm kind of new with PHP and databases.
    Exactly how new? I mean, can you code an HTML form, have you written "hello world" in PHP, etc. I've outlined some basic first steps below.

    First, create a basic web form (based on what I posted previously) and add in all the extra fields you want. Don't forget to set the name of the file in the form's "action" attribute to the name of the file you create in the next step:

    Next, create a basic php file that checks to see if the form was posted, and if so, print out the $_POST variables. That way you can actually see that you got some info. Basically, something like this:

    PHP Code:
    <?
          
    // if "submit" button was pressed, process the form
          
    if ($_POST['submit'] == 'submit')
         {
                foreach (
    $_POST as $postvar)
                      echo 
    htmlentities($postvar), '<br />';
         }
    ?>
    Next, you'll need to handle the image upload. For this, I recommend reading the online PHP documentation, because they have a whole section dedicated to explaining how to do this, along with wiki-style comments from users containing lots of tips and useful code.

    I *think* this should be enough to get you going.

  6. #6
    Join Date
    Oct 2005
    Posts
    72
    Ok.. I found some PHP code that will allow me to upload images. The only problem is that I that there is not an area for users to enter their information (ie - name, email address etc.). Is there any way I can add this to the upload image form??

    Or maybe have a 2 step process (step 1 would be entering your info, step 2 would be uploading the image)?



    Here is the code I am using for the upload image form:

    <?php
    //define a maxim size for the uploaded images in Kb
    define ("MAX_SIZE","100");

    //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
    function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }

    //This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['Submit']))
    {
    //reads the name of the file the user submitted for uploading
    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image)
    {
    //get the original name of the file from the clients machine
    $filename = stripslashes($_FILES['image']['name']);
    //get the extension of the file in a lower case format
    $extension = getExtension($filename);
    $extension = strtolower($extension);
    //if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
    {
    //print error message
    echo '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else
    {
    //get the size of the image in bytes
    //$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
    $size=filesize($_FILES['image']['tmp_name']);

    //compare the size with the maxim size we defined and print error if bigger
    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    //we will give an unique name, for example the time in unix time format
    $image_name=time().'.'.$extension;
    //the new name will be containing the full path where will be stored (images folder)
    $newname="images/".$image_name;
    //we verify if the image has been uploaded, and print error instead
    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }}}}

    //If no errors registred, print the success message
    if(isset($_POST['Submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully! Try again!</h1>";
    }

    ?>

    <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
    <form name="newad" method="post" enctype="multipart/form-data" action="">
    <table>
    <tr><td><input type="file" name="image"></td></tr>
    <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
    </table>
    </form>

  7. #7
    Join Date
    Oct 2005
    Posts
    72
    I just ran into another problem with this script... the files are renamed when they are placed on the server - is there a way to turn this off?

  8. #8
    Join Date
    Oct 2005
    Posts
    72
    ok.. so I figured out that the files were being renamed with a unix timecode... I fixed that part so that the file name stays the same.. but I still can't figure out how to add seperate fields for contact information. Anyone know of a solution???

  9. #9
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    1. Add two lines like this to the form:

    PHP Code:
    <label for="username">name: </label><input name="username" id="username" type="text" size="15" value="" /><br />
    <
    label for="email">email: </label><input name="email" id="email" type="text" size="15" value="" /><br /> 
    2. In your PHP code, the values will be here (after the form has uploaded):

    PHP Code:
    $username $_POST['username'];
    $email $_POST['email']; 

  10. #10
    Join Date
    Oct 2005
    Posts
    72
    I tried this and it did not work - the image uploads but not the text info.. This is what the basic form looks like:

    <form name="newad" method="post" enctype="multipart/form-data" action="">
    <table>
    <tr><td><input type="file" name="image"></td></tr>
    <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
    </table>
    </form>


    Since the submit button is for uploading the photo - the text information (name, email) is not gathered. However, I have the php code and the form on the same PHP page - does this make any difference?

  11. #11
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    That's not exactly the best image upload code you're working with there, but I guess it'll do.

    The submit button works for the entire form -- including text fields. Behind the scenes, PHP takes the uploaded file information and processes it, and then puts the non-file field values in the $_POST array.

    Having it all on the same page (rather, in the same file) is fine.

    Here's Your form with an email field added:

    PHP Code:
    <form name="newad" method="post" enctype="multipart/form-data" action="">
    <
    table>
    <
    tr><td><input type="file" name="image"></td></tr>
    <
    tr><td>Email: <input name="email" id="email" type="text" size="15" value="" /></td></tr>
    <
    tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
    </
    table>
    </
    form
    You can test it with this:
    PHP Code:
    if ($_POST['email'])
     echo 
    '<h1>Your email: ' htmlentities(trim($_POST['email'])) . '</h1>'

  12. #12
    Join Date
    Oct 2005
    Posts
    72
    hmm

    Well, the picture is uploading fine, but I am still not seeing the text anywhere. The images are being uploaded the a 'images' folder on the server... shouldn't the text info go in this area as well?

    Also, do you know where I could find a better PHP script than this one? This one was the only one that I could find that was easy to set up.. (since I am a PHP novice)

    thanks

  13. #13
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Quote Originally Posted by Aristotl3
    hmm

    Well, the picture is uploading fine, but I am still not seeing the text anywhere. The images are being uploaded the a 'images' folder on the server... shouldn't the text info go in this area as well?
    Errrrr....it doesn't quite work that way I've created and deployed numerous upload forms containing file fields and input fields, and the non-file information gets through fine and is placed in the $_POST array. It can be done.

    Where in your code are you checking (and echoing out) the $_POST value for the email input field (assuming you typed in the code I posted)?

    Also, do you know where I could find a better PHP script than this one? This one was the only one that I could find that was easy to set up.. (since I am a PHP novice)
    thanks
    If you're looking for a complete file upload site script, the one by celerondude is very popular. It's the foundation behind many, many image upload sites. He's spent years working out all the kinks.

    If you're just trying to create a simple file upload form, you can start with what you already have, but need to fix two things:

    1. File type detection: don't rely on the file extention, which can easily be spoofed. Instead, use mime_content_type(). Documentation page is here: http://us3.php.net/manual/en/functio...ntent-type.php

    2. Handling the upload: don't use copy(). Instead, use is_uploaded_file() and move_uploaded_file(). An example with complete working code is on the php site here: http://us3.php.net/manual/en/features.file-upload.php

  14. #14
    Join Date
    Oct 2005
    Posts
    72
    Here is all of the code I am using:

    <?php
    //define a maxim size for the uploaded images in Kb
    define ("MAX_SIZE","6500");

    //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
    function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }

    //This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['Submit']))
    {
    $username = $_POST['username'];
    $email = $_POST['email'];
    //reads the name of the file the user submitted for uploading
    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image)
    {
    //get the original name of the file from the clients machine
    $filename = stripslashes($_FILES['image']['name']);
    //get the extension of the file in a lower case format
    $extension = getExtension($filename);
    $extension = strtolower($extension);
    //if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "eps") && ($extension != "gif"))
    {
    //print error message
    echo '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else
    {
    //get the size of the image in bytes
    //$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
    $size=filesize($_FILES['image']['tmp_name']);

    //compare the size with the maxim size we defined and print error if bigger
    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    //we will give an unique name, for example the time in unix time format
    $image_name=$filename;
    //the new name will be containing the full path where will be stored (images folder)
    $newname="images/".$image_name;
    //we verify if the image has been uploaded, and print error instead
    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }}}}

    //If no errors registred, print the success message
    if(isset($_POST['Submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully! Thanks.</h1>";
    }

    ?>

    <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
    <form name="newad" method="post" enctype="multipart/form-data" action="">
    <table>
    <tr><td><input type="file" name="image"></td></tr>
    <tr><td>Email: <input name="email" id="email" type="text" size="15" value="" /></td></tr>
    <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
    </table>
    </form>

  15. #15
    I'm working on a "private" image uploader so that my father can upload images to a database without knowing anything whatsoever about code/databases.

    How would I go about password protecting a form so that not just anybody could upload a photo (I will put it in a hidden folder obviously, but for added security)?

  16. #16
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    @Aristotl3 - it might take a while for me to get the time to actually modify the code, if that's what you're hoping for here. Possibly this weekend, but no guarantees.

    @Jon_W - this should go in its own thread, but here's a quick answer:

    1. add a password field to your form:

    PHP Code:
    Enter Password: <input type="password" size="25" name="pw" id="pw" /> 
    2. in your form handling script (which I assume is in PHP because you posted in a PHP thread), check the value:

    PHP Code:
    <?
        
    if (($_POST['pw']) && (trim($_POST['pw']) == 'secret_password'))
       {
            
    // all is well; handle the upload, etc.
       
    }
       else
       {
          
    // bad password; do whatever you want, like print an error and then exit
          
    echo 'Invalid password.  File upload cancelled.';
          exit;
       }
    ?>

  17. #17
    Join Date
    Oct 2005
    Posts
    72
    thanks for the help sea otter. I was able to install the script by Celerondude and it works perfectly! This is exactly what I was looking for.. now if I could just figure out how to modify the template files (saved as .tpl)

  18. #18
    Join Date
    May 2004
    Location
    NYC
    Posts
    793
    Ah, good. Sorry -- I lost track of this thread, because normally such discussions are in the programming forum and not the web design forum.

    If I recall, celerondude has a discussion forum on his site. Skinning his script might be covered there.

  19. #19
    Good day Jon W

    I used your upload script the browser showed my file but when i pressed the submit button the image did not appear. Please advise .


    thank you
    leecsone

  20. Newsletters

    Subscribe Now & Get The WHT Quick Start Guide!

Posting Permissions

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