[PHP] Creating a File Upload Script

o0slowpaul0o

New Member
Messages
254
Reaction score
0
Points
0
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>
 

Tyler

Retired Staff
Messages
8,564
Reaction score
0
Points
0
Re: Creating a File Upload Script

Thanks for that, I was actually just wanting to make one of those!!
 

trev

Member
Prime Account
Messages
670
Reaction score
0
Points
16
Re: Creating a File Upload Script

This is a very cool script thanks alot
 

n4tec

Active Member
Messages
3,312
Reaction score
0
Points
36
Re: Creating a File Upload Script

cool script..

*4*
 

Origin

New Member
Messages
1,082
Reaction score
0
Points
0
Re: Creating a File Upload Script

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

o0slowpaul0o

New Member
Messages
254
Reaction score
0
Points
0
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.
 

o0slowpaul0o

New Member
Messages
254
Reaction score
0
Points
0
Re: Creating a File Upload Script

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

Conquester777

New Member
Messages
180
Reaction score
0
Points
0
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>';

?>
 

Corey

I Break Things
Staff member
Messages
34,553
Reaction score
203
Points
63
Re: Creating a File Upload Script

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

Please give credit in the post when it comes from some where else :grin:
 

Bryon

I Fix Things
Messages
8,149
Reaction score
101
Points
48
"This" has happened more then once now.. You take a tutorial from another site and act as if it if yours. Just give credit to the people who make/made them, it's not that hard.

To get back on topic.. I found a nice file upload function/form on php.net. All you have to do is echo teh function, and it's all set up nice. Has multiple options for the "amount" of files, teh directory, the max upload size, etc. Let me check.


Edit:



dmsuperman at comcast dot net
26-Apr-2005 11:00 I needed a file uploader for a client a little while ago, then the client didn't want it, so I'll share with all of you. I know I hated coding it, it was confusing (for me anyway), but I made it fairly simple to use:


PHP:
<?
function uploader($num_of_uploads=1, $file_types_array=array("txt"), $max_file_size=1048576, $upload_dir=""){
  if(!is_numeric($max_file_size)){
    $max_file_size = 1048576;
  }
  if(!isset($_POST["submitted"])){
$form = "<form action='".$PHP_SELF."' method='post' enctype='multipart/form-data'>Upload files:<br /><input type='hidden' name='submitted' value='TRUE' id='".time()."'><input type='hidden' name='MAX_FILE_SIZE' value='".$max_file_size."'>";
    for($x=0;$x<$num_of_uploads;$x++){
	  $form .= "<input type='file' name='file[]'><font color='red'>*</font><br />";
    }
$form .= "<input type='submit' value='Upload'><br /><font color='red'>*</font>Maximum file length (minus extension) is 15 characters. Anything over that will be cut to only 15 characters. Valid file type(s): ";
    for($x=0;$x<count($file_types_array);$x++){
	  if($x<count($file_types_array)-1){
	    $form .= $file_types_array[$x].", ";
	  }else{
	    $form .= $file_types_array[$x].".";
	  }
    }
    $form .= "</form>";
    echo($form);
  }else{
    foreach($_FILES["file"]["error"] as $key => $value){
	  if($_FILES["file"]["name"][$key]!=""){
	    if($value==UPLOAD_ERR_OK){
		  $origfilename = $_FILES["file"]["name"][$key];
		  $filename = explode(".", $_FILES["file"]["name"][$key]);
		  $filenameext = $filename[count($filename)-1];
		  unset($filename[count($filename)-1]);
		  $filename = implode(".", $filename);
		  $filename = substr($filename, 0, 15).".".$filenameext;
		  $file_ext_allow = FALSE;
		  for($x=0;$x<count($file_types_array);$x++){
		    if($filenameext==$file_types_array[$x]){
			  $file_ext_allow = TRUE;
		    }
		  }
		  if($file_ext_allow){
		    if($_FILES["file"]["size"][$key]<$max_file_size){
			 if(move_uploaded_file($_FILES["file"]["tmp_name"][$key], $upload_dir.$filename)){
			 echo("File uploaded successfully. - <a href='".$upload_dir.$filename."' target='_blank'>".$filename."</a><br />");
			  }else{
			 echo($origfilename." was not successfully uploaded<br />");
			  }
		    }else{
			 echo($origfilename." was too big, not uploaded<br />");
		    }
		  }else{
		 echo($origfilename." had an invalid file extension, not uploaded<br />");
		  }
	    }else{
		  echo($origfilename." was not successfully uploaded<br />");
	    }
	  }
    }
  }
}
?>

uploader([int num_uploads [, arr file_types [, int file_size [, str upload_dir ]]]]);

num_uploads = Number of uploads to handle at once.

file_types = An array of all the file types you wish to use. The default is txt only.

file_size = The maximum file size of EACH file. A non-number will results in using the default 1mb filesize.

upload_dir = The directory to upload to, make sure this ends with a /

This functions echo()'s the whole uploader, and submits to itself, you need not do a thing but put uploader(); to have a simple 1 file upload with all defaults.

http://us2.php.net/manual/en/features.file-upload.php#52268
 
Last edited:

Aswin

New Member
Messages
12
Reaction score
0
Points
0
very nice tutorials thx but is there any way to learn php as i m a newbie :(
 

Bryon

I Fix Things
Messages
8,149
Reaction score
101
Points
48
phpfreaks.com
php.net

Both will help you if your serious...
 

Mani5

New Member
Messages
946
Reaction score
0
Points
0
nice! all u guyz who ever copied it off a site (i dont care) and whoever is da author od da script..

Thanx!
 
Last edited:
Top