• 05Apr

    This tutorial goes over the concept of uploading files, and keeping records in a MySQL database.
    So lets try this
    When: I need to upload files and keep long term records on who uploaded and where it is.
    Why: I don’t know, you make up the reasons.
    What: Exactly do you need to keep record of? Time, who sent it, where is it?
    Who: Depends on how you implement
    Where: On the Internet!
    How: I’ll show you.

    There are two parts, so pay attention closely. (The last part is always the most important) Don’t forget to see more of this post for the sources and part two!


    So first we need to make our uploading page. It is pretty much an XHTML template base with an uploading form

    <!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.0 Transitional//EN”>
    <html>
    <head>
            <link href=“main.css” type=“text/css” media=“screen” rel=“stylesheet”/>
            <title>Upload Index</title>
    </head>

    <body>
    <form enctype=“multipart/form-data” action=“upload.php” method=“post”>
            Choose your file to upload!
            <input name=“uploadedfile” type=“file” />
            <br />
            And what would you like to call it? <input name=“title” type=“text” />
            <br />
            <input type=“submit” value=“upload file”/>
            </form>

    </body>
    </html>

    The most important part is the input for the file, the submit button and the form itself. In this case we have to say that there are multiple parts(the text, and the file) for this file upload so we set the enctype to “multipart/form-data”.
    Since we are sending to another page(upload.php), we need to process it.
    In upload.php, the basic way to save the file to the uploads directory is like the following(not final)

    <?php

    //time to see if the file is uploaded.
    $putItAt "uploads/".basename($_FILES['uploadedfile']['name']);
    //hmm, will they try uploading a script or a page that might be a security risk?
    //lets prevent any .php from getting in, and rename with .txt
    $putItAt str_replace("php","txt"$putItAt);
    if(
    move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$putItAt)){
        
    //we could echo, but why don't we just go to the file list now?
        
    savedata();
        
    header("location: listfiles.php");//redirect them to the listfiles.php page
        
        
    }else{
        
    //we failed. Lets try a slightly different method here. instead of moving, try copying
        
    if(copy($_FILES['uploadedfile']['tmp_name'],$putItAt)){
            
    //we have success!
            
    savedata();
            
    header("location: listfiles.php");
        }else{
            
    //we totally failed... so lets tell them.
            
    echo 'You totally failed. click <a href="index.php">here</a> to go back and try again.';
        }
    }
    ?>

    Next it is noticed that we aren’t saving any information in the database. Here comes the MySQL part.
    Make your table in the database, call it what ever you want, in my case I named it ‘thefiles’. The requirement is that we connect to the database and set our script up to be able to query in and for information.
    $link mysql_connect('localhost''phpuser''phppass');
    if (!
    $link) {
        die(
    'Could not connect: ' mysql_error());
    }
    //WE NEED to select the database!
    mysql_selectdb("tutorials_upload");

    By putting that at the top of our script, we now have a connection to the database so now we want to insert our information when it is uploaded. Now the question is: do we want to be redundant and have the inserting code twice(for copy and move), or do we want to make a function and refer to that function twice? Honestly I choose the later, it makes the code cleaner.

    //function time!
    function savedata(){
        global 
    $_FILES$_POST$putItAt;
        
    $sql "INSERT INTO `tutorials_upload`.`thefiles` (
    `ID` ,
    `Time` ,
    `FileLocation` ,
    `IP` ,
    `Title`
    )
    VALUES (
    NULL , UNIX_TIMESTAMP( ) , '"
    .mysql_real_escape_string($putItAt)."', '".$_SERVER['REMOTE_ADDR']."', '".mysql_real_escape_string($_POST['title'])."'
    );"
    ;
    mysql_query($sql);
        
    }

    So now that I have this function, I need to implement it into the uploading code.
    So, now my code finally for upload.php is

    <?php
    $link 
    mysql_connect('localhost''phpuser''phppass');
    if (!
    $link) {
        die(
    'Could not connect: ' mysql_error());
    }
    //WE NEED to select the database!
    mysql_selectdb("tutorials_upload");
    if(!
    is_dir("uploads")){//do we need to make the uploads directory for the files?
        
    mkdir("uploads");//make the rest of the script safe, though this will only be done once
        
    }
    //function time!
    function savedata(){
        global 
    $_FILES$_POST$putItAt;
        
    $sql "INSERT INTO `tutorials_upload`.`thefiles` (
    `ID` ,
    `Time` ,
    `FileLocation` ,
    `IP` ,
    `Title`
    )
    VALUES (
    NULL , UNIX_TIMESTAMP( ) , '"
    .mysql_real_escape_string($putItAt)."', '".$_SERVER['REMOTE_ADDR']."', '".mysql_real_escape_string($_POST['title'])."'
    );"
    ;
    mysql_query($sql);
        
    }
    //time to see if the file is uploaded.
    $putItAt "uploads/".basename($_FILES['uploadedfile']['name']);
    //hmm, will they try uploading a script or a page that might be a security risk?
    //lets prevent any .php from getting in, and rename with .txt
    $putItAt str_replace("php","txt"$putItAt);
    if(
    move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$putItAt)){
        
    //we could echo, but why don't we just go to the file list now?
        
    savedata();
        
    header("location: listfiles.php");//redirect them to the listfiles.php page
        
        
    }else{
        
    //we failed. Lets try a slightly different method here. instead of moving, try copying
        
    if(copy($_FILES['uploadedfile']['tmp_name'],$putItAt)){
            
    //we have success!
            
    savedata();
            
    header("location: listfiles.php");
        }else{
            
    //we totally failed... so lets tell them.
            
    echo 'You totally failed. click <a href="index.php">here</a> to go back and try again.';
        }
    }
    ?>

    Next, we have our file list page. We will start off with a basic XHTML template and have a CSS file linked in.

    < !DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.0 Transitional//EN”>
    <html>
    <head>
            <link href=“main.css” type=“text/css” media=“screen” rel=“stylesheet”/>
        <title>Uploaded Files</title>
    </head>

    <body>

    <br />
    <a href=“index.php”>Go back to the index</a>
    </body>
    </html>

    The main.css has

    ul li {
        display: block;
        width: 160px;
        min-height: 160px;
        border: thin dashed black;
        float: left;
        padding: 8px;
    }
    ul {
        clear: both;
    }
    br {
        clear: left;
    }

    in it, which pretty much makes our list items boxes with a dashed border around them.

    So the format I want to use is something like

    <ul>
    <li>
        <h1>YYYYYYY</h1><br />
        <h3>Uploaded By: XXX.XXX.XXX.XXX</h3><br />
        <a href=“uploads/ZZZZZZZ.jpg”>YYYYYYY</a>
    </li>
    </ul>

    So, in php, I would query the database for ‘thefiles’ and display the information in the like format.

    <?php
    //time to get our info
    $sql "SELECT * FROM `thefiles`";
    $result mysql_query($sql);
    while(
    $file mysql_fetch_array($result)){
        echo 
    '<li>';
        echo 
    '<h1>'.$file['Title'].'</h1><br />';
        
    //now the file info and link
        
    echo '<h3>Uploaded By: '.$file['IP'].'</h3><br />';
        echo 
    '<a href="'.$file['FileLocation'].'">'.$file['Title'].'</a>';
        echo 
    '</li>';
    }
    ?>


    So, finally, our listfiles.php looks like (along with the MySQL connection section) this:

    <?php
    $link 
    mysql_connect('localhost''phpuser''phppass');
    if (!
    $link) {
        die(
    'Could not connect: ' mysql_error());
    }
    //WE NEED to select the database!
    mysql_selectdb("tutorials_upload");
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
            <link href="main.css" type="text/css" media="screen" rel="stylesheet"/>
        <title>Uploaded Files</title>
    </head>
    <body>
    <ul>
    <?php
    //time to get our info
    $sql "SELECT * FROM `thefiles`";
    $result mysql_query($sql);
    while(
    $file mysql_fetch_array($result)){
        echo 
    '<li>';
        echo 
    '<h1>'.$file['Title'].'</h1><br />';
        
    //now the file info and link
        
    echo '<h3>Uploaded By: '.$file['IP'].'</h3><br />';
        echo 
    '<a href="'.$file['FileLocation'].'">'.$file['Title'].'</a>';
        echo 
    '</li>';
    }
    ?>
    </ul>

    <br />
    <a href="index.php">Go back to the index</a>
    </body>
    </html>

    All that put together provides something that looks like
    Upload form
    and ends with
    File list

    Posted by Kloplop321 @ 7:15 pm

    Tags: , , , , , , , , , , , , , , , , , ,

20 Responses

WP_Orange_Techno
  • rafi Says:

    its a nice tutorial a bit to fast

    thanks

  • rafi Says:

    Browse and upload battens are missing

    way?

  • Kloplop321 Says:

    @rafi, I’m not sure what you mean by ‘Browse and upload battens are missing’ I assume you mean upload patterns, but still. Are you referring to a file list for what has been uploaded?

  • karol Says:

    nice one, it works i had been looking for File Upload system with records in MySQL for ages. Good work Kloplop

  • Dana Says:

    Great tutorial! I am still a php beginner, and I have a need to do something VERY similar to this for a friend of mine. She owns her own photography business, and I want to be able to allow her to upload client proofs, but this could get very tedious doing this one picture at a time. Is there any way to allow multiple uploads? How would I modify your script?

    Thanks!

    Dana

  • Kloplop321 Says:

    Sorry, I saw your comment within 20 minutes, but forgot about it half an hour later. What you want to do is name the upload input element(as in name=”uploadfile”) to something like uploadfile[]
    Then, count($_REQUEST['uploadfile'])
    and perform the upload accordingly from uploadfile[0] to uploadfile[count - 1]
    So that means you should also make a way to have more upload fields in your html.
    If you do a google search, there are many wonderful examples. However, this is a great idea for a tutorial I might make some day.

  • RR Says:

    hi i have a problem with your code especially uploading larger size of file.

    Notice: Undefined index: uploadedfile in C:\wamp\www\document\upload.php on line 25

    Notice: Undefined index: uploadedfile in C:\wamp\www\document\upload.php on line 29

    Notice: Undefined index: uploadedfile in C:\wamp\www\document\upload.php on line 37

    Warning: copy() [function.copy]: Filename cannot be empty in C:\wamp\www\document\upload.php on line 37
    You totally failed. click here to go back and try again.

    upload.php same code to your tutorial. i’m trying to upload larger file.

  • Kloplop321 Says:

    Either it is that you aren’t using the exact line for the form settings: enctype=”multipart/form-data” action=”upload.php” method=”post”
    Or, your PHP configuration does not allow you to upload files, Or your PHP configuration is ignoring the file because it is too large.
    On the page
    http://forums.devarticles.com/general-programming-help-4/files-userfile-tmp-name-not-working-1454.html
    The last post says “The problem was my file was bigger than the MAX_FILE_SIZE. Silly me.” so check your php settings to see what it is set to.

  • Liam Says:

    Thanks sooo much for this tutorial, helped me out alot. You are a god. I learn pretty quickly and by watching this tutorial only I learnt basic php and how it’s set out, surprisingly alike to c or c++. LOVE IT MAN <3 maybe more tutorials on maybe things like after that a more advanced view page like a music player for it once you get the link, well thanks heaps man :)

  • Preston Todd Says:

    PHP Tutorials By Kloplop321 » Blog Archive » PHP & MySQL Tutorial 09: File Upload system with records in MySQL is an interesting name for a blog, keep up the good work, thanks, from Preston Todd

  • suthagar Says:

    hi mate!

    i am beginner of php and i try to write code in several way for uploading file. i got the same error each time. finally i copied your code and tried. even-though i got same error.

    could you please find out the solution.

    the error as follows

    Warning: move_uploaded_file(uploads/myname.rtf) [function.move-uploaded-file]: failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/upload/uploading.php on line 33

    Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘/Applications/XAMPP/xamppfiles/temp/phpjMuJGA’ to ‘uploads/myname.rtf’ in /Applications/XAMPP/xamppfiles/htdocs/upload/uploading.php on line 33

    Warning: copy(uploads/myname.rtf) [function.copy]: failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/upload/uploading.php on line 41
    You totally failed. click here to go back and try again.

    i understand that i need to do some setting somewhere. but i dont know how to do it.

    i am using Mac operating system. and using XAMPP.

    could you please write me where should i do some setting for permission ?

    thank you

  • joe Says:

    thanks for the code. its working ok. but how do i check if the file i want to upload is already uploaded at the same location i want to upload my file. waiting to hear from you soon

  • Kloplop321 Says:

    you can do something like
    if(!file_exists(“location/for/uploads/”.$_FILE["uploadedfile"]['name'])){
    //continue to save over it..
    }
    However, this is after they have already sent the web page, so the file is in a temporary folder on the server at this point.

  • joe Says:

    thanks a lot. i appreciate. God bless you.

  • jimmyo88 Says:

    Heya mate, brilliant tutorial, has been very helpful. Could you please do a follow on about deleting files as well?

  • Kloplop321 Says:

    Sure, but if you want the answer quickly, the way to delete a file is
    unlink($pathToFile)

  • Kanna Ng Says:

    I would like to insert into thefiles table the title without move or copy file to uploads folder. When needed i will alter value of the record then move or copy file to uploads folder. what could i do with the Filename because: Warning: copy() [function.copy]: Filename cannot be empty in C:\wamp\www\PHP-Login\upload.php on line

  • Andras Says:

    Hi I get blank filelocation, any solution using something instead basename to get the file location?

  • Kloplop321 Says:

    basename does NOT return the file location, basename returns the name of the file, it searches for the last slash in the value you give it, and then gives you what ever is after that(the file name)
    If you are giving it a directory, with a / at the end, it will return nothing.

  • Andras Says:

    Thanks Kloplop, I find the problem finally, I put the global $_FILES, $_POST, $upfile; at the wrong place. NO it works thanks a lot mate!

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.