Search code examples
phparrayspathinfo

PHP : How to properly use pathinfo after using base64 decode


I'm getting an error Array to string conversion at pathinfo after using base64 decode image. Error occurs when trying to put my files into diretory. I need to maintain the name of the image.

BTW my image files came from js DOM

var formG = new FormData();
for(var i=0; i<imageTrust.length;i++){
    formG.append('file_multiImage[]', imageTrust[i]);
}


if(isset($_POST['file_multiImage'])){
    $multi_image =  $_POST['file_multiImage'];
    foreach ($multi_image as $key => $value) {
        $staticName = $event_id.'conNo'.$finalContestantNum;
        $data = str_replace('data:image/jpeg;base64,', '', $value);
        $data = str_replace(' ', '+', $data);
        $data = base64_decode($data);
        $file = pathinfo( $staticName . PATHINFO_EXTENSION); //Error occurs here
        file_put_contents($theDir.'/'. $file, $data);

    }
}

The array result

Array(
       [0] => data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQA 
       [1] => data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAlgCWAAD
       [2] => data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QC
)
//I did not just continue strings are too long

Solution

  • There is syntax issue that the parser wouldn't have detected.

    $file = pathinfo( $staticName . PATHINFO_EXTENSION);

    change to

    $file = pathinfo( $staticName , PATHINFO_EXTENSION);

    however, your next usage of $file seems invalid, creating a malformed filename for the file_put_contents() call. By specifying PATHINFO_EXTENSION you are picking just the extension from the filename, which doesn't appear to exist.