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.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

PHP File Upload ISYS 475.
Welcome to WebCRD.
1 Configuring Internet- related services (April 22, 2015) © Abdou Illia, Spring 2015.
1 Chapter 5 – Handling HTML Controls in Web Pages spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
More on PHP Coding Lab no. 6 Advance Database Management System.
Cox Personal Web Space (or AOL space) Free Storage for Image Galleries.
Images By Tara Frieszell By Tara Frieszell. Adding images to your website will make it more interesting and add to the design. However, some viewers aren’t.
Edit the text with your own short phrases. The animation is already done for you; just copy and paste the slide into your existing presentation. RegisterLogin.
FILE UPLOADS CHAPTER 11. THE BASIC PROCESS 1.The HTML form displays the control to locate and upload a file 2.Upon form submission, the server first stores.
Uploading Files. Why? By giving a user the option to upload a file you are creating an interactive page You can enable users have a greater web experience.
File uploading in PHP Basharat Mahmood, Department of Computer Science,CIIT,Islamabad, Pakistan. 1.
Working with SharePoint Document Libraries. What are document libraries? Document libraries are collections of files that you can share with team members.
Agenda Overview 2.What is SharePoint? 3.NCDOT Websites 4.Roles 5.Search 6.SharePoint Interface.
Web Programming Week 10 Old Dominion University Department of Computer Science CS 418/518 Fall 2010 Martin Klein 11/02/10.
U NIT 4 F ILE U PLOAD. I. C REATE AN U PLOAD -F ILE F ORM - With PHP, it is possible to upload files to the server.To allow users to upload files from.
Leveraging the UpSideDown21 Content Management System Tutorial #2.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
FireRMS SQL Audit, Archiving & Purging Presented by Laura Small FireRMS Quality Assurance.
INTERNET APPLICATION DEVELOPMENT For More visit:
A Guide to the BIZNET Online Filing System STATE OF CONNECTICUT DEPARTMENT OF CHILDREN & FAMILIES (DCF) DEPARTMENT OF DEVELOPMENTAL SERVICES (DDS) DEPARTMENT.
UC Berkeley, Employment Services Candidate Gateway Tutorial External Applicants.
Server-side Scripting Powering the webs favourite services.
Tutorial 10 Adding Spry Elements and Database Functionality Dreamweaver CS3 Tutorial 101.
Getting Started with Moodle Getting Started Logging In Entering Your Address Viewing a Course Navigating Your Course’s Homepage Personalizing Your.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Moodle (Course Management Systems). Assignments 1 Assignments are a refreshingly simple method for collecting student work. They are a simple and flexible.
Using School fusion A great interactive tool to aid in communication for students, parents and YOU!!! Property of TSVest 2006.
PHP meets MySQL.
Images. The Element To place an image on our web page, we use the self-closing element: The src attribute ("source") is required and supplies the name.
Microsoft Office 2008 for Mac – Illustrated Unit C: Understanding File Management.
Introduction to MySQL Lab no. 10 Advance Database Management System.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
NMD202 Web Scripting Week3. What we will cover today Includes Exercises PHP Forms Exercises Server side validation Exercises.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Diagnostic Pathfinder for Instructors. Diagnostic Pathfinder Local File vs. Database Normal operations Expert operations Admin operations.
14. Uploading Files to MySQL Database. M. Udin Harun Al Rasyid, S.Kom, Ph.D Desain dan.
Creating databases for web applications Library. New example: student database. Homework: Complete class example. Catch up on source postings. Do creation.
240-Current Research Easily Extensible Systems, Octave, Input Formats, SOA.
Rev.04/2015© 2015 PLEASE NOTE: The Application Review Module (ARM) is a system that is designed as a shared service and is maintained by the Grants Centers.
Storing and Retrieving Data
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
Advanced Web 2012 Lecture 6 Sean Costain Files Sean Costain 2012 Php allows for the : Creation Reading Appending Deleting Uploading And Closing.
Microsoft FrontPage 2003 Illustrated Complete Integrating a Database with a Web Site.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Since you’ll need a place for the user to enter a search query. Every form must have these basic components: – The submission type defined with the method.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Your current Moodle 1.9 Minimum Requirements Ability to do a TEST RUN! Upgrading Moodle to Version 2 By Ramzan Jabbar Doncaster College for the Deaf By.
Unit 7 How to Upload Files. A very useful aspect of PHP is its ability to manage file uploads to your server. Before you can use PHP to manage your uploads,
TechKnowlogy Conference August 2, 2011 Using GoogleDocs for Collaboration.
PHP File Handling. Opening a file Fopen(filename,mode) Closing a file Fclose(filename)
Migrating Wordpress Migrating Wordpress can sometimes get more complicated as it should. There is no plugin that does this for you, the best way is to.
Web Engineering Lecture-08.
Using the Personal Image Photo Library
CHAPTER 5 SERVER SIDE SCRIPTING
Using E-Business Suite Attachments
and Defining Table Relationships
>> PHP: File Uploads
Learn How to Register as a Student and Upload a Resume
Adding Assignments and Learning Units to Your TSS Course
Principles of report writing
ISC440: Web Programming 2 Server-side Scripting PHP 3
Handling Files In particular, uploading files.
Dealing with images in a resume form.
Handling Files In particular, uploading files.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2016 Section DA MW 4:05-5:20
Catalog Manager Standard Supplier Training.
Presentation transcript:

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

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.

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

After uploading a file using the code from the previous slide, you get something like: Upload: Desert.jpg Type: image/jpeg Size: 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 : upload.errors.php upload.errors.php

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

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

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.

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.

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:

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

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.

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

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)

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

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

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

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.