-1

I'm testing php 7.4 on file upload errors I have 2 files:

  1. testscript.html (html form)
  2. testscript.php

Error = Invalid parameters when uploading an image jpg or png

<html>
<head></head>
<body>
  <form action="testscript.php" method="post">
    <input type="file"
       id="upfile" name="upfile"
       accept="image/png, image/jpeg">
    <input type="submit" value="send">
  </form>
</body>
</html>

Here is the php script Found it here: https://www.php.net/manual/en/features.file-upload.php

I'm testing out Magento 2 and first problem I came across is that the front-end doesn't show images. I can't even upload images. It seems broken in the back-end.

   <?php
    
    header('Content-Type: text/plain; charset=utf-8');
    
    try {
    
    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
        !isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }
    
    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }
    
    // You should also check filesize here.
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }
    
    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }
    
    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }
    
    echo 'File is uploaded successfully.';
    
    } catch (RuntimeException $e) {
    
    echo $e->getMessage();
    
    }
    
    ?>
Yori
  • 5
  • 2

1 Answers1

1

Missing enctype='multipart/form-data' in your <form> tag This value is necessary if the user will upload a file through the form

Kindly read this

https://www.w3schools.com/tags/att_form_enctype.asp

Milad Elyasi
  • 789
  • 4
  • 12