Presentation is loading. Please wait.

Presentation is loading. Please wait.

CST336, Spring 2015 Week 8: PHP File Upload. PHP provides specific functions to handle binary data such as uploading a file into the server, storing it.

Similar presentations


Presentation on theme: "CST336, Spring 2015 Week 8: PHP File Upload. PHP provides specific functions to handle binary data such as uploading a file into the server, storing it."— Presentation transcript:

1 CST336, Spring 2015 Week 8: PHP File Upload

2 PHP provides specific functions to handle binary data such as uploading a file into the server, storing it into a database, and retrieving the file, among others. The first step to upload a file is creating the corresponding HTML form, which must use the POST method and also the enctype (encryption type) attribute: The form must also include an input element with type=file:

3 Select file: uploadFile.php Copy and paste the following HTML Form into a new file. Test the form. You'll be able to browse to select any file within your local computer. However, the file won't be uploaded since we haven't implemented that functionality yet.

4 <?php if (isset($_POST['uploadForm'])) { if ($_FILES["fileName"]["error"] > 0) { echo "Error: ". $_FILES["fileName"]["error"]. " "; } else { echo "Upload: ". $_FILES["fileName"]["name"]. " "; echo "Type: ". $_FILES["fileName"]["type"]. " "; echo "Size: ". ($_FILES["fileName"]["size"] / 1024). " KB "; echo "Stored in: ". $_FILES["fileName"]["tmp_name"]; } } //endIf form submission ?> Select file: uploadFile.php Notice that "fileName" matches the name of the type="file" on the form

5 After uploading a file using the code from the previous slide, you get something like: Upload: Desert.jpg Type: image/jpeg Size: 826.1142578125 KB Stored in: /tmp/phpcJzYdC $_FILES["fileName"]["name"] - Contains the name of the file $_FILES["fileName"]["type"] - Contains the Mime Type (e.g., image/gif) $_FILES["fileName"]["size"] - Contains the file size in bytes $_FILES["fileName"]["tmp_name"] - Contains the path and name of the temporary file on the server $_FILES["fileName"]["error"] - Contains the error code, if any. Such as missing a temporary folder, file partially uploaded, etc. A list of errors is located here : http://php.net/manual/en/features.file- upload.errors.php http://php.net/manual/en/features.file- upload.errors.php

6 function filterUploadedFile() { $allowedTypes = array("text/plain","image/png"); $filterError = ""; if (!in_array($_FILES["fileName"]["type"], $allowedTypes ) ) { $filterError = "Invalid type. "; } return $filterError; } if (isset($_POST['uploadForm'])) { $filterError = filterUploadedFile(); if (empty($filterError)) { if ($_FILES["fileName"]["error"] > 0) { echo "Error: ". $_FILES["fileName"]["error"]. " "; } else { echo "Upload: ". $_FILES["fileName"]["name"]. " "; echo "Type: ". $_FILES["fileName"]["type"]. " "; echo "Size: ". ($_FILES["fileName"]["size"] / 1024). " KB "; echo "Stored in: ". $_FILES["fileName"]["tmp_name"]; } }//end empty($filterError) } //endIf form submission ?>

7 The following code has more filter restrictions regarding the file extension and size: function filterUploadedFile() { $allowedTypes = array("text/plain","image/png"); $allowedExtensions = array("txt", "png"); $allowedSize = 1000; $filterError = ""; if (!in_array($_FILES["fileName"]["type"], $allowedTypes ) ) { $filterError = "Invalid type. "; } $fileName = $_FILES["fileName"]["name"]; if (!in_array(substr($fileName,strrpos($fileName,".")+1), $allowedExtensions) ) { $filterError = "Invalid extension. "; } if ($_FILES["fileName"]["size"] > $allowedSize ) { $filterError.= "File size too big. "; } return $filterError; }

8 So far, we have uploaded the files to a temporal location. The files are automatically deleted from that location as soon as the program finishes. Once we have tested that only certain file type, extension and size are being uploaded, we can proceed to store the file into a more permanent storage. There are two ways in which uploaded files can be stored: 1.In a database 2.In the server's file system Both methods have pros and cons: Database approach: It's slower and it's more difficult to migrate data to a different database; however, the files are more secure. File system: It's faster but it's open to having malicious files that could compromise the integrity of the file system.

9 Database Approach This approach is recommended when uploading confidential documents that are intended to be used by the owner or a small group of people (medical records, copy of bank checks, etc.) Here are the field data types recommended for storing files in a database (in addition to fields to identify the owner and the PK): fileName VARCHAR (100) fileSize INT fileType VARCHAR(100) fileData MEDIUMBLOB //allows up to 16GB of data storage uploadDate TIMESTAMP Create a table called up_files with the above fields and a PK.

10 if ($_FILES["fileName"]["error"] > 0) { echo "Error: ". $_FILES["fileName"]["error"]. " "; } else { echo "Upload: ". $_FILES["fileName"]["name"]. " "; echo "Type: ". $_FILES["fileName"]["type"]. " "; echo "Size: ". ($_FILES["fileName"]["size"] / 1024). " KB "; echo "Stored in: ". $_FILES["fileName"]["tmp_name"]; include 'dbConn.php'; $binaryData = file_get_contents($_FILES["fileName"]["tmp_name"]); $sql = "INSERT INTO up_files (fileName, fileType, fileData ) ". " VALUES (:fileName, :fileType, :fileData) "; $stm=$dbConn->prepare($sql); $stm->execute(array (":fileName"=>$_FILES["fileName"]["name"], ":fileType"=>$_FILES["fileName"]["type"], ":fileData"=>$binaryData)); echo " File saved into database "; } To save the binary data into the database we use file_get_contents:

11 <?php include 'dbConn.php'; $sql = "SELECT * FROM up_files WHERE fileId = :fileId"; $stmt = $dbConn->prepare($sql); $stmt->execute( array(":fileId"=> $_GET['fileId'])); $stmt->bindColumn('fileData', $data, PDO::PARAM_LOB); $record = $stmt->fetch(PDO::FETCH_BOUND); if (!empty($record)){ header('Content-Type:'. $record['fileType']); //specifies the mime type header('Content-Disposition: inline;'); echo $data; } ?> Let's create another file to download the binary data from the database: downloadFile.php "fileData" is the field with the binary data If using "attachment" instead of "inline" will force to download the file

12 File System Approach This approach is recommended when you trust the users or there is a way to hold them accountable for the content uploaded in the web server. To upload files to the file system we use move_uploaded_file to move the uploaded file from the temporary folder to a different folder. The following code puts the files into the same folder as the PHP program.

13 File System Approach When moving the uploading file from the temporary folder, it is possible to specify a different folder where to store the file. However, the folder has to be created first (which could be done through PHP). The file name could be changed too but the extension needs to be the same as the original. The following line moves the uploaded file to the "uploadedFiles" folder move_uploaded_file($_FILES["fileName"]["tmp_name"], "uploadedFiles/". $_FILES["fileName"]["name"]);

14 File System Approach When uploading a file with the same name, it will overwrite the previous one by default. To prevent this from happening, a condition can be added: if (file_exists("path/". $_FILES["file"]["name"])) { echo $_FILES["file"]["name"]. " already exists. "; } else { move_uploaded_file($_FILES["fileName"]["tmp_name"], "path/". $_FILES["fileName"]["name"]); } To delete a file from the file system within PHP, use: unlink(path/filename)

15 Creating Thumbnails PHP provides functions to create jpg images with a specific size. These functions can be used to create a thumbnail of the images uploaded: function createThumbnail(){ $sourcefile = imagecreatefromstring(file_get_contents($_FILES["fileName"]["tmp_name"])); $newx = 150; $newy = 150; //new size $thumb = imagecreatetruecolor($newx,$newy); imagecopyresampled($thumb, $sourcefile, 0,0, 0,0, $newx, $newy, imagesx($sourcefile), imagesy($sourcefile)); imagejpeg($thumb,"thumb.jpg"); //creates jpg image file called "thumb.jpg" echo " "; }

16 Creating Thumbnails $newx = 150; $newy = 150; //new size if (imagesx($sourcefile) > imagesy($sourcefile)) { // landscape orientation $newy = round($newx/imagesx($sourcefile) * imagesy($sourcefile)); } else { // portrait orientation $newx = round($newy/imagesy($sourcefile) * imagesx($sourcefile)); }

17 Combined File System/Database Approach In some cases, it might be necessary to store additional information in a database about the documents uploaded. For instance, if uploading a PDF document about a medical exam, it might be important to store the date, medical procedures, and diagnosis. This will prevent having to download every single PDF document to search for specific information. Likewise, if uploading images, one might want to add comments such as the location the image was taken or created and a description of it. In cases like these, an option is to store in the database the path to the uploaded file instead of uploading the binary data. imageId ownerId dateUpload description path 123 jdoe 12/31/2014 Times Square New Year jdoe/img/ny7.jpg

18 Lab Create an "Update Profile" page from which people can upload their pic. If no profile picture has been uploaded, we'll show a generic image such as: The image will be uploaded into the File System, within the folders: profilePics/username/ (where username is the actual username) The name of the image file will have the format: current_time.jpg The uploaded profile pic must be resized in proportion to 100x100 of the original picture. The profile pic will be replaced when uploading a new one and the old one must be deleted from the file system.


Download ppt "CST336, Spring 2015 Week 8: PHP File Upload. PHP provides specific functions to handle binary data such as uploading a file into the server, storing it."

Similar presentations


Ads by Google