• 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: , , , , , , , , , , , , , , , , , ,

4 Responses

WP_Orange_Techno

Leave a Comment

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