Skip to content

Instantly share code, notes, and snippets.

@techiediaries
Created March 6, 2019 20:06
Show Gist options
  • Save techiediaries/63ff058114e473d4ebaadce294ce09d5 to your computer and use it in GitHub Desktop.
Save techiediaries/63ff058114e473d4ebaadce294ce09d5 to your computer and use it in GitHub Desktop.
PHP Upload File Script
<?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