Images & PHP

CS418 - Web Programming - Spring 2015

Old Dominion University

Mat Kelly (mkelly@cs.odu.edu)
http://www.cs.odu.edu/~mkelly/cs418 Adapted from slides by Michele C. Weigle

What this lecture will cover

  • Uploading Files
  • Manipulating Images

File Upload with PHP

  • HTML form-based
  • Uses POST method
  • Content Type (enctype) attribute: multipart/form-data
    • no application/x-www-form-urlencoded
  • define MAX_FILE_SIZE in hidden field
    • must precede input type: file
File:

File Upload in PHP

  • Associate array $_FILES
  • $_FILES['mkfile']['name']
    • original name from client
  • $_FILES['mkfile']['type']
    • MIME type if provided
  • $_FILES['mkfile']['size']
    • size in bytes
  • $_FILES['mkfile']['tmp_name']
    • tmp file name on server
  • $_FILES['mkfile']['error']
    • error code

Potential Errors

  • UPLOAD_ERR_OK [0]
    • no error, file upload successful
  • UPLOAD_ERR_INI_SIZE [1]
    • uploaded file exceeds upload_max_filesize in php.ini
  • UPLOAD_ERR_FORM_SIZE [2]
    • uploaded file exceeds MAX_FILE_SIZE specified in HTML form
  • UPLOAD_ERR_PARTIAL [3]
    • file was only partially uploaded
  • UPLOAD_ERR_NO_FILE [4]
    • no file uploaded
  • UPLOAD_ERR_NO_TMP_DIR [6]
    • missing temporary folder
  • UPLOAD_ERR_CANT_WRITE [7]
    • write file to disk failed
  • UPLOAD_ERR_EXTENSION [8]
    • PHP extension stopped the file upload

PHP Example of File Upload

<?php
$uploaddir = '/home/mkelly/cs418/uploads/';
$uploadfile = $uploaddir . basename($_FILES['mkfile']['name']);

if (move_uploaded_file($_FILES['mkfile']['tmp_name'],$uploadfile)) {
	echo "File is valid, and was successfully uploaded.\n";
} else {
	echo "Possible file upload attack!\n";
}

print_r($_FILES);
?>
  • $uploaddir - must have write permissions (chmod 777)
  • Demo