PHP upload image

前端 未结 10 2460
不知归路
不知归路 2020-12-06 01:46

Alright I have way to much time invested in this. I am new to PHP programming and trying to grasp the basics, but I am a little lost as of last night I was able to get a PHP

10条回答
  •  不思量自难忘°
    2020-12-06 02:19

    I would recommend you to save the image in the server, and then save the URL in MYSQL database.

    First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.

    1. Check the image

      if (empty($_FILES['image']))
        throw new Exception('Image file is missing');
      
    2. Save the image in a variable

      $image = $_FILES['image'];
      
    3. Check the upload time errors

      if ($image['error'] !== 0) {
         if ($image['error'] === 1) 
            throw new Exception('Max upload size exceeded');
      
         throw new Exception('Image uploading error: INI Error');
      }
      
    4. Check whether the uploaded file exists in the server

      if (!file_exists($image['tmp_name']))
          throw new Exception('Image file is missing in the server');
      
    5. Validate the file size (Change it according to your needs)

       $maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
          if ($image['size'] > $maxFileSize)
              throw new Exception('Max size limit exceeded'); 
      
    6. Validate the image (Check whether the file is an image)

       $imageData = getimagesize($image['tmp_name']);
           if (!$imageData) 
           throw new Exception('Invalid image');
      
    7. Validate the image mime type (Do this according to your needs)

       $mimeType = $imageData['mime'];
       $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
       if (!in_array($mimeType, $allowedMimeTypes)) 
          throw new Exception('Only JPEG, PNG and GIFs are allowed');
      

    This might help you to create a secure image uploading script with PHP.

    Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql

    Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.

    Thank you.

提交回复
热议问题