Upload Image in PHP

Total Views : 381
Zoom In Zoom Out Read Later Print

A code snippet for image upload in php, this code will allow you to upload images in php and you can change it to upload file other then images.

Code for file selection

file.php

<!DOCTYPE html>
<html>
<body>
<form name="form" action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="U_FILE" >
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

Code for uploading image

upload.php


<?php
if (isset($_POST["submit"])) {
// image mime to be checked
$imagetype = array(image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_JPEG),
image_type_to_mime_type(IMAGETYPE_PNG), image_type_to_mime_type(IMAGETYPE_BMP));

$error_msg = "";
$noERROR = false;
$FOLDER = "uploads/";
$keepName = false;
if ($_FILES["U_FILE"]["name"] <> "" && $_FILES["U_FILE"]["error"] == 0) {
// file is OK
if (in_array($_FILES["U_FILE"]["type"], $imagetype)) {
// Setting an unique name for the file
if($keepName) {
$file_name = $_FILES["U_FILE"]["name"];
} else {
// get file extention
$file_extention = @strtolower(@end(@explode(".", $_FILES["U_FILE"]["name"])));
$file_name = date("Ymd") . '_' . rand(10000, 990000) . '.' . $file_extention;
}

if (move_uploaded_file($_FILES["U_FILE"]["tmp_name"], $FOLDER . $file_name) === FALSE) {
$error_msg = "Error while uploading the file";
} else {
$noERROR = true;
echo json_encode(array ('error'=>false,'msg'=>"File Uploaded",'fileName'=>$file_name));
}
} else {
$error_msg = "File is not a valid image type.";
}

if ($noERROR === FALSE) {
// Failed to upload file
echo json_encode(array ('error'=>true,'msg'=>$error_msg));
}
}
} else {
echo "Hello";
}
?>

See More

Latest Photos