php downloading files – How to Force Download Files Using PHP?

php downloading files : Using header() and readfile() function, you can easily download a file in PHP. This PHP download file script makes it possible to download files without a direct link.

php downloading files

You can force images, text, pdf, csv or other kind of files (PHP content in different formats(content-type like HTML,XHTML,images,pdf,flash,video etc)) to fource download directly to the member’s hard drive using the PHP readfile() function.

this source code provides files to the user by forcing them to download. A beginners PHP tutorial with examples and a demo.

PHP File Download

Downloading Files with PHP

<a href="media/version.zip">Download version Zip file</a>
<a href="media/angularjs.pdf">Download angularjs PDF file</a>
<a href="media/laravel.jpg">Download laravel Image file</a>
<a href="media/kamaniya.exe">Download kamaniya EXE file</a>

Don’t Miss : PHP force download file from URL

Read Also:  Laravel Delete Record using jquery Ajax Request

Forcing a Download Using PHP

product-list.php



<style type="text/css">
    .img-box{<br />
        display: inline-block;<br />
        text-align: center;<br />
        margin: 0 15px;<br />
    }<br />
</style>


<!--?php <br ?--> $profiles = array("pakainfo.jpg", "infinityknow.jpg");

foreach($profiles as $profile){
echo '
<div class="img-box">';
echo '<img src="profiles/' . $profile . '" alt="' . pathinfo($profile, PATHINFO_FILENAME) .'" width="200" />';
echo '<a href="download.php?file=' . urlencode($profile) . '">Download</a>

';
echo '

</div>
';
}
?>


download.php

<!--?php if(isset($_REQUEST["file"])){ $new_fl = urldecode($_REQUEST["file"]); if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $new_fl)){ $base_fl_source = "profiles/" . $new_fl; if(file_exists($base_fl_source)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($base_fl_source).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($base_fl_source)); flush(); readfile($base_fl_source); die(); } else { http_response_code(404); die(); } } else { die("Invalid file name!"); } } ?-->

I hope you get an idea about php downloading files.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.