+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 18

Thread: [PHP] Creating a File Upload Script

  1. #1
    o0slowpaul0o's Avatar
    o0slowpaul0o is offline x10 Sophmore o0slowpaul0o is an unknown quantity at this point
    Join Date
    Mar 2005
    Posts
    127

    [PHP] Creating a File Upload Script

    Recently someone asked for an Upload script, so here you go, out my pure PHP.

    First we need to create the database table with the following SQL:

    Code:
    CREATE TABLE `uploads` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `whenuploaded` datetime NOT NULL default '0000-00-00 00:00:00',
    `ipaddress` varchar(15) NOT NULL default 'unknown',
    `imageloc` varchar(255) NOT NULL default 'unknown',
    `imagesize` int(10) unsigned default NULL,
    `imagetype` varchar(30) default NULL,
    PRIMARY KEY (`id`)
    ) TYPE=MyISAM;
    Then here's the PHP code you need at the top of the page where you're going to have your upload form. You need to change the database access details at the top and the 'defines' to specify your domain and path names. Create the DEST_DIR directory on the server with 777 permissions.

    Code:
    <?php
    
    define('MAX_ALLOWED_FILE_SIZE', 1024000);
    define("DEST_DIR", '/upload/1/');
    define('DEST_PATH', '/home/yourcpanelid/public_html' . DEST_DIR);
    define('DEST_URL', 'http://yourdomain.com' . DEST_DIR);
        
    $allowed_types = array("image/gif", "image/pjpeg", "image/x-png", "image/bmp");
        
    $dbhost = "localhost";
    $dbname = "yourdb_name";
    $dbuser = "yourdb_user";
    $dbpass = "yourdb_password";
    
    $errormessage = "Please enter file to be uploaded.";
        
    if ((isset($_REQUEST['form_submit'])) && ('form_uploader' == $_REQUEST['form_submit']))
    {
        $picfile_name = $_FILES['picfile']['name'];
        $picfile_type = $_FILES['picfile']['type'];
        $picfile_size = $_FILES['picfile']['size'];
        $picfile_temp = $_FILES['picfile']['tmp_name'];
            
        if (MAX_ALLOWED_FILE_SIZE >= $picfile_size)
        {
            if (in_array($picfile_type, $allowed_types))
        {
            if (is_uploaded_file($_FILES['picfile']['tmp_name']))
            {
    
                if (file_exists(DEST_PATH . $picfile_name))
                {
                    $unique_id = time();
                $picfile_name = $unique_id . '_' . $picfile_name;
                }
                        
                if (move_uploaded_file($picfile_temp, DEST_PATH . $picfile_name))
                {
                    $errormessage = "File uploaded as:
    <b>" . DEST_URL . $picfile_name . "</b>";
                            
                    if(mysql_connect($dbhost, $dbuser, $dbpass))
                {
                    if(mysql_select_db($dbname))
                    {
                    $sql1 = "INSERT INTO uploads (whenuploaded, ipaddress, imageloc, imagesize, imagetype) VALUES (";
                    $sql1 .= "'" . date("Y-m-d H:i:s") . "',";
                    $sql1 .= "'" . $_SERVER['REMOTE_ADDR'] . "',";
                    $sql1 .= "'" . DEST_DIR . $picfile_name . "',";
                    $sql1 .= "" . $picfile_size . ",";
                    $sql1 .= "'" . $picfile_type . "')";
                                    
                    if (!mysql_query($sql1))
                    {
                        $errormessage .= "
    <font color=red><b>Query failed [$sql1].</b></font>";
                    }
                    }
                    else
                    {
                        $errormessage .= "
    <font color=red><b>Could not select database.</b></font>";
                    }
                }
                else
                {
                    $errormessage .= "
    <font color=red><b>Could not connect to database.</b></font>";
                }
                }
                else
                {
                $errormessage = "<b><font color='red'>File upload failed for obscure reasons (error code: " . $_FILES['picfile']['error'] . ").</font></b>";
                }
            }
            else
            {
                $errormessage = "<b><font color='red'>No file uploaded.</font></b>";
            }
            }
            else
            {
            $errormessage = "<b><font color='red'>Invalid file type.</font></b>";
            }
        }
        else
        {
            $errormessage = "<b><font color='red'>File too big (maximum size is " . MAX_ALLOWED_FILE_SIZE .    ").</font></b>";
        }
        $_REQUEST['form_submit'] = "";
    }
    
    ?>
    And here's your form, which goes on the same page as the PHP script above.

    Code:
    <form action="<?php $PHP_SELF ?>" method="post" enctype="multipart/form-data" name="form_uploader" id="form_uploader">
    <table border="0" align="center" cellpadding="1" cellspacing="1">
       <tr>
          <td colspan="3">
             <div align="center"><?php echo $errormessage; ?></div>
          </td>
       </tr>
       <tr>
          <td>File:</td>
          <td colspan="2">
             <input name="MAX_FILE_SIZE" type="hidden" value="<?php echo MAX_ALLOWED_FILE_SIZE ?>">
        <input name="picfile" type="file" id="picfile" title="Enter the path to the file you wish to upload, or use the Browse button to get a file selection dialog." size="60" maxlength="250">
        <input name="form_submit" type="hidden" id="form_submit" value="form_uploader">
          </td>
       </tr>
       <tr>
          <td colspan="3">
             <div align="center">
            <input name="Submit" type="submit" title="Press this button to start the upload." value="Upload">
             </div>
          </td>
       </tr>
    </form>

  2. #2
    Tyler's Avatar
    Tyler is offline Retired Staff Tyler is an unknown quantity at this point
    Join Date
    Feb 2005
    Location
    Michigan, USA
    Posts
    4,282

    Re: Creating a File Upload Script

    Thanks for that, I was actually just wanting to make one of those!!
    The Sims 2 Extreme | TTECH - Work In Progress

    E-Mail Me | PM Me

  3. #3
    trev's Avatar
    trev is offline x10 Lieutenant trev is an unknown quantity at this point
    Join Date
    Feb 2005
    Location
    Guildford
    Posts
    334

    Re: Creating a File Upload Script

    This is a very cool script thanks alot
    :ughdance: ::Trev Is back:: :ughdance:
    X10Hosting is the best free host ever

  4. #4
    n4tec's Avatar
    n4tec is offline Lord Of The Keys n4tec is an unknown quantity at this point
    Join Date
    Feb 2005
    Location
    GeT NOTICED via n4tec
    Posts
    1,656

    Re: Creating a File Upload Script

    cool script..

    *4*
    .::: Regards, n4tec :::.


  5. #5
    Origin's Avatar
    Origin is offline x10 Elder Origin is an unknown quantity at this point
    Join Date
    Mar 2005
    Location
    Silicon Valley, California
    Posts
    541

    Re: Creating a File Upload Script

    Does it upload to server, or to the DB? If the former, what's the DB for?

  6. #6
    o0slowpaul0o's Avatar
    o0slowpaul0o is offline x10 Sophmore o0slowpaul0o is an unknown quantity at this point
    Join Date
    Mar 2005
    Posts
    127

    Re: Creating a File Upload Script

    Database is store the files what have been uploaded. If you delete something what has been uploaded. It will delete in the database.

  7. #7
    CheetahShrk is offline x10 Sophmore CheetahShrk is an unknown quantity at this point
    Join Date
    Mar 2005
    Posts
    102

    Re: Creating a File Upload Script

    Are you sure thats your tut?

    http://www.oxyscripts.com/item-1054.html <-- whats this then, its been posted at the site since January :P

  8. #8
    o0slowpaul0o's Avatar
    o0slowpaul0o is offline x10 Sophmore o0slowpaul0o is an unknown quantity at this point
    Join Date
    Mar 2005
    Posts
    127

    Re: Creating a File Upload Script

    Hmmm. I know. I got it from there, didn't say it was mine.

  9. #9
    Origin's Avatar
    Origin is offline x10 Elder Origin is an unknown quantity at this point
    Join Date
    Mar 2005
    Location
    Silicon Valley, California
    Posts
    541

    Re: Creating a File Upload Script

    Recently someone asked for an Upload script, so here you go, out my pure PHP.
    *AHEM*

  10. #10
    Conquester777's Avatar
    Conquester777 is offline x10Hosting Member Conquester777 is an unknown quantity at this point
    Join Date
    Mar 2005
    Location
    Vancouver, BC, Canada
    Posts
    90

    Re: Creating a File Upload Script

    if anybody wants to try my version (which i haven't really edited, but you can check it out if you like), which doesn't requier the use of a database.

    create a file called description.txt, and put the code at the bottom in to index.php

    if you want to put it in to something other than index.php, you'll have to replace all to that file name.

    also, as (pathetic) saftey control (I didn't want just anybody uploading to my site...) you have to go to index.php?id=view or something, index.php?id=upload, index.php?id=input

    Code:
    <? 
    if (!isset($id)) header('Location: http://www.circlesarefun.com/'); 
    $m_time = explode(" ",microtime());
    $m_time = $m_time[0] + $m_time[1];
    $starttime = $m_time;
    echo '<html><head><title>'.ucfirst($id).'</title>' . (($id==='view') ? '<style type="text/css">table,tr,td { border-collapse: collapse; border: 1px solid #000000; padding-left:10px; font-family: Verdana; font-size: 14px; border-left-style:dashed; border-right-style:dashed; } .i { border: 0px hidden #FFFFFF; } .i { cursor: default; } a{text-decoration:none;} a:hover {color:#FF0000;text-decoration:underline}</style>' : '' ). '</head><body>
    ';
    
    if ($id==='view') { 
    
    $dir = '.';
    
    if (is_dir($dir)) { if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false)
    
    
    { if ($file!=='.' && $file!=='..' &&  $file!=='error_log' &&  $file!=='index.php' &&  $file!=='description.txt' && $file!=='Alayna__\\\'s Journal.htm') {
    $size = filesize("$file");
    $ar_file[$file]=$size; } }
    closedir($dh); } }
    
    $filecount=count($ar_file);
    
    $handle=fopen('description.txt','rb');
    for ($i=1; !feof($handle) && $i<=99;$i++){
    $line = fgets($handle, 1024);
    $pieces[]=explode('///', $line);
    // $name_ar[]=$piece[0];
    // $desc_ar[]=$piece[1];
    for ($i2=0; $i2<$arraylength2; $i2++) { if ($pieces2[$i2]=="$ip") { $go="no"; } } 
    }
    fclose($handle);
    
    
    echo '<center><a href="index.php?id=input"><font face="Verdana" size="2">Upload More</font></a><br /><br /><table cellspacing="0" cellpadding="5" border="0" width=50%>
    <tr><td>Thumbnail</td>
    <td>Description</td><td>File Name & Size</td></tr>';
    
    foreach($ar_file as $key => $value) {
    $ext=substr($key,-3);
    echo '<tr><td align="center">';
      if ($ext=='jpg' || $ext==='JPG' || $ext=='gif' || $ext==='GIF' || $ext=='png' || $ext==='PNG' || $ext=='bmp' || $ext==='BMP' || $ext=='img' || $ext==='IMG')
      { list($width, $height, $type, $attr)=GetImageSize("$key"); if ($width>200 && $width<300 && $height<200) $wh=''; else if ($width<200 && $height<200) $wh=''; else if ($width>$height) $wh=' width="200"'; else if ($width<$height) $wh=' height="200"'; else if ($width===$height) $wh=' width="200" height="200"';
        echo "<a href=\"$key\"><img src=\"$key\"$wh class=\"i\"></a></td>";
      } else echo 'N/A</td>';
    
    foreach($pieces as $valu)
    { if ($key===$valu[0]) { $display=stripslashes($valu[1]); } } echo (isset($display)) ? "<td style=\"font-size:12px\">$display</td>" : '<td style=\"font-size:12px\">N/A</td>';
    
    echo "<td><a href=\"$key\">$key</a><div align=\"right\">$value bytes</div></td>";
    
    echo '</tr>'; unset($ok);
    } 
    
    echo '</table>';
    
    } //
    
    else if ($id==='input') { //
    
    echo '<center><form action="index.php?id=upload" method="post" ENCTYPE="multipart/form-data">
    File:<br />
    <input type="file" size="40" name="imagefile" maxlength="255">
    <input type="hidden" name="MAX_FILE_SIZE" value="500000"><br /><br />
    Description:<br /><textarea name="description" cols="40" rows="2"></textarea><br />
    <input type="submit" value="Upload">
    </form></center>';
    
    } else if ($id==='upload') { //
    
     // The complete path to where you want upload:
    $uploaddir = '/home/circlesa/public_html/upload/';
    
    if (!isset($HTTP_POST_FILES)) die('</body></html>');
    $key=$HTTP_POST_FILES['imagefile']['name'];
    $ext=substr($key,-3);
    if ($key==='.' || $key==='..' || $key==='error_log' || $key==='index.php' || $key==='description.txt' || strstr($key,"'") || $ext==='php' || $ext==='php3' || $ext==='cgi') die("Invalid File Name (No \"<b>'</b>\"'s) \n</body></html>");
    $file_realname = trim($HTTP_POST_FILES['imagefile']['name']);
    move_uploaded_file($HTTP_POST_FILES['imagefile']['tmp_name'], $uploaddir . $file_realname) or die("<!-- --></body></html>");
    
    if (isset($_POST['description'])) $description=$_POST['description']; else $description='N/A';
    if ($description==='') $description='N/A';
    $ip = getenv("REMOTE_ADDR");
    
    $key2=str_replace('///','//',$key);
    
    $description2=str_replace('///','//',$description);
    
    $handle=fopen('description.txt','a+b');
    $success=fwrite($handle,"$key2///$description2///$ip
    ");
    fclose($handle);
    
    $ext=substr($key,-3); echo '<center>';
      if ($ext=='jpg' || $ext==='JPG' || $ext=='gif' || $ext==='GIF' || $ext=='png' || $ext==='PNG' || $ext=='bmp' || $ext==='BMP' || $ext=='img' || $ext==='IMG')
      { list($width, $height, $type, $attr)=GetImageSize("$key"); if ($width<500 && $height<500) $wh=''; else if ($width>$height) $wh=' width="500"'; else if ($width<$height) $wh=' height="500"'; else if ($width===$height) $wh=' width="500" height="500"';
    echo "<img src=\"$key\"$wh class=\"i\"><br />"; }
    echo "<a href=\"$key\">$key</a><br /><br />Description:<table cellspacing=0 cellpadding=10 border=1 bordercolor=black style=\"border-collapse:collapse\"><tr><td><div align=justify>$description</div></td></tr></table><br />Upload Successful<br /><br /><a href=\"http://circlesarefun.com/upload/index.php?id=view\">View All Files</a></center>";
    
    } //
    
    
    if ($id==='view') {
    $round = 4;// The number of decimal places to round the micro time to.
    $m_time = explode(" ",microtime());
    $m_time = $m_time[0] + $m_time[1];
    $endtime = $m_time;
    $totaltime = ($endtime - $starttime);
    echo '<font size=1 face=Arial>loaded in '. round($totaltime,$round) .' seconds</font></center>'; }
    
    echo '
    </body></html>';
    
    ?>
    Somebody help you out?
    SHOP
    Click on the UK LONDON SHOP to raise their rep bar!

+ Reply to Thread
Page 1 of 2 12 LastLast

Similar Threads

  1. file upload script
    By nightscream in forum Scripts & 3rd Party Apps
    Replies: 9
    Last Post: 01-11-2011, 06:04 PM
  2. Converting a .RMVB file
    By SEŅOR in forum Off Topic
    Replies: 7
    Last Post: 06-19-2006, 03:20 PM
  3. Simple Image Upload [PHP]
    By ak007 in forum Tutorials
    Replies: 1
    Last Post: 10-10-2005, 07:11 AM
  4. Upload file size limit
    By funindia in forum Free Hosting
    Replies: 0
    Last Post: 06-05-2005, 02:06 AM
  5. Creating a Card Game Script
    By Rhianna in forum Scripts & 3rd Party Apps
    Replies: 17
    Last Post: 05-30-2005, 04:12 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers