-3

I use php for download different types of file. My download file code is

  <?php
if(isset($_GET['path']))
{
//Read the url
$url = $_GET['path'];
echo $url;

//Clear the cache
clearstatcache();

//Check the file path exists or not
if(file_exists($url)) {

//Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($url).'"');
header('Content-Length: ' . filesize($url));
header('Pragma: public');

//Clear system output buffer
flush();

//Read the size of the file
readfile($url,true);

//Terminate from the script
die();
}
else{
echo "File path does not exist.";
}
}
echo "File path is not defined."

?>

and i use okhttp3 for download pdf file from server. My code is

  OkHttpClient client = new OkHttpClient();
  String url = "http://www.hitlarweb.com/hitlar/download.php?path=fighter.pdf";
  Call call = client.newCall(new Request.Builder().url(url).get().build());

  try {
       Response response = call.execute();
       if (response.code() == 200 || response.code() == 201) {
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
              Log.d(LOG_TAG, responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }
            String str = response.body().string();  
        }  
      }catch(){}

It returns header

"Server" = "nginx"
"Date" = "Thu, 13 Oct 2022 11:00:59 GMT"
"Content-Type" = "text/html"
"Transfer-Encoding" = "chunked"
"Connection" = "keep-alive"
"Vary" = "Accept-Encoding"
"Expires" = "Thu, 01 Jan 1970 00:00:01 GMT"
"Cache-Control" = "no-cache" 

and body return

<html><body><script>document.cookie="_test=3615ff5e48bd398a38d2ce932bef0629 ; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/" ;document.location.href="http://www.webweb.infinityfreeapp.com/lichi/download.php?path=fighter.pdf&i=1";</script></body></html>

My question is why php file does not return pdf file data in body and application/pdf in Content-Type. whats problem occur please guide to solve this

  • 1
    Because you do `echo $url;` before setting headers, so headers can not be set anymore. Turn on error reporting and will see error. – Justinas Oct 13 '22 at 11:16

1 Answers1

0

The header command lines should be enough to allow the download.

This code should work and suffice normally

<?
// Type MIME
$type   = "application/pdf";

// Force download
header("Content-disposition: attachment; filename=$visibleName"); 
header("Content-Type: application/force-download"); 
header("Content-Transfer-Encoding: $type\n");
header("Content-Length: ".filesize($completePath)); 
header("Pragma: no-cache"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public"); 
header("Expires: 0"); 
readfile($completePath); 
?>
Juan
  • 690
  • 4
  • 15