Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Tuesday, October 25, 2011

Creating a PHP File/Image Uploader


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:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?
   // 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 http://jamesblogs.com/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> .
 
?>
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:
1
$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:
1
2
3
4
5
6
<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.

No comments:

Post a Comment