amitshree
amitshree

Reputation: 2298

PHP file upload/move doesn't work

I'm trying to move/copy/upload an image from tmp directory to another directory using following code, but I don't see my image being moved/copied to the destination. Is there any alternative?

    public function uploadToS3($file, $tmp_url) {
    if (strrpos($file, '.tmp') == strlen($file)-4) {
                $file = substr($file, 0, strlen($file)-4);
            }
        $destination = "var/www/html/image" . $file;

    if (file_exists($destination)) {
        echo 'File '. $destination. ' already exists!';
    } else {
    move_uploaded_file($tmp_url, $destination);
    }
}
    //Ex: $tmp_url = http://localhost/mage/media/tmp/catalog/product/s/c/abc.png
    //Ex: $destination = /var/www/html/image/s/c/abc.png

Following comments below I've tried following php code which fails too

 <?php
$tmp_url = "var/www/html/abc/abc.png";
$destination = "var/www/html/des/abc.png";
 if(move_uploaded_file($tmp_url, $destination)){echo "success";}else{echo "fail";} 

Upvotes: 2

Views: 2377

Answers (2)

user5134807
user5134807

Reputation:

When it comes to uploading files it's always a good idea to construct the destination in a full path manner - why not create a global helper that gives you access to your base path:

/**
 * Return the base path.
 *
 * @param void
 * @return string
 */
function base_path()
{
    // I go back 2 directories here - it all depends where
    // you decide to place this global helper function.
    return realpath(__DIR__ . '/../..');
}

Great, now this is available globally, you may decide to use it like so:

$destination = base_path() . '/var/www/html/image';

This way, you don't have to worry about your current location - it's just too easy.

Upvotes: 0

H.Dave
H.Dave

Reputation: 21

Also please check the destination image folder has 777 / 775 permission

$ImageName = $_FILES['file']['name'];
$fileElementName = 'file';
$path = 'var/www/html/image/'; 
$location = $path . $_FILES['file']['name']; 
move_uploaded_file($_FILES['file']['tmp_name'], $location);

Upvotes: 1

Related Questions