cst336, spring 2015 week 8: php file upload. php provides specific functions to handle binary data...

18
CST336, Spring 2015 Week 8: PHP File Upload

Upload: doris-taylor

Post on 14-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

CST336, Spring 2015

Week 8: PHP File Upload

Page 2: 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

PHP File UploadPHP 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:

<form method="POST" enctype="multipart/form-data">

The form must also include an input element with type=file:

<input type="file" name="fileName" />

Page 3: 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

PHP File Upload

<form method="POST" enctype="multipart/form-data">

Select file: <input type="file" name="fileName" /> <br />

<input type="submit" name="uploadForm" value="Upload File" />

</form>

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.

Page 4: 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

PHP File Upload

<?phpif (isset($_POST['uploadForm'])) { if ($_FILES["fileName"]["error"] > 0) { echo "Error: " . $_FILES["fileName"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["fileName"]["name"] . "<br>"; echo "Type: " . $_FILES["fileName"]["type"] . "<br>"; echo "Size: " . ($_FILES["fileName"]["size"] / 1024) . " KB<br>"; echo "Stored in: " . $_FILES["fileName"]["tmp_name"]; } } //endIf form submission?><form method="POST" enctype="multipart/form-data">

Select file: <input type="file" name="fileName" /> <br /><input type="submit" name="uploadForm" value="Upload File" /> </form>

uploadFile.php

Notice that "fileName"

matches the name of the

type="file" on the form

Page 5: 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

PHP File Upload

After uploading a file using the code from the previous slide, you get something like:Upload: Desert.jpgType: image/jpegSize: 826.1142578125 KBStored 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

Page 6: 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

PHP File Uploadfunction filterUploadedFile() { $allowedTypes = array("text/plain","image/png"); $filterError = ""; if (!in_array($_FILES["fileName"]["type"], $allowedTypes ) ) { $filterError = "Invalid type. <br>"; } return $filterError;}

if (isset($_POST['uploadForm'])) { $filterError = filterUploadedFile(); if (empty($filterError)) {

if ($_FILES["fileName"]["error"] > 0) { echo "Error: " . $_FILES["fileName"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["fileName"]["name"] . "<br>"; echo "Type: " . $_FILES["fileName"]["type"] . "<br>"; echo "Size: " . ($_FILES["fileName"]["size"] / 1024) . " KB<br>"; echo "Stored in: " . $_FILES["fileName"]["tmp_name"]; } }//end empty($filterError)} //endIf form submission ?>

Page 7: 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

PHP File Upload

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. <br>"; }

$fileName = $_FILES["fileName"]["name"]; if (!in_array(substr($fileName,strrpos($fileName,".")+1), $allowedExtensions) ) { $filterError = "Invalid extension. <br>"; } if ($_FILES["fileName"]["size"] > $allowedSize ) { $filterError .= "File size too big. <br>"; } return $filterError;}

Page 8: 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

PHP File Upload

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.

Page 9: 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

PHP File Upload

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 INTfileType VARCHAR(100)fileData MEDIUMBLOB //allows up to 16GB of data storageuploadDate TIMESTAMP

Create a table called up_files with the above fields and a PK.

Page 10: 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

if ($_FILES["fileName"]["error"] > 0) { echo "Error: " . $_FILES["fileName"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["fileName"]["name"] . "<br>"; echo "Type: " . $_FILES["fileName"]["type"] . "<br>"; echo "Size: " . ($_FILES["fileName"]["size"] / 1024) . " KB<br>"; 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 "<br />File saved into database <br /><br />"; }

To save the binary data into the database we use file_get_contents:

PHP File Upload

Page 11: 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

<?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

PHP File Upload

Page 12: 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

PHP File Upload

File System ApproachThis 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.

Page 13: 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

PHP File Upload

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"]);

Page 14: 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

PHP File Upload

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)

Page 15: 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

PHP File UploadCreating 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 "<img src='thumb.jpg'/>"; }

Page 16: 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

PHP File Upload

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));

}

Page 17: 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

PHP File Upload

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

Page 18: 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

PHP File UploadLab

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.