sathish sathish - 7 months ago 10
PHP Question

PHP Coding for downloading the image

Browser download location
In the website page contains many images with downloading options. If I click the download button it automatically downloaded on user system and it shows on browser downloadable page. I have PHP code like

$image = file_get_contents('http://website.com/images/logo.png');
file_put_contents('C:/Users/ASUS/Downloads/image.jpg', $image);


Above coding is working fine. But I need to provide the path name for image to save. In user side we don`t know the path.

I need the PHP code to use the browser download location and download images need to show the browser downloads.

Answer

you have to save/download the image somewhere on your web serwer and next send the file to user using header function, for example:

$file = 'path_to_image';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
else {
    echo "file not exists";
}

manual

Comments