Wednesday 4 March 2015

PHP File Upload

This tutorial focuses on letting your users upload and save file information in database using PHP. To achieve this we only need two files, an HTML upload form and a process page. HTML form allows user choose a file, and when user click on upload button, process page will upload file to server.

Also see : Ajax File Upload using jQuery.

Database Table

For the tutorial, I have created a database table called file_records with 5 columns to store file information. Just copy and run following SQL query in your PhpMyAdmin to create file_records database table.
 
1
2
3
4
5
6
7
8
CREATE TABLE IF NOT EXISTS `file_records` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(60) NOT NULL,
`file_title` varchar(60) NOT NULL,
`file_size` int(11) NOT NULL,
`uploaded_date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Upload Form

HTML code below is simple upload form, it contains two input field, a title box and file browse button to let user choose files from computer. Form tag includes enctype=”multipart/form-data” for binary uploads. I have included a style file to make it look good, you can find it in sample zip fie.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
<head>
<title>File Upload with PHP</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="theForm">
<form action="uploader.php" id="FileUploader" enctype="multipart/form-data" method="post" >
    <label>Title
    <span class="small">Title of the File</span>
    </label>
    <input type="text" name="mName" id="mName" />

    <label>File
    <span class="small">Choose a File</span>
    </label>
    <input type="file" name="mFile" id="mFile" />
    <button type="submit" class="red-button" id="uploadButton">Upload (1MB)</button>
    <div class="spacer"></div>
</form>
</div>
</body>
</html>

Uploader Page

This PHP page uploads files to server, check for allowed file extensions, empty field and if everything looks good, it stores information in the database table. I have provided comment lines before each PHP codes to help you understand better. Just modify settings text on top, it should start working in your testing server.
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
$UploadDirectory    = 'uploads/'; //Upload Directory, ends with slash & make sure folder exist
$SuccessRedirect    = 'success.html'; //Redirect to a URL after success

// replace with your mysql database details

$MySql_username     = "xxx"; //mysql username
$MySql_password     = "xxx"; //mysql password
$MySql_hostname     = "localhost"; //hostname
$MySql_databasename = 'xxx'; //databasename


if (!@file_exists($UploadDirectory)) {
    //destination folder does not exist
    die("Make sure Upload directory exist!");
}

if($_POST)
{
    if(!isset($_POST['mName']) || strlen($_POST['mName'])<1)
    {
        //required variables are empty
        die("Title is empty!");
    }


    if($_FILES['mFile']['error'])
    {
        //File upload error encountered
        die(upload_errors($_FILES['mFile']['error']));
    }

    $FileName           = strtolower($_FILES['mFile']['name']); //uploaded file name
    $FileTitle          = mysql_real_escape_string($_POST['mName']); // file title
    $ImageExt           = substr($FileName, strrpos($FileName, '.')); //file extension
    $FileType           = $_FILES['mFile']['type']; //file type
    $FileSize           = $_FILES['mFile']["size"]; //file size
    $RandNumber         = rand(0, 9999999999); //Random number to make each filename unique.
    $uploaded_date      = date("Y-m-d H:i:s");

    switch(strtolower($FileType))
    {
        //allowed file types
        case 'image/png': //png file
        case 'image/gif': //gif file
        case 'image/jpeg': //jpeg file
        case 'application/pdf': //PDF file
        case 'application/msword': //ms word file
        case 'application/vnd.ms-excel': //ms excel file
        case 'application/x-zip-compressed': //zip file
        case 'text/plain': //text file
        case 'text/html': //html file
            break;
        default:
            die('Unsupported File!'); //output error
    }


    //File Title will be used as new File name
    $NewFileName = preg_replace(array('/s/', '/.[.]+/', '/[^w_.-]/'), array('_', '.', ''), strtolower($FileTitle));
    $NewFileName = $NewFileName.'_'.$RandNumber.$ImageExt;
   //Rename and save uploded file to destination folder.
   if(move_uploaded_file($_FILES['mFile']["tmp_name"], $UploadDirectory . $NewFileName ))
   {
        //connect & insert file record in database
        /*
        $dbconn = mysql_connect($MySql_hostname, $MySql_username, $MySql_password)or die("Unable to connect to MySQL");
        mysql_select_db($MySql_databasename,$dbconn);
        @mysql_query("INSERT INTO file_records (file_name, file_title, file_size, uploaded_date) VALUES ('$NewFileName', '$FileTitle',$FileSize,'$uploaded_date')");
        mysql_close($dbconn);
        */


        header('Location: '.$SuccessRedirect); //redirect user after success

   }else{
        die('error uploading File!');
   }
}

//function outputs upload error messages, http://www.php.net/manual/en/features.file-upload.errors.php#90522
function upload_errors($err_code) {
    switch ($err_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>