SlideShare a Scribd company logo
CSC 2720 Building Web Applications PHP File Upload
Handling File Uploads in PHP PHP must run with the right settings. You may need to change the PHP configuration file  php.ini . A temporary storage directory must exists with the correct permissions. Uploaded files are stored here temporarily; the files  may  be removed from here when your PHP script finishes processing the HTTP request. The final storage directory must exists with the correct permissions. You have to write codes to move the uploaded files from the temporary directory to another directory.
Configuring  php.ini file_uploads  Enable/disable PHP support for file uploads max_input_time Indicates how long, in seconds, a PHP script is allowed to receive input post_max_size Size, in bytes, of the total allowed POST data upload_tmp_dir Indicates where uploaded files should be temporarily stored upload_max_filesize Size, in bytes, of the largest possible file upload allowed
HTTP File Upload ( RFC 1867 ) Set attribute  METHOD=&quot;POST&quot; Set attribute  ENCTYPE=&quot;multipart/form-data&quot; Use INPUT element with  TYPE=&quot;file&quot;  to create a file upload control (one control per file) Hidden input field MAX_FILE_SIZE  recommends  to the web client the limit of the size of the uploaded file. <form action=&quot;file_upload.php&quot;  method=&quot;post&quot; enctype=&quot;multipart/form-data&quot; > <input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot;  value=&quot;30000&quot; /> <input  type=&quot;file&quot;  name=&quot;upload&quot; /> <input type=&quot;submit&quot; value=&quot;Upload&quot; /> </form>
POST register.jsp HTTP/1.1 Host: hi/iq User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.2) Gecko/20021126 Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8, video/x-mng,image/png,image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1 Accept-Language: en-us, en;q=0.50 Accept-Encoding: gzip, deflate, compress;q=0.9 Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66 Keep-Alive: 300 Connection: keep-alive Content-Type: multipart/form-data; boundary=---------------------------29772313742745 Content-Length: 452 -----------------------------29772313742745 Content-Disposition: form-data; name=&quot;name&quot; J.Doe -----------------------------29772313742745 Content-Disposition: form-data; name=&quot;email&quot; [email_address] -----------------------------29772313742745 Content-Disposition: form-data; name=&quot;file-upload&quot;; filename=&quot;test.txt&quot; Content-Type: text/plain test data with some high ascii: ¿Como estás? -----------------------------29772313742745-- An example of data sent via POST method with enctype=&quot;multipart/form-data&quot; (Copied from  http://www.devx.com/Java/Article/17679/0/page/2 )
The  $_FILES  Array The error code associated with any problem. error The temporary filename of the uploaded file as it was stored on the server. tmp_name The size of the uploaded file in bytes. size The MIME type of the file, as provided by the browser. type The original name of the file (as it was on the user's computer). name Meaning Index
Processing the uploaded items // &quot;upload&quot;  is the name assigned to the input element, as in // <input type=&quot;file&quot; name=&quot;upload&quot; /> if (isset( $_FILES['upload'] )) { if ( $_FILES['upload']['error']  > 0)) { //  File upload fails.  See next slide for detailed info about the  //  meaning of the error code. } else { //  e.g., only allows JPEG image files to be uploaded //  Note: This is not a complete list of MIME types for JPEG images $allowed = array('image/jpeg', 'image/jpg'); // Continue next page …
Processing the uploaded items ( … continue) if (in_array( $_FILES['upload']['type'] , $allowed)) { $tmp =  $_FILES['upload']['tmp_name'] ; $dst = &quot;C:/uploads/{ $_FILES['upload']['name'] }&quot;; if ( move_upload_file ($tmp, $dst)) { // Success ! } } }  // End of else // Manually delete the temporary uploaded file if // it still exists $tmp =  $_FILES['upload']['tmp_name'] ; if (file_exists($tmp) && is_file($tmp)) unlink($tmp);  } Note:  move_uploaded_file()  will overwrite an existing file without warning.
File Upload Error Messages Explained UPLOAD_ERR_OK   Value: 0; There is no error, the file uploaded with success.  UPLOAD_ERR_INI_SIZE   Value: 1; The uploaded file exceeds the  upload_max_filesize  directive in  php.ini .  UPLOAD_ERR_FORM_SIZE   Value: 2; The uploaded file exceeds the  MAX_FILE_SIZE  directive that was specified in the HTML form.  UPLOAD_ERR_PARTIAL   Value: 3; The uploaded file was only partially uploaded.  UPLOAD_ERR_NO_FILE   Value: 4; No file was uploaded.  UPLOAD_ERR_NO_TMP_DIR   Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.  UPLOAD_ERR_CANT_WRITE   Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.  UPLOAD_ERR_EXTENSION   Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0.  Source:  http://www.php.net/manual/en/features.file-upload.errors.php
References and Related Resources PHP: Filesystem Functions e.g.,  mkdir() – Create a directory filesie() – Get the size of a file copy() – Copy a file rename() – Rename a file or folder filemtime() – Get file modification time http://www.php.net/manual/en/ref.filesystem.php PHP: Handling File Uploads http://www.php.net/manual/en/features.file-upload.php PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide (3rd Edition) , by Larry Ullman. Peachpit Press, 2007 (pp 302-15)

More Related Content

PPTX
File Uploading in PHP
Idrees Hussain
 
PPTX
Uploading a file with php
Muhamad Al Imran
 
PPTX
File upload php
sana mateen
 
ODP
Php File Upload
Hiroaki Kawai
 
PPTX
Image upload in php MySql
Ishaq Shinwari
 
PPT
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
PPT
05 File Handling Upload Mysql
Geshan Manandhar
 
PPTX
Php file upload, cookies & session
Jamshid Hashimi
 
File Uploading in PHP
Idrees Hussain
 
Uploading a file with php
Muhamad Al Imran
 
File upload php
sana mateen
 
Php File Upload
Hiroaki Kawai
 
Image upload in php MySql
Ishaq Shinwari
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
webhostingguy
 
05 File Handling Upload Mysql
Geshan Manandhar
 
Php file upload, cookies & session
Jamshid Hashimi
 

What's hot (20)

PDF
Web Development Course: PHP lecture 4
Gheyath M. Othman
 
PDF
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
PPTX
PHP Hypertext Preprocessor
adeel990
 
PDF
Php workshop L04 database
Mohammad Tahsin Alshalabi
 
PDF
Php workshop L03 superglobals
Mohammad Tahsin Alshalabi
 
PDF
Php file handling in Hindi
Vipin sharma
 
ODP
PHP BASIC PRESENTATION
krutitrivedi
 
PPT
Class 6 - PHP Web Programming
Ahmed Swilam
 
PPT
PHP and MySQL
webhostingguy
 
PDF
File system
Gayane Aslanyan
 
PPT
Php File Operations
mussawir20
 
PPTX
Files in php
sana mateen
 
PPTX
PHP Function
Reber Novanta
 
PDF
InfiniFlux collector
InfiniFlux
 
PDF
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
PDF
New Features in PHP 5.3
Bradley Holt
 
PPT
Intro to php
Sp Singh
 
PPTX
File upload for the 21st century
Jiří Pudil
 
ODP
Database Connection With Mysql
Harit Kothari
 
PPT
Intro to PHP
Sandy Smith
 
Web Development Course: PHP lecture 4
Gheyath M. Othman
 
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
PHP Hypertext Preprocessor
adeel990
 
Php workshop L04 database
Mohammad Tahsin Alshalabi
 
Php workshop L03 superglobals
Mohammad Tahsin Alshalabi
 
Php file handling in Hindi
Vipin sharma
 
PHP BASIC PRESENTATION
krutitrivedi
 
Class 6 - PHP Web Programming
Ahmed Swilam
 
PHP and MySQL
webhostingguy
 
File system
Gayane Aslanyan
 
Php File Operations
mussawir20
 
Files in php
sana mateen
 
PHP Function
Reber Novanta
 
InfiniFlux collector
InfiniFlux
 
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
New Features in PHP 5.3
Bradley Holt
 
Intro to php
Sp Singh
 
File upload for the 21st century
Jiří Pudil
 
Database Connection With Mysql
Harit Kothari
 
Intro to PHP
Sandy Smith
 
Ad

Similar to File Upload (20)

PPTX
PHP fundamnetal in information technology CHapter -02.pptx
worldchannel
 
PDF
Introduction to php web programming - get and post
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
lecture 11.pptx
ITNet
 
PPTX
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
DOCX
Php advance
Rattanjeet Singh
 
PDF
Python Google Cloud Function with CORS
RapidValue
 
PPT
eZ Publish Cluster Unleashed
Bertrand Dunogier
 
PPT
Parameter Passing & Session Tracking in PHP
amichoksi
 
PPTX
On secure application of PHP wrappers
Positive Hack Days
 
ODP
Website releases made easy with the PEAR installer, OSCON 2009
Helgi Þormar Þorbjörnsson
 
PDF
Hacking IIS - NahamCon.pdf
distortdistort
 
PDF
Getting to The Loop - London Wordpress Meetup July 28th
Chris Adams
 
PDF
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
ODP
Website releases made easy with the PEAR installer - Barcelona 2008
Helgi Þormar Þorbjörnsson
 
DOCX
Copy of cgi
Abhishek Kesharwani
 
ODP
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
PPTX
Advance Mobile Application Development class 02-B
Dr. Mazin Mohamed alkathiri
 
PPTX
This slide show will brief about database handling
averynight005
 
PDF
File Handling-Module V.pdf dSfcsvfsvcdfscfd
mbavadharini
 
PPTX
PHP File Handling
Degu8
 
PHP fundamnetal in information technology CHapter -02.pptx
worldchannel
 
Introduction to php web programming - get and post
baabtra.com - No. 1 supplier of quality freshers
 
lecture 11.pptx
ITNet
 
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
Php advance
Rattanjeet Singh
 
Python Google Cloud Function with CORS
RapidValue
 
eZ Publish Cluster Unleashed
Bertrand Dunogier
 
Parameter Passing & Session Tracking in PHP
amichoksi
 
On secure application of PHP wrappers
Positive Hack Days
 
Website releases made easy with the PEAR installer, OSCON 2009
Helgi Þormar Þorbjörnsson
 
Hacking IIS - NahamCon.pdf
distortdistort
 
Getting to The Loop - London Wordpress Meetup July 28th
Chris Adams
 
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Website releases made easy with the PEAR installer - Barcelona 2008
Helgi Þormar Þorbjörnsson
 
Copy of cgi
Abhishek Kesharwani
 
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Advance Mobile Application Development class 02-B
Dr. Mazin Mohamed alkathiri
 
This slide show will brief about database handling
averynight005
 
File Handling-Module V.pdf dSfcsvfsvcdfscfd
mbavadharini
 
PHP File Handling
Degu8
 
Ad

More from webhostingguy (20)

PDF
Running and Developing Tests with the Apache::Test Framework
webhostingguy
 
PDF
MySQL and memcached Guide
webhostingguy
 
PPT
Novell® iChain® 2.3
webhostingguy
 
PDF
Load-balancing web servers Load-balancing web servers
webhostingguy
 
PDF
SQL Server 2008 Consolidation
webhostingguy
 
PDF
What is mod_perl?
webhostingguy
 
PDF
What is mod_perl?
webhostingguy
 
PDF
Master Service Agreement
webhostingguy
 
PPT
Notes8
webhostingguy
 
PDF
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
webhostingguy
 
PPT
Managing Diverse IT Infrastructure
webhostingguy
 
PPT
Web design for business.ppt
webhostingguy
 
PPS
IT Power Management Strategy
webhostingguy
 
PPS
Excel and SQL Quick Tricks for Merchandisers
webhostingguy
 
PPT
OLUG_xen.ppt
webhostingguy
 
PPT
Parallels Hosting Products
webhostingguy
 
PPT
Microsoft PowerPoint presentation 2.175 Mb
webhostingguy
 
PDF
Reseller's Guide
webhostingguy
 
PDF
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
webhostingguy
 
PDF
Getting Started Guide
webhostingguy
 
Running and Developing Tests with the Apache::Test Framework
webhostingguy
 
MySQL and memcached Guide
webhostingguy
 
Novell® iChain® 2.3
webhostingguy
 
Load-balancing web servers Load-balancing web servers
webhostingguy
 
SQL Server 2008 Consolidation
webhostingguy
 
What is mod_perl?
webhostingguy
 
What is mod_perl?
webhostingguy
 
Master Service Agreement
webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
webhostingguy
 
Managing Diverse IT Infrastructure
webhostingguy
 
Web design for business.ppt
webhostingguy
 
IT Power Management Strategy
webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
webhostingguy
 
OLUG_xen.ppt
webhostingguy
 
Parallels Hosting Products
webhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
webhostingguy
 
Reseller's Guide
webhostingguy
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
webhostingguy
 
Getting Started Guide
webhostingguy
 

File Upload

  • 1. CSC 2720 Building Web Applications PHP File Upload
  • 2. Handling File Uploads in PHP PHP must run with the right settings. You may need to change the PHP configuration file php.ini . A temporary storage directory must exists with the correct permissions. Uploaded files are stored here temporarily; the files may be removed from here when your PHP script finishes processing the HTTP request. The final storage directory must exists with the correct permissions. You have to write codes to move the uploaded files from the temporary directory to another directory.
  • 3. Configuring php.ini file_uploads Enable/disable PHP support for file uploads max_input_time Indicates how long, in seconds, a PHP script is allowed to receive input post_max_size Size, in bytes, of the total allowed POST data upload_tmp_dir Indicates where uploaded files should be temporarily stored upload_max_filesize Size, in bytes, of the largest possible file upload allowed
  • 4. HTTP File Upload ( RFC 1867 ) Set attribute METHOD=&quot;POST&quot; Set attribute ENCTYPE=&quot;multipart/form-data&quot; Use INPUT element with TYPE=&quot;file&quot; to create a file upload control (one control per file) Hidden input field MAX_FILE_SIZE recommends to the web client the limit of the size of the uploaded file. <form action=&quot;file_upload.php&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot; > <input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;30000&quot; /> <input type=&quot;file&quot; name=&quot;upload&quot; /> <input type=&quot;submit&quot; value=&quot;Upload&quot; /> </form>
  • 5. POST register.jsp HTTP/1.1 Host: hi/iq User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.2) Gecko/20021126 Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8, video/x-mng,image/png,image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1 Accept-Language: en-us, en;q=0.50 Accept-Encoding: gzip, deflate, compress;q=0.9 Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66 Keep-Alive: 300 Connection: keep-alive Content-Type: multipart/form-data; boundary=---------------------------29772313742745 Content-Length: 452 -----------------------------29772313742745 Content-Disposition: form-data; name=&quot;name&quot; J.Doe -----------------------------29772313742745 Content-Disposition: form-data; name=&quot;email&quot; [email_address] -----------------------------29772313742745 Content-Disposition: form-data; name=&quot;file-upload&quot;; filename=&quot;test.txt&quot; Content-Type: text/plain test data with some high ascii: ¿Como estás? -----------------------------29772313742745-- An example of data sent via POST method with enctype=&quot;multipart/form-data&quot; (Copied from http://www.devx.com/Java/Article/17679/0/page/2 )
  • 6. The $_FILES Array The error code associated with any problem. error The temporary filename of the uploaded file as it was stored on the server. tmp_name The size of the uploaded file in bytes. size The MIME type of the file, as provided by the browser. type The original name of the file (as it was on the user's computer). name Meaning Index
  • 7. Processing the uploaded items // &quot;upload&quot; is the name assigned to the input element, as in // <input type=&quot;file&quot; name=&quot;upload&quot; /> if (isset( $_FILES['upload'] )) { if ( $_FILES['upload']['error'] > 0)) { // File upload fails. See next slide for detailed info about the // meaning of the error code. } else { // e.g., only allows JPEG image files to be uploaded // Note: This is not a complete list of MIME types for JPEG images $allowed = array('image/jpeg', 'image/jpg'); // Continue next page …
  • 8. Processing the uploaded items ( … continue) if (in_array( $_FILES['upload']['type'] , $allowed)) { $tmp = $_FILES['upload']['tmp_name'] ; $dst = &quot;C:/uploads/{ $_FILES['upload']['name'] }&quot;; if ( move_upload_file ($tmp, $dst)) { // Success ! } } } // End of else // Manually delete the temporary uploaded file if // it still exists $tmp = $_FILES['upload']['tmp_name'] ; if (file_exists($tmp) && is_file($tmp)) unlink($tmp); } Note: move_uploaded_file() will overwrite an existing file without warning.
  • 9. File Upload Error Messages Explained UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success. UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini . UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded. UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded. UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0. UPLOAD_ERR_EXTENSION Value: 8; File upload stopped by extension. Introduced in PHP 5.2.0. Source: http://www.php.net/manual/en/features.file-upload.errors.php
  • 10. References and Related Resources PHP: Filesystem Functions e.g., mkdir() – Create a directory filesie() – Get the size of a file copy() – Copy a file rename() – Rename a file or folder filemtime() – Get file modification time http://www.php.net/manual/en/ref.filesystem.php PHP: Handling File Uploads http://www.php.net/manual/en/features.file-upload.php PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide (3rd Edition) , by Larry Ullman. Peachpit Press, 2007 (pp 302-15)