mysql - PHP: How to make browser to download file on click -


php beginner. file uploading successful browser doesn't download files, instead reads file. referred other threads , found below code not working. want download files when click on hyperlink download. selected path mysql database.

$rows = mysqli_num_rows($result);                  if($rows>0)                 {                      while($row = mysqli_fetch_assoc($result))                     {                            ?>                         <div> <?php echo $row['object_name'];?>                          <a href="<?php                          $file_url = $row['object_path'];                         header('content-type: application/octet-stream');                         header("content-disposition: attachment; filename=\"".$row['object_name']. "\"");                          readfile($file_url);                         ?>">download</a><br>                         </div>                           <?php                     }                  } 

in paged called download.php, have following code:

<?php  $filename = 'file.pdf';//this should name of file want download  header('pragma: public'); header('expires: 0'); header('cache-control: must-revalidate, post-check=0, pre-check=0'); header('cache-control: private', false); // required browsers  header('content-type: application/pdf');  header('content-disposition: attachment; filename="'. basename($filename) . '";'); header('content-transfer-encoding: binary'); header('content-length: ' . filesize($filename));  readfile($filename);  exit; ?> 

your main page should have link download page this:

<a href="download.php">download</a> 

let me know if works you.


edited:

my previous example download of pdf file. in case want download different type of file, few lines have modified. recommend first try downloading pdf file previous code, , after having accomplished testing out on other files.

to retrieve path database, can use mysql (pdo).

$sqlstatement = "select path my_table some_id = ".$something; /*if retrieving path database,  have lot of different paths available  there, know criteria decide of many paths choose extract*/  $sqlprepared = $connection->prepare($sqlstatement); $sqlprepared->execute();  $row_info = fetch($sqlprepared);  $filename = $row_info['path'];// $filename = 'file.pdf'  //that in example above 

if not sure how connect database, there lot of articles online explaining mysql relatively straightforward.

i hope helped :)


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -