简体   繁体   中英

Generating a download link for an uploaded file using PHP

Using PHP, I have created a form which uploads and sends files via email. Now, the upload works perfectly and automatically sends an email to a specified email address. I'd like to include, if it's possible a download link for the file inside the email. I am able to send a link already but whenever I click on the link, all it does it open the file on the browser. I'd like it download when the link is clicked instead. The thing is, I am not connecting or saving the uploaded file to my database. I'm just uploading it on my server and sending it directly to the receiver. Is it possible to achieve what I'd like to do? If it is, how can I achieve this? Or do I need to create a database for it?

You need to write file download code on that page where your link is pointing. From link extract the file name and write the following code

 if (file_exists($file))
 {
    if (FALSE!== ($handler = fopen($file, 'r')))
   {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: chunked'); //changed to chunked
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    //header('Content-Length: ' . filesize($file)); //Remove

    //Send the content in chunks
    while(false !== ($chunk = fread($handler,4096)))
    {
        echo $chunk;
    }
}
exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM