Last active
August 9, 2021 05:58
-
-
Save Ayubur/798659b6ec29e8291e96d7f8ad23ce64 to your computer and use it in GitHub Desktop.
PHP Single Image Upload REST API
This file contains 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 | |
// Include the database configuration file | |
include '/server/connection.php'; | |
if(is_uploaded_file($_FILES['file']['tmp_name'])){ | |
// File upload path | |
$targetDir = "../uploads/"; | |
$file=$_FILES['file']['tmp_name']; | |
$fileName = time()."-".$_FILES['file']['name']; | |
$targetFilePath = $targetDir . $fileName; | |
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); | |
$allowTypes = array('jpg','png','jpeg'); // allowed image extensions | |
//checking extensions | |
if(in_array($fileType, $allowTypes)){ | |
// Upload file to server | |
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ | |
$query= $db->query($checkstmt); // $checkstmt refers to db query statement, executing query statement | |
if($query){ | |
if($query){ | |
echo json_encode(array("success_message" => "File has been uploaded successfully")); | |
}else{ | |
echo json_encode(array("error_message" => "File upload failed, please try again.")); | |
} | |
} | |
}else{ | |
echo json_encode(array("error_message" => "Sorry, there was an error uploading your file.")); | |
} | |
}else{ | |
echo json_encode(array("error_message" => "Sorry, only JPG, JPEG, PNG files are allowed to upload")); | |
} | |
}else{ | |
echo json_encode(array("error_message" => "Data incomplete")); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment