0

im new here, hope to grow into this community. I am currently learning php and i am making a program to upload a file. i found a tutorial with some code that makes a little sense to me but not really as i dont understand the lingo in php too well yet... so i have made the api to upload an image and i am testing via postman... so when i test im running a command in json to say {"upfile":"*whatever the base 64 encode is*"}.when i run this i get an error saying

Warning: Undefined array key "upfile" in C:\xampp\htdocs\upload.php on line 37

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\upload.php on line 37

i have tried to remove the ! from an if statement, which i will show below, but that give an invalid parameters error instead... any idea what i am doing wrong?

<?php

header('Content-Type: text/plain; charset=utf-8');

$server_url = '/xampp/htdocs';
$uploadDirectory = "/pic/";

$target_dir = $server_url.$uploadDirectory; // add the specific path to save the file

//$headers = getRequestHeaders();
//
//$arr = array();
//
//foreach ($headers as $header => $value) {
////    echo "$header: $value <br />\n";
//    array_push($arr,"$header: $value");
//}
//
//
////    $arr = array('result'=>'mime type '.$mime_type,'ext '=>$ext);
//    throw new RuntimeException(json_encode(print_r($arr)));

//    echo json_encode('mime_type = '.$mime_type.' extension = '.$ext);

try {
//echo 'Files Array ';
//echo "\r\n";
//echo print_r($_FILES);

//    throw new RuntimeException(json_encode($_FILES['upfile']['tmp_name']));
//die('here');

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
     isset($_FILES['upfile']['error']) ||     //if i use !isset,  i get invalid parameters
        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'] > 1000000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $_FILES['upfile']['tmp_name']);
//    $mime_type = finfo_buffer(finfo_open(), $_FILES['upfile']['name'], FILEINFO_MIME_TYPE); // extract mime type
    $ext = mime2ext($mime_type); // extract extension from mime type


    $ext1 = mime2ext($_FILES['upfile']['type']);

    if ($ext !== $ext1) {
        $ext=$ext1;
    }


//    $arr = array('result'=>'mime type '.$mime_type,'ext '=>$ext);
//    throw new RuntimeException(json_encode($arr));

//    echo json_encode('mime_type = '.$mime_type.' extension = '.$ext.' FILES type = '.$_FILES['upfile']['type'].' exte 1 = '.$ext1);

//
//
//    // 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.

    $newfilename = uniqid();//sha1_file($_FILES['upfile']['tmp_name']);

    $file = $newfilename.".".$ext;

    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf($target_dir.'%s.%s',
            $newfilename,
            $ext
        )
    )) {
        $arr = array('result'=>'Failed to move uploaded file.','filename'=>$file);
        throw new RuntimeException(json_encode($arr));
    }



    $arr = array('result'=>'File Uploaded Sucessfully','filename'=>$file);
//        echo json_encode("File Uploaded Successfully");
    echo json_encode($arr);
//    echo json_encode();

} catch (RuntimeException $e) {

    echo $e->getMessage();

}

function mime2ext($mime){
    $all_mimes = '{"png":["image\/png","image\/x-png"],"bmp":["image\/bmp","image\/x-bmp",
"image\/x-bitmap","image\/x-xbitmap","image\/x-win-bitmap","image\/x-windows-bmp",
"image\/ms-bmp","image\/x-ms-bmp","application\/bmp","application\/x-bmp",
"application\/x-win-bitmap"],"gif":["image\/gif"],"jpeg":["image\/jpeg",
"image\/pjpeg"],"xspf":["application\/xspf+xml"],"vlc":["application\/videolan"],
"wmv":["video\/x-ms-wmv","video\/x-ms-asf"],"au":["audio\/x-au"],
"ac3":["audio\/ac3"],"flac":["audio\/x-flac"],"ogg":["audio\/ogg",
"video\/ogg","application\/ogg"],"kmz":["application\/vnd.google-earth.kmz"],
"kml":["application\/vnd.google-earth.kml+xml"],"rtx":["text\/richtext"],
"rtf":["text\/rtf"],"jar":["application\/java-archive","application\/x-java-application",
"application\/x-jar"],"zip":["application\/x-zip","application\/zip",
"application\/x-zip-compressed","application\/s-compressed","multipart\/x-zip"],
"7zip":["application\/x-compressed"],"xml":["application\/xml","text\/xml"],
"svg":["image\/svg+xml"],"3g2":["video\/3gpp2"],"3gp":["video\/3gp","video\/3gpp"],
"mp4":["video\/mp4"],"m4a":["audio\/x-m4a"],"f4v":["video\/x-f4v"],"flv":["video\/x-flv"],
"webm":["video\/webm"],"aac":["audio\/x-acc"],"m4u":["application\/vnd.mpegurl"],
"pdf":["application\/pdf","application\/octet-stream"],
"pptx":["application\/vnd.openxmlformats-officedocument.presentationml.presentation"],
"ppt":["application\/powerpoint","application\/vnd.ms-powerpoint","application\/vnd.ms-office",
"application\/msword"],"docx":["application\/vnd.openxmlformats-officedocument.wordprocessingml.document"],
"xlsx":["application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application\/vnd.ms-excel"],
"xl":["application\/excel"],"xls":["application\/msexcel","application\/x-msexcel","application\/x-ms-excel",
"application\/x-excel","application\/x-dos_ms_excel","application\/xls","application\/x-xls"],
"xsl":["text\/xsl"],"mpeg":["video\/mpeg"],"mov":["video\/quicktime"],"avi":["video\/x-msvideo",
"video\/msvideo","video\/avi","application\/x-troff-msvideo"],"movie":["video\/x-sgi-movie"],
"log":["text\/x-log"],"txt":["text\/plain"],"css":["text\/css"],"html":["text\/html"],
"wav":["audio\/x-wav","audio\/wave","audio\/wav"],"xhtml":["application\/xhtml+xml"],
"tar":["application\/x-tar"],"tgz":["application\/x-gzip-compressed"],"psd":["application\/x-photoshop",
"image\/vnd.adobe.photoshop"],"exe":["application\/x-msdownload"],"js":["application\/x-javascript"],
"mp3":["audio\/mpeg","audio\/mpg","audio\/mpeg3","audio\/mp3"],"rar":["application\/x-rar","application\/rar",
"application\/x-rar-compressed"],"gzip":["application\/x-gzip"],"hqx":["application\/mac-binhex40",
"application\/mac-binhex","application\/x-binhex40","application\/x-mac-binhex40"],
"cpt":["application\/mac-compactpro"],"bin":["application\/macbinary","application\/mac-binary",
"application\/x-binary","application\/x-macbinary"],"oda":["application\/oda"],
"ai":["application\/postscript"],"smil":["application\/smil"],"mif":["application\/vnd.mif"],
"wbxml":["application\/wbxml"],"wmlc":["application\/wmlc"],"dcr":["application\/x-director"],
"dvi":["application\/x-dvi"],"gtar":["application\/x-gtar"],"php":["application\/x-httpd-php",
"application\/php","application\/x-php","text\/php","text\/x-php","application\/x-httpd-php-source"],
"swf":["application\/x-shockwave-flash"],"sit":["application\/x-stuffit"],"z":["application\/x-compress"],
"mid":["audio\/midi"],"aif":["audio\/x-aiff","audio\/aiff"],"ram":["audio\/x-pn-realaudio"],
"rpm":["audio\/x-pn-realaudio-plugin"],"ra":["audio\/x-realaudio"],"rv":["video\/vnd.rn-realvideo"],
"jp2":["image\/jp2","video\/mj2","image\/jpx","image\/jpm"],"tiff":["image\/tiff"],
"eml":["message\/rfc822"],"pem":["application\/x-x509-user-cert","application\/x-pem-file"],
"p10":["application\/x-pkcs10","application\/pkcs10"],"p12":["application\/x-pkcs12"],
"p7a":["application\/x-pkcs7-signature"],"p7c":["application\/pkcs7-mime","application\/x-pkcs7-mime"],"p7r":["application\/x-pkcs7-certreqresp"],"p7s":["application\/pkcs7-signature"],"crt":["application\/x-x509-ca-cert","application\/pkix-cert"],"crl":["application\/pkix-crl","application\/pkcs-crl"],"pgp":["application\/pgp"],"gpg":["application\/gpg-keys"],"rsa":["application\/x-pkcs7"],"ics":["text\/calendar"],"zsh":["text\/x-scriptzsh"],"cdr":["application\/cdr","application\/coreldraw","application\/x-cdr","application\/x-coreldraw","image\/cdr","image\/x-cdr","zz-application\/zz-winassoc-cdr"],"wma":["audio\/x-ms-wma"],"vcf":["text\/x-vcard"],"srt":["text\/srt"],"vtt":["text\/vtt"],"ico":["image\/x-icon","image\/x-ico","image\/vnd.microsoft.icon"],"csv":["text\/x-comma-separated-values","text\/comma-separated-values","application\/vnd.msexcel"],"json":["application\/json","text\/json"]}';
    $all_mimes = json_decode($all_mimes,true);
    foreach ($all_mimes as $key => $value) {
        if(array_search($mime,$value) !== false) return $key;
    }
    return false;
}

function getRequestHeaders() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
            continue;
        }
        $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$header] = $value;
    }
    return $headers;
}


?> 
UltimateMaster
  • 11
  • 1
  • 1
  • 5
  • Can you please be specific in your explanation of what you are actually doing in postman? It sounds like that was wrong to begin with. Normal HTTP file uploads are not send as base64 or JSON. – CBroe Jan 27 '21 at 08:34
  • on postman i am trying to simulate uploading the file, so im calling the url and inserting the base64 encode and posting – UltimateMaster Jan 27 '21 at 08:40
  • But why base64? PHP will not populate $_FILES, if you send JSON containing some base64 encoded stuff. In the body panel, you need to set the type to `form-data`, and then add a parameter of type `file`. – CBroe Jan 27 '21 at 08:44
  • how would i go about doing that? – UltimateMaster Jan 27 '21 at 08:50
  • I don’t get the question, did I not just say how? What about that is unclear? // Maybe you should not play on too many fields where you still lack base knowledge at the same time - instead of using postman, perhaps rather start with a simple HTML form to upload a file via the browser, as explained under https://www.php.net/manual/en/features.file-upload.post-method.php – CBroe Jan 27 '21 at 09:17

5 Answers5

3

To check if key exists, you should use array_key_exists ( string|int $key , array $array ) : bool Doc.

So your code should be like:

if(array_key_exists('upfile', $_FILES) && array_key_exists('error', $_FILES['upfile'])

OR

if(array_key_exists('upfile', $_FILES)){
   if(array_key_exists('error', $_FILES['upfile'])
}
MaxiGui
  • 6,190
  • 4
  • 16
  • 33
1

Check if you are using enctype="multipart/form-data"

as stated here in this answer

When you are writing client-side code:

  • use multipart/form-data when your form includes any <input type="file"> elements
Kym NT
  • 670
  • 9
  • 28
0

If your migration image field is like this

$table->string('image');

and you don't insert image while submitting form it will throw an error like this

Error: Undefined array key "image"

So, in validation and migration you should pass nullable().

$table->string('image')->nullable();

MShaba007
  • 56
  • 4
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 20 '22 at 20:11
0

Ensure after the form POST you declare enctype="multipart/form-data

<form action="upload.php" method="post" enctype="multipart/form-data">

That will solve your headache.

-1

In Your you just have to make a pic folder on current directory and use "$target_dir"

$target_dir ='pic/';

Example of Uploading File in Php :

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

php code :

<?php
$target_d

ir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
      $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
      if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
      } else {
        echo "File is not an image.";
        $uploadOk = 0;
      }

  

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

$query = "INSERT INTO table  (`image_path`) VALUES ('$target_file')
";
            echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
          } else {
            echo "Sorry, there was an error uploading your file.";
          }
    
    
        }
        ?>

base 64 code for image in db :

 $data = file_get_contents($_FILES['name_of_control']['tmp_name']);
$data = mysql_real_escape_string($data);

$query = "
  INSERT INTO table
    (`blob_column`)
  VALUES
    ('$data')
";

mysql_query($query);
Hammad Ahmed khan
  • 1,618
  • 7
  • 19