loading comments

Creating a PHP File/Image Uploader

Posted on: January 10, 2009 Categories: PHP, Tutorials, Uploaders
PHP logo

Uploaders are scripts that give a user the ability to upload a file/image to a certain space defined in the script that runs the uploader, im sure the websites such as Imageshack and Photobucket are familiar to you, and there many services out there, but wouldn’t it be nice to create your own little uploader service? Well in this tutorial you will create a small uploader that is quick, easy and customizable to your liking. Includes a great little feature that generates embed codes for you.

Step 1: Preparation

All you going to need is a code editor that you will be able to save .php extension files in and just any code editor that you type html in, nothing to high spec really. You are also going to need to create two documents for the uploader to work these are index.php and uploader.php

Step 2: The PHP Functions (uploader.php)

The PHP functions are of course the life blood of this script and all the functions written on the uploader.php page will be used to process a upload. Lets dive in:

<?
   // Config upload options
      define("ALL_LOWERCASE", true);  // Fixes a bug with capitalised file extensions
      $allowed_filetypes = array('.jpg', '.jpeg','.gif','.bmp','.png', '.ico','.JPG','.PNG','.JPEG','.GIF','.ICO','.BMP',); // These will be the types of file that will pass the validation.
      $max_filesize = 2097152; // Maximum filesize in BYTES (currently 2.0MB).
      $upload_path = 'upload/'; // The place the files will be uploaded to (currently a 'upload' directory, remember it needs to be CHMOD 777).

   $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.

   // Checks file extension thats requested to be uploaded compared to the allowed_filetypes array, if allowed continue. If not on the allow list, DISPLAY ERROR 1
   if(!in_array($ext,$allowed_filetypes))
      die('<h3>OOPS!</h3>
	  <p>The file you attemped to upload is not allowed, make sure the file is on the allowed list and try again.</p>'); // ERROR 1

   // Checks file size to make sure it is below the maximum set by the max_filesize array. If under set value (Currently 2.0 MB) continue. If larger then set value, DISPLAY ERROR 2
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('<h3>OOPS!</h3>
	  <p>The image you attempted to upload is too large.</p>'); // ERROR 2

   // Confirms the existance and access to the upload directory (Where uploads will be stored) if directory set is writable upload will process. If directory set doesn't exist or isn't accesible, DISPLAY PROCESS ERROR 1
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.'); // PROCESS ERROR 1

   // Uploader will upload the requested file to the path given.
   if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))

   // Upload successful, final step, generate embed codes. (My URL structure e.g. http://www.james-blogs.com/wp-content/tutorials/uploader/ is present in this code at the moment as in order to test out the uploader and embed codes yourself (For the live preview) I've set it up fully. Edit them to your website url and directories etc.. when you set it up on your own web-server

         echo '<h3>The Upload was successful</h3>
		 <p><strong>Your image upload of <em>'. $filename . '</em> was successful:</strong></p>
		 <img src="http://www.james-blogs.com/wp-content/tutorials/uploader/'.$upload_path.$filename.' " "alt="uploaded image"/>
		<p><strong>Your uploaded image is now live on our servers, scroll down below to obtain the URL to your file. Optionally you can use one of the embed methods which have been generated for you.</strong></p>
		 <table border="0" cellspacing="10" cellpadding=0">
		 <tr>
		 <td>If you just need the general link to your uploaded image then use this code below:</td>
		 </tr>
		 <tr>
         <td><strong>Direct link to image</strong>:<br/> <textarea cols="35" rows="3">http://www.james-blogs.com/wp-content/tutorials/uploader/'.$upload_path.$filename.'</textarea></td>
         </tr>
		 </table>
		 <table border="0" cellspacing="10" cellpadding="0">
		 <tr>
		 <td>If you have uploaded this image and need it embedding in a forum post then use the codes generated below!</td>
		 </tr>
		 <tr>
		 <td><strong>Embedding the image in a forum:</strong><br/> <textarea cols="35" rows="3">[IMG]http://www.james-blogs.com/wp-content/tutorials/uploader/'.$upload_path.$filename.'[/IMG]</textarea></td>
		 </tr>
		 </table>
		 <table border="0" cellspacing="10" cellpadding="0">
		 <tr>
		 <td>If you want to make your images have a hyperlink on a forum or website then use these codes:</td>
		 </tr>
		 <tr>
		 <td>
		 <strong>Hotlink for forums 1</strong>:<br/> <textarea cols="35" rows="3">[URL=http://yourlinkhere.com][IMG=http://www.james-blogs.com/wp-content/tutorials/uploader/'.$upload_path.$filename.'[/IMG][/URL]</textarea></td>
		 </tr>
		 <tr>
		 <td>
		 <strong>Hotlink for forums 2</strong>:<br/> <textarea cols="35" rows="3">[url=http://yourlinkhere.com][img=http://www.james-blogs.com/wp-content/tutorials/uploader/'.$upload_path.$filename.'[/img][/url]</textarea></td>
		 </tr>
		 <tr>
		 <td>
		 <strong>Hotlink for Websites</strong>:<br/> <textarea cols="35" rows="3"><a href="http://yourlinkhere.com"><img src="http://www.james-blogs.com/wp-content/tutorials/uploader/'.$upload_path.$filename.'" border="0" alt="image hosted at Pulse GFX"/></a></textarea></td>
         </tr>
         </table>
		 ';
      else
         echo '<h3>OOPS</h3>
		 <p><strong>There was an error during the image upload.</strong></p>'; // PROCESS ERROR 2 :( .

?>

There’s quite alot of information to take in, but I’ve commented nearly every array and function that is on there and gave an explaination of what it’s doing. With this script it’s important to take note of:

$upload_path = 'upload/';

Note: The upload directory specified has to be set CHMOD 777 (Writable) otherwise the script can’t save the uploads

This must be specified correctly because any attempt of a upload will fail if it’s not or is incorrectly specified, the best way to setup a directory where the files will go is to place the two files that make this uploader index.php and uploader.php in some of directory called uploader Which would be located within your public_html and then create a directory within that called upload which would be your directory where any uploads would be stored.

So your URL structure to access the actual uploader would be:

www.yoursite.com/uploader/ (Your page with the upload form would have to be named index.php for this otherwise you’ll get the 403 Forbidden error)

And then your upload directory (Where the uploads would be stored) would be like this:

www.yoursite.com/uploader/upload/filethatsbeenuploaded.doc

Basically thats the main point about this uploader script, need a bit of thought on how the directories will work, but other than that just ready through the comments next to the various arrays and functions and you should be fine!

Step 3: Creating the uploader form (index.php)

Now that you’ve need all php functions thats behind it all, it’s now time to build a form that will allow someone to browse files on there computer and select them for upload:

<form action="uploader.php" method="post" enctype="multipart/form-data">
      <div align="center"><label for="file">Select a file:</label> <input type="file" name="userfile" id="file"></div> <br/>
	  <div align="center">File types allowed: .jpg .jpeg .bmp .png .gif</div>
	  <div align="center">Maxium file size: 2.0 MB</div>
	  <div align="center"><input type="submit" name="submit" value="Upload" /></div>
</form>

Notice the form action and what filename is stated. This is the actual uploader script that will contain all of the php functions that make it work. Throughout this example and on the live version (Link at the end of the tutorial) the main file that contains all the PHP functions is uploader.php so thats why it’s set as that in the example.

This form will need to be placed on a seperate page, I suggested a suitable file directory structure for the uploader and suggested that the form page is called index.php and placed within a uploader directory that’s within the public_html

So it can be accessed from:

http://yoursite.com/uploader

Step 4: Give it a test run before you download

Because it’s PHP you won’t be able to test it via preview unless you have a localhost or server thats configured to display php.

Download PHP script and Form:
Download Form and functions page (Zipped file)

I'm James, I'm 18 years old and I'm a freelance website developer from Nottingham, England. I have a passion for website development and have designed websites for a range of clients in my freelance years. James' Blog is my personal blog where I post articles and general posts whenever I can. I typically like talking website development, but you'll find a range of posts and articles here on my blog.

  • http://fire-studios.com/blog Fire G

    Nice article James. An issues though:
    *.) You should detail out every bit of code, not just comment it. If I hadn’t been the one that created that script (well, the first version. I’m sure you’ve modded) I doubt I would understand all that’s going on.

  • http://projectdeploy.org Oscar Godson

    Looks very good. I’d fix the typo though ;)
    “Maxium” should be “Maximum”

  • http://www.james-blogs.com James

    Hey thanks for spotting that Oscar! I’ll go ahead and correct it!

  • Alexwebmaster

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

  • http://ramencreation.com Ramanand Shiamsundar

    Nice Tutorial James, now what would be cool is to have a tutorial on how to integrate that script into a nice little design?

  • http://iLuvDesigns.com Scott

    Is there a way to randomize the uploaded filename? so duplicate items arnt replaced.

  • Sid

    Thanks man! I now have my own image uploader! You rock.
    Is there anyway to make a file uploader though? Like mediafire or is it only images. Thanks~ Sid

  • http://www.james-blogs.com James

    Im glad you like it Sid :)

    You can make it into a file uploader by simply changing the allowed extensions list and adding file extensions like .zip, .mp3 etc You may also want to change the maximum file size as well. It probably not the best file uploader but it gets the job done.

  • http://pc-aras.com/en/2009/04/25/creating-a-php-fileimage-uploader/ Creating a PHP File/Image Uploader | pc-aras

    [...] Source :: james-blogs [...]

  • http://rcthegreatblog.com Rahul Chowdhury

    Nice Tutorial James, really helpful. I would use this for my upcoming Image Sharing Site. Thanks a lot man.

  • http://www.james-blogs.com James

    Thanks Rahul, hope it serves you well :)

  • http://rcthegreatblog.com Rahul Chowdhury

    Hi James, I have modified your Image Uploader to a File Uploader and Notifier, and have posted as a tutorial in my blog. I have credited you as the Original Creator and made a linkback to you. Hope, its okay, you can view the article here, http://rcthegreatblog.com/2009/05/creating-your-own-file-uploader-easily/ .

  • http://www.james-blogs.com James

    Hi Rahul,

    Thats totally fine with me, nice modifications too!

  • http://rcthegreatblog.com Rahul Chowdhury

    Thanks James!

  • http://www.james-blogs.com/2009/05/06/website-development-tools-image-uploader/ James’ Blog » Website Development Tools: Image Uploader

    [...] Windows Classic is faster because it…James Im glad you found my article easy to follow :) …James Thanks James!…Rahul Chowdhury Hi Rahul, Thats totally fine with me, nice modifications too!…James Hi James, I have modified [...]

  • http://infoeduindia.com/2009/06/06/creating-a-php-fileimage-uploader/ Creating a PHP File/Image Uploader – Tutorial Collection

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Saturday, June 6th, 2009 at 6:50 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  • Anton

    Hi,

    I always got the error of

    Parse error: parse error in C:\xampp\htdocs\test\Upload\upload.php on line 12

    which in your code is…

    define(”ALL_LOWERCASE”, true); // Fixes a bug with capitalised file extensions

    why is it like this?
    Btw, this is very useful if can work.
    Thank you

  • http://www.james-blogs.com James

    Mm very strange, I see your using xampp I’ve only tested this on a live PHP enabled server, try taking out that line and see what happens.

  • http://www.klinker.sk Mjaus Berry

    Hello James.

    Thank for this best article. Its very helpful for me. But I want to ask how I can add image name in to database for later database preview all uploaded images with some description?

    You can see in http://www.klinker.sk – in sortiment in for example roben. There is list from database with images. There is and login access for adding and editing this data, but I can use your image upload for it because image upload isnt there.

    Can you let me know to email, please?
    Thank a lot

blog comments powered by Disqus