How to upload image in php ?

<?php

header('Content-Type: application/json');

include '../connection.php';

$target_dir = "../upload/profile/";
$userId = $_POST['userId'];

$target_file = $target_dir . basename($_FILES["profile_photo"]["name"]);

$message="";
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["profile_photo"]["tmp_name"]);
if($check !== false) {
        // echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$message =  "File is not an image.";
$uploadOk = 0;
}

// Check if file already exists
if (file_exists($target_file)) {
$message = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["profile_photo"]["size"] > 500000) {
$message = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
$temp = explode(".", $_FILES["profile_photo"]["name"]);
$newfilename = "mysmartapp_". $userId . '.' . end($temp);
$newfilename = $target_dir . $newfilename;

if (move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $newfilename)) {
$message = "Profile Photo Uploaded.";
// echo "The file ". basename( $_FILES["profile_photo"]["name"]). " has been uploaded.";
$uploadOk = 1;
} else {
$message = "Sorry, there was an error uploading your file.";
$uploadOk = 0;
}

if ($uploadOk == 1) {
$status = TRUE;
}else{
$status = FALSE;
}

echo json_encode(array("status" => $status ,"message" => $message,"profile_photo" => $newfilename));

?>

Comments

Popular posts from this blog

How to Fix ‘This file name is too long’ Error?

General Knowledge