phpjsonextjs

PHP - Getting the filepath of the file after uploading to server


I am uploading an image file to my PHP server. I am successfully uploading the file to a folder. What I want to do now is as I assemble my JSON response, I want to get the new file path of the file so I would know where it is programmatically.

Here is my php code so far:

<?php
header('Content-Type: text/html; charset=utf-8');

    if (
        !isset($_FILES['fileToUpload']['error']) ||
        is_array($_FILES['fileToUpload']['error'])
    ) {
        die(json_encode(array(
            'success' => false,
            'status' => "Invalid Parameters. - 1",
            'files' => $_FILES 
        )));
    }

    // Check $_FILES['fileToUpload']['error'] value.
    switch ($_FILES['fileToUpload']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:

            die(json_encode(array(
                'success' => false,
                'status' => "No file sent. - 2",
                'files' => $_FILES
            )));

        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            die(json_encode(array(
                'success' => false,
                'status' => "Exceeded filesize limit. - 3",
                'files' => $_FILES
            )));

        default:
            die(json_encode(array(
                'success' => false,
                'status' => "Unknown errors. - 4",
                'files' => $_FILES
            )));

    }

    // You should also check filesize here. 
    if ($_FILES['fileToUpload']['size'] > 1000000) {
            die(json_encode(array(
                'success' => false,
                'status' => "Exceeded File Size Limit. - 5",
                'files' => $_FILES
            )));

    }

    // DO NOT TRUST $_FILES['fileToUpload']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE); 
    if (false === $ext = array_search(
        $finfo->file($_FILES['fileToUpload']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ),
        true
    )) {
        die(json_encode(array(
            'success' => false,
            'status' => "Invalid file format. - 6",
            'files' => $_FILES
        )));

    }

    // You should name it uniquely.
    // DO NOT USE $_FILES['fileToUpload']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['fileToUpload']['tmp_name'],
        sprintf('./gallery/%s.%s',
            sha1_file($_FILES['fileToUpload']['tmp_name']),
            $ext
        )
    )) {
        die(json_encode(array(
            'success' => false,
            'status' => "Failed to move uploaded file. - 7",
            'files' => $_FILES
        )));

    }
        $filePathFull = sprintf('./gallery/%s.%s',
            sha1_file($_FILES['fileToUpload']['tmp_name']);

        $uploaddir = '/gallery/';
        $uploadfile = $uploaddir . basename($_FILES['fileToUpload']['tmp_name']);


        die(json_encode(array(
            'success' => true,
            'status' => "File is uploaded successfully. - 8",
            'files' => $_FILES,
            'filePath' => $uploadfile
        )));
?>

I am trying to get the new file path which is /gallery/ + the filename, however, I am getting an invalid JSON Object when I process it in my ExtJS part.

What can I try next? I also tried sprintf('./gallery/%s.%s', sha1_file($_FILES['fileToUpload']['tmp_name']); but that doesn't seem to work.

Edit

So far this works:

$uploaddir = '/gallery/';
$uploadFile = $uploaddir . basename($_FILES['fileToUpload']['tmp_name']);

die(json_encode(array(
    'success' => true,
    'status' => "File is uploaded successfully. - 8",
    'filePath' => $uploadFile
)));

However, I don't have the file extension and I get something like: /gallery/phptnLZJm but upon checking, an image is actually uploaded but the filename is off.


Solution

  • I made it work. I think it sha1_file was the issue. The code is now:

        if (!move_uploaded_file(
            $_FILES['fileToUpload']['tmp_name'],
            sprintf('./gallery/%s.%s',
                basename($_FILES['fileToUpload']['tmp_name']),
                $ext
            )
        )) {
            die(json_encode(array(
                'success' => false,
                'status' => "Failed to move uploaded file. - 7",
                'files' => $_FILES
            )));
    
        }
    //          $uploadFile = sprintf('./gallery/%s.%s',
    //              sha1_file($_FILES['fileToUpload']['tmp_name']);
    
            $uploaddir = '/gallery/';
    //          $uploadFile = $uploaddir . basename($_FILES['fileToUpload']['tmp_name']);
            $name = $_FILES["fileToUpload"]["tmp_name"];
    
            $fullPath = sprintf('/gallery/%s.%s',
                basename($_FILES['fileToUpload']['tmp_name']),
                $ext
            );
    
            die(json_encode(array(
                'success' => true,
                'status' => "File is uploaded successfully. - 8",
                'filePath' => "$fullPath"
            )));
    

    Before, I would call sha1_file instead of basename as I am assembling my $fullPath, and I don't know why. Was it because it was moved already and now has a different name?