简体   繁体   中英

How to insert into database after you click on <a> href link?

I have a link for download <a href="http://website/filename.pdf">Download</a> and I would like that everytime when someone clicks on Download I could insert into database total_downloads+1. For inserting into database I normally use

<form method="POST">
<input type="submit" name="download" value="Download">
</form>

and then

if (isset($_POST['download'])) {...}

But I don't know how to trigger download after click on download button in form.

The quick and easy way is:

header('Location: http://website/filename.pdf');

To have little more control over the parameters you can use this code:

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="somename.pdf');
header('Content-Length: '.filesize($filepath) );
readfile($filepath);

Regarding the answer of kgm (which is absolutely correct), you should make sure that the files to download are fairly small, because readfile() reads all the file contents into memory, which could lead to exhausted memory. To avoid this, have a look at "readfile_chunked" in the user contributions on this site: http://php.net/manual/de/function.readfile.php

cheers :)

To make submit button work like a html link add onclick attribute to submit button

<input type="submit" onClick="parent.location='http://website/filename.pdf'" 
 name="download" value="Download">
<a href="http://website/filename.pdf" onclick='$.post("name_of_page.php", {download: "Download"});'>Download</a>

我不确定报价。

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