Last active
March 9, 2016 16:17
-
-
Save FedericoPonzi/2688b349b0cd8702afe1 to your computer and use it in GitHub Desktop.
A simple image uploader in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* A simple image uploader | |
* Federico Ponzi | |
*/ | |
/* Config: **/ | |
// Base url, for the json response: | |
define ("BASE_URL", "http://127.0.0.1/"); | |
// Where to put the images: | |
define ("UPLOADS_DIR", "uploads/"); | |
//Max filesize in bytes: | |
define ("MAX_FILESIZE", "500000"); | |
$response['status'] = "error"; | |
/** | |
* @return True, if the file is an image | |
*/ | |
function isImage() | |
{ | |
$target_file = $_FILES["fileToUpload"]["tmp_name"]; | |
$check = getimagesize($target_file); | |
$image_type = $check[2]; | |
if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP))) | |
{ | |
return true; | |
} | |
return false; | |
} | |
/** | |
* @return true if the file is too big | |
*/ | |
function fileTooBig() | |
{ | |
return $_FILES["fileToUpload"]["size"] > MAX_FILESIZE; | |
} | |
/** | |
* It returns a unique random file (based on the files list in UPLOADS_DIR | |
*/ | |
function getUniqueName($fileName) | |
{ | |
while(file_exists(UPLOADS_DIR . $fileName)) | |
{ | |
$fileName = bin2hex(openssl_random_pseudo_bytes(10)) . $fileName; | |
//Generate random name. | |
} | |
return $fileName; | |
} | |
//The main script: | |
if(isset($_FILES['fileToUpload']["name"])) | |
{ | |
if(!isImage()) | |
{ | |
$response['error'] = "Wrong file type error."; | |
} | |
else if(fileTooBig()) | |
{ | |
$response['error'] = "The image is too big."; | |
} | |
else if (!move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], ($fileName = UPLOADS_DIR . getUniqueName(basename($_FILES["fileToUpload"]["name"]))))) { | |
$response['error'] = "Can't complete the upload due to a Server error."; | |
} | |
else | |
{ | |
$response['status'] = "ok"; | |
$response['path'] = BASE_URL . UPLOADS_DIR . $fileName; | |
} | |
} | |
else | |
{ | |
$response['error'] = "No file uploaded."; | |
} | |
header('Content-Type: application/json'); | |
echo json_encode($response); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment