Sunny Books
What we have

PHP image upload

Some websites may need the functionality to allow users to upload images. By using the global PHP $_FILES array we can creat an image upload script to upload files from a client computer to the remote server.

Sometimes uploading file to the server may cause security issue, just make sure only allow trusted users to upload certain types and certain size of file.

Here is the script of uploading images. first of all we need a form to let users select an image and upload. Then PHP manages the uploaded file.

// form
echo "<form action=\"\" method=\"post\"
<label for=\"file\">Filename:</label>
<input type=\"file\" name=\"uploadedfile\" id=\"file\"><br>
<input type=\"submit\" name=\"submit\" value=\"Submit\">

$validate = 0;
$allowedExts = array("jpg", "jpeg", "gif", "png");
$allowedTypes = $allowedExts;
$target_path = "uploads/";

foreach ($allowedTypes as &$val) {
	$val = "image/".$val;

$extension = end(explode(".", $_FILES["uploadedfile"]["name"]));
// check if uploaded file is valid or not
if(in_array($_FILES["uploadedfile"]["type"],$allowedTypes) && 
  in_array($extension, $allowedExts) && $_FILES["uploadedfile"]["size"] < 200000 && 
  $_FILES["uploadedfile"]["error"]==0) {
  $validate = 1;

// upload image
if($validate=1) {
  $target_file = $target_path . basename( $_FILES['uploadedfile']['name']);
  if (file_exists($target_file){
    echo basename( $_FILES['uploadedfile']['name'] . " already exists. ";
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_file)) {
        echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
        " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";