Created
April 28, 2019 22:22
-
-
Save techiediaries/effb110532168444319c677cdbf5b4b3 to your computer and use it in GitHub Desktop.
PHP File Upload Example
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 | |
header('Content-Type: application/json; charset=utf-8'); | |
header("Access-Control-Allow-Origin: *"); | |
header("Access-Control-Allow-Methods: PUT, GET, POST"); | |
$response = array(); | |
$upload_dir = 'uploads/'; | |
$server_url = 'http://127.0.0.1:8000'; | |
if($_FILES['avatar']) | |
{ | |
$avatar_name = $_FILES["avatar"]["name"]; | |
$avatar_tmp_name = $_FILES["avatar"]["tmp_name"]; | |
$error = $_FILES["avatar"]["error"]; | |
if($error > 0){ | |
$response = array( | |
"status" => "error", | |
"error" => true, | |
"message" => "Error uploading the file!" | |
); | |
}else | |
{ | |
$random_name = rand(1000,1000000)."-".$avatar_name; | |
$upload_name = $upload_dir.strtolower($random_name); | |
$upload_name = preg_replace('/\s+/', '-', $upload_name); | |
if(move_uploaded_file($avatar_tmp_name , $upload_name)) { | |
$response = array( | |
"status" => "success", | |
"error" => false, | |
"message" => "File uploaded successfully", | |
"url" => $server_url."/".$upload_name | |
); | |
}else | |
{ | |
$response = array( | |
"status" => "error", | |
"error" => true, | |
"message" => "Error uploading the file!" | |
); | |
} | |
} | |
}else{ | |
$response = array( | |
"status" => "error", | |
"error" => true, | |
"message" => "No file was sent!" | |
); | |
} | |
echo json_encode($response); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment