Upload PHP Script

Welcome,
In this short tutorial I will show you how to create an upload php script. The documentation contains 4 simple steps which will teach you how to create the application. Go and start with first step, then follow the other three!

If you don't want to follow the steps you can just:
Download PHP Upload Script Files

Step 1 Creating the database table to keep uploaded files on record

We will need the following columns :
  • ID
  • filename
  • timestamp (added time)
  • ip (visitor)
Go into phpmyadmin and paste this code, which will create the table:
	CREATE TABLE `files` (
	`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
	`filename` VARCHAR( 255 ) NOT NULL ,
	`timestamp` INT NOT NULL ,
	`ip` VARCHAR( 50 ) NOT NULL
	) ENGINE = MYISAM ;
	
	

Step 2 Choosing uploaded file types allowed

Build a php array with all allowed extensions, this can be changed to whatever files types you would like users to upload.
	$allowed = array("jpeg","gif","png","bmp");
	

Step 3 Creating the php upload script

This is what you want the most. Here's how it works, first we build a simple form, then we validate the extension of uploaded file. If successfull, we go to define a folder/directory were new files will be added and finally we upload the file.
	
Choose file to upload
if(isset($_POST['sb'])) { //check for valid extension $pathInfo = pathinfo($_FILES[upload][name]); $extension = $pathInfo['extension']; //choose directory/foolder to place the file in $dir = "uploads"; if(!in_array($extension, $allowed)) die("Extension not allowed!"); if(move_uploaded_file($_FILES['upload']['tmp_name'], "$dir/".$_FILES['upload']['name'])) { print "Your new file can be viewed/download at "; }else{ print "File could not be uploaded"; } }

Step 4 Inserting uploaded file name into database

This is the final step. We'll connect & insert the filename, time when file is added and the visitor's IP address into the table we've just created earlier.
	 $DatabaseHost = "localhost";
	 $DatabaseUsername = "root";
	 $DatabasePassword = "";
	 $DatabaseName = "upload_php_script";
	
	 $connection = mysql_connect($DatabaseHost, $DatabaseUsername, $DatabasePassword) 
	 or die("Cannot connect to MySQL!");
	 mysql_select_db($DatabaseName, $connection) or die("Cannot find database!");
	 
	 $sql = "insert into files values (null, '".htmlentities($_FILES['upload']['name'])."', 'now()', '$_SERVER[REMOTE_ADDR]')";
	 $rs = mysql_query($sql);
	 
	 print mysql_error();
 
	
Toronto Web Design | web design in london | php chat software
Copyright © 2010 uploadphpscript.net