File Uploads Via PHP : Specific MIME Types

Disclaimer

These instructions/steps worked for me in CentOS. It may very well work for you on Red Hat-like or other distributions. Please note that if you decide to use these instructions on your machine, you are doing so entirely at your very own discretion and that neither this site, sgowtham.com, nor its author is responsible for any/all damage – intellectual or otherwise.


During my recent, still on-going, attempts to write a personally satisfying photoblog software/application, I happened to learn about File Uploads using PHP and in my previous post, I discussed the general procedure for doing so. There are numerous articles on the web and in the books, but what follows here is what worked for me – it is expected to serve as a Note2Self but if you find it useful, please feel free to do so.

A Form To Select The File

This portion is exactly the same as in previous post but for completeness sake, here it is. Let us suppose that the HTML file that displays this form is called NewFile.html and the PHP file that does the actual uploading work (and some more) is called Uploader.php.

1
2
3
 
 
<!-- The data encoding type, enctype, MUST be specified as below -->
Select A File


1
 

Uploader.php

Suppose that the end-user selected a file to upload and hit the Upload This File button. Now, the file, Uploader.php takes over and does a few things. But let us suppose that only image file types (JPEG, GIF, PNG) are to be allowed as uploadable types. Let us also suppose that the image file so uploaded needs to be thumbnailed and put in a folder called thumbnails (located under the uploads folder). The source code follows:

1
2
3
4
5
6
7
8
9
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
73
74
75
76
<!--?php 
# Some other MIME types are as follows
# $_FILES['uploaded_file']['type'] == 'application/pdf'
# $_FILES['uploaded_file']['type'] == 'application/xml'  
if ((($_FILES['uploaded_file']['type'] == 'image/gif')    ||
     ($_FILES['uploaded_file']['type'] == 'image/png')    ||
     ($_FILES['uploaded_file']['type'] == 'image/jpeg')   ||
     ($_FILES['uploaded_file']['type'] == 'image/pjpeg')) &amp;&amp;
     ($_FILES['uploaded_file']['size'] &lt; 4194304)) { if ($_FILES['uploaded_file']['error'] &gt; 0) {
    # The error code  associated with this file upload.
    echo "Error: "     . $_FILES['uploaded_file']['error'] . "&lt;br&gt;";
  } else {
    # The original name of the file on the client machine.
    echo "Upload: "    . $_FILES['uploaded_file']['name'] . "&lt;br&gt;";
 
    # The mime type of the file, if the browser provided this information. 
    # This mime type is however not checked on the PHP side and therefore it's value should
    # should not be taken for granted.
    echo "Type: "      . $_FILES['uploaded_file']['type'] . "&lt;br&gt;";
 
    # The size, in bytes, of the uploaded file.
    echo "Size: "      . ($_FILES['uploaded_file']['size'] / 1024) . " kB&lt;br&gt;";
 
    # The temporary filename of the file in which the uploaded file was stored on the server.
    echo "Stored in: " . $_FILES['uploaded_file']['tmp_name'] . "&lt;br&gt;";
 
    # Where the file is going to be placed and thumbnail will be creatd; choose this judiciously
    # These locations needs to have 'write' permissions for 'apache' (or the web-user)
    $target_path       = "tmp/";
    $target_thumb_path = "$target_path/thumbnails/";
 
    if(!is_writable($target_path)) {
      die('Cannot be uploaded to the specified directory. Please change permission  to 777.');
    }
 
    if(!is_writable($target_thumb_path)) {
      die('Thumbnail cannot be created. Please change permission  to 777.');
    }
 
    # This is the temporary file created by PHP
    $uploaded_file = $_FILES['uploaded_file']['tmp_name'];
    $target_path   = $target_path . basename( $_FILES['uploaded_file']['name']);
 
    # Create an image from the $uploaded_file so that it can be thumbnailed
    $src = imagecreatefromjpeg($uploaded_file);
 
    # Extract the original size of the uploaded image
    list($width, $height)=getimagesize($uploaded_file);
 
    # Let the thumbnail be 150 pixels in width, height adjusted based on original aspect ratio
    $new_width   = 150;
    $new_height  = ($height/$width)*$new_width;
    $tmp         = imagecreatetruecolor($new_width, $new_height);
 
    # The following line does the thumbnailing
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
 
    # Write the thumbnailed image to disk
    # Check/modify this part for other image types
    $filename = $target_thumb_path . $_FILES['uploaded_file']['name'];
    imagejpeg($tmp, $filename, 100);
 
    # PHP will clean up the temporary files after the request is completed
    imagedestroy($src);
    imagedestroy($tmp)
 
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
      echo "The file " .  basename( $_FILES['uploaded_file']['name']) . " has been uploaded";
    } else{
      echo "There was an error uploading the file, please try again!";
    }
  }
} else {
  echo "Invalid file type!";
}
?-->

2 Replies to “File Uploads Via PHP : Specific MIME Types”

  1. I’m trying to use this, but I keep getting a 404 error:
    Parse error: syntax error, unexpected T_VARIABLE in
    /home/caronthegerman/loldmypants.com/pictures/uploader/upload.php on line 73

    On line 73, I have
    $target_path = $target_path . basename( $_FILES[‘uploaded_file’][‘name’]);

    and $target_path is
    $target_path = “http://www.loldmypants.com/picturearchive/useruploadstrue”;

    This is like the 5th uploader I’ve tried and I have no idea what I’m doing wrong. Gah…

    1. I believe the error is due to the fact that your $target_path variable is a URL instead of absolute path. Give that a try and let me know if it solves your problem.

Leave a Reply to Caron Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.