User9123
User9123

Reputation: 47

PHP Download image and redirect external url

I want to download image and redirect to specific external url in PHP.

I have this code,

$file_name = '1.png';
  // make sure it's a file before doing anything!
  if( !is_file($file_name) )
    exit();
  // required for IE
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
  // get the file mime type using the file extension
  switch(strtolower(substr(strrchr($file_name,'.'),1)))
  {
    case 'pdf': $mime = 'application/pdf'; break;
    case 'zip': $mime = 'application/zip'; break;
    case 'jpeg':
    case 'jpg': $mime = 'image/jpg'; break;
    case 'png': $mime = 'image/png'; break;
    default: exit();
  }
  header('Pragma: public');     // required
  header('Expires: 0');     // no cache
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
  header('Cache-Control: private',false);
  header('Content-Type: '.$mime);
  header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
  header('Content-Transfer-Encoding: binary');
  header('Content-Length: '.filesize($file_name));  // provide file size
  header('Connection: close');
  readfile($file_name);     // push it out

  header('Location: http://google.com');

But, there are no redirection after download.

How can i solve this situation, thanks for your helps & advices.

Upvotes: -1

Views: 503

Answers (1)

Nuwan Attanayake
Nuwan Attanayake

Reputation: 1201

If you download the file which means you have already received the response(Header already send to the client).

There is no way in PHP to set custom header and then have a redirect.

What you can do is have an Ajax call from client side to download the image and then another Ajax call to redirect page.

Upvotes: 0

Related Questions