PHP   72

upload.php

Guest on 14th September 2021 09:04:03 PM

  1. <?php
  2. header('Content-Type: application/json; charset=utf-8');
  3. header("Access-Control-Allow-Origin: *");
  4. header("Access-Control-Allow-Methods: PUT, GET, POST");
  5.  
  6.  
  7.  
  8. $response = array();
  9. $upload_dir = 'uploads/';
  10. $server_url = 'http://127.0.0.1:8000';
  11.  
  12. if($_FILES['avatar'])
  13. {
  14.     $avatar_name = $_FILES["avatar"]["name"];
  15.     $avatar_tmp_name = $_FILES["avatar"]["tmp_name"];
  16.     $error = $_FILES["avatar"]["error"];
  17.  
  18.     if($error > 0){
  19.         $response = array(
  20.             "status" => "error",
  21.             "error" => true,
  22.             "message" => "Error uploading the file!"
  23.         );
  24.     }else
  25.     {
  26.         $random_name = rand(1000,1000000)."-".$avatar_name;
  27.         $upload_name = $upload_dir.strtolower($random_name);
  28.         $upload_name = preg_replace('/\s+/', '-', $upload_name);
  29.    
  30.         if(move_uploaded_file($avatar_tmp_name , $upload_name)) {
  31.             $response = array(
  32.                 "status" => "success",
  33.                 "error" => false,
  34.                 "message" => "File uploaded successfully",
  35.                 "url" => $server_url."/".$upload_name
  36.               );
  37.         }else
  38.         {
  39.             $response = array(
  40.                 "status" => "error",
  41.                 "error" => true,
  42.                 "message" => "Error uploading the file!"
  43.             );
  44.         }
  45.     }
  46.  
  47.  
  48.  
  49.    
  50.  
  51. }else{
  52.     $response = array(
  53.         "status" => "error",
  54.         "error" => true,
  55.         "message" => "No file was sent!"
  56.     );
  57. }
  58.  
  59. echo json_encode($response);
  60. ?>

Raw Paste


Login or Register to edit or fork this paste. It's free.