Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. <?php
  2.  
  3.     if(isset($_FILES['avatar'])){
  4.  
  5.         // Let's store that bad boy in a variable
  6.         $img = $_FILES['avatar'];
  7.  
  8.         // In what folder do we want to save the file in?
  9.         $folder = "uploads";
  10.  
  11.         // Let's find that extension
  12.         $extension = pathinfo($img['name'], PATHINFO_EXTENSION);
  13.  
  14.         // Generate a 'random' name
  15.         $randomFileName = time() . ".$extension"; // Example: 123124124.png
  16.  
  17.         // The new generated file name that points to the location that we want the file to be in
  18.         $fullFileName = $folder . "/" . $randomFileName; // Example: uploads/123124124.png
  19.  
  20.         // If it has to be an IMAGE:
  21.         $isImage = getimagesize($img['tmp_name']);
  22.         if(!$isImage) {
  23.             $error = "The file has to be an image!";
  24.         }
  25.  
  26.         // If it has to be an IMAGE:
  27.         $size = filesize($img['tmp_name']);
  28.         if($size > 2097152) { // 2MB
  29.             $error = "This file is too large. It must be smaller than 2MB!";
  30.         }
  31.  
  32.         // If there are no errors, let's move the file
  33.         if(!isset($error)){
  34.  
  35.             // Try to move the file
  36.             $upload = move_uploaded_file($img['tmp_name'], $fullFileName);
  37.             if($upload){
  38.                 // Yay! It is uploaded.
  39.             } else {
  40.                 $error = "File could not be uploaded. Such a shame!";
  41.             }
  42.         }
  43.     }
  44.  
  45. ?>
  46.  
  47. <form action="upload.php" enctype="multipart/form-data" method="POST">
  48.  
  49.     <?php if(isset($error)) echo $error ?>
  50.  
  51.     <input type="file" name="avatar">
  52.     <input type="submit">
  53. </form>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement