How to Download a File on Clicking the Name of File Using PHP

How to download a file on clicking the name of file using PHP?

so, How to download a file on clicking the name of file using PHP?

The easiest way should be linking to it.

<a href="download.php?......" target="_blank">DMS.doc</a>

PHP: How to make browser to download file on click

In a paged called download.php, have the following code:

<?php

$filename = 'file.pdf';//this should be the name of the file you want to download
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain 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 then have a link to the download page like this:

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

Let me know if that works for you.


Edited:

My previous example was for the download of a pdf file. In the case that you want to download a different type of file, a few lines have to be slightly modified. I recommend you first try downloading a pdf file with the previous code, and after having accomplished that testing out on other files.

To retrieve the path from the database, you can use MySQL (PDO).

$sqlStatement = "SELECT path FROM my_table WHERE some_id = ".$something;
/*if you are retrieving the path from the database,
you probably have a lot of different paths available
there, so only you know the criteria which will decide
which of the many paths it is that you choose to extract*/

$sqlPrepared = $connection->prepare($sqlStatement);
$sqlPrepared->execute();

$row_info = fetch($sqlPrepared);

$filename = $row_info['path'];// this would be the $filename = 'file.pdf'
//that was in the example above

If you are not sure how to connect to the database, there are a lot of articles online explaining MySQL that is relatively straightforward.

I hope that helped :)

Downloading a file with a different name to the stored name

Sure, use a Content-disposition header

header('Content-Disposition: attachment; filename="filetodownload.jpg"');

if you wish to provide a default filename, but not automatic download, this seems to work.

header('Content-Disposition: filename="filetodownload.jpg"');

With PHP how to force download of file with randon file name and type

First and foremost create a download handler file which will be accepting parameters.

I'll call it download.php

download.php

<?php
ignore_user_abort(true); // prevents script termination
set_time_limit(0); // prevent time out

$file = isset($_GET['file']) ? $_GET['file'] : ''; //get filename

if ($file) {
$path_info = pathinfo($_GET['file']);
$file_name = $path_info['basename'];
$dir = "uploads"; //directory

$path_to_file = $dir.'/'.$file_name; //full path

if(!file_exists($path_to_file)) { // check if file exist or terminate request

exit('the file does not exist');
}

if(!is_readable($path_to_file)) { //check if file is readable from the directory

exit("security issues. can't read file from folder");

}

// set download headers for file

$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: ' . finfo_file($finfo, $path_to_file));

$finfo = finfo_open(FILEINFO_MIME_ENCODING);
header('Content-Transfer-Encoding: ' . finfo_file($finfo, $path_to_file));

header('Content-disposition: attachment; filename="' . basename($path_to_file) . '"');

readfile($path_to_file); // force download file with readfile()
}

else {

exit('download paramater missing');
}
?>

Usage

<a href="download.php?file=randomfilename.pdf">My pdf </a>

Hope this helps.

Download a file by clicking a button

Don't use AJAX to download a file. It's not that it can't make the request and receive the response, it's just that it doesn't really have any meaningful way to handle the response.

The browser itself, on the other hand, does.

So you can just direct the browser to the request:

$parent.find('button[name=download]').click(function () {
window.location.href = 'download.php';
});

If download.php is sending a response of Content-Disposition: attachment; then the page isn't going to be unloaded or modified in any way. The browser is going to handle the response of this request entirely separately from the current page context, and after handling the response that page context will remain.

(Unless, of course, the browser is configured to do something with that response, such as always display it instead of prompting to save it. But there's nothing you can do about that in code.)

At this point, in fact, it makes even more sense to just remove the JavaScript entirely and make it a normal link, which would accomplish the same thing:

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

You can style it to look like a button, which it probably more accessible than an actual button running JavaScript code. (If the browser doesn't have JavaScript enabled then the button would be useless, but a link would work just fine.)

How can I generate and download a file with one user action in PHP?

The script you have posted, which is a derivative of the one in the manual (I have found the manual version to be a very reliable download example), should fall above any of your page html (or other browser output), so an example would be:

<?php
# I would still put session at the top
session_start();

# To create the file, use
# Make this anywhere above any possible browser output
if(!empty($_POST['action']) && $_POST['action'] == 'export_meals') {
# I would make the file noted on the php side, not sent by the form
$file = "docs/meals.csv";
# This would be the data to save to file
$data = getDataFromSomePlace();
# This will save the file to disk–not sure where you get the data...
file_put_contents($file, $data);
# Check if the file is really there and can be read
if(!is_file($file) || !is_readable($file))
die('File does not exists. Check path again.');
# Do the default from-the-manual download script
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
# Now you can start all your other scripts and html
?><!doctype html>
<html>
...etc
<body>

<form action="season.php" method="POST" id="export_meals_form">
<!-- I would just make this an "action" name, not the actual file path -->
<input type="hidden" name="action" value="export_meals" />
<input type="submit" value="Generate Export File" />
</form>

</body>
</html>

NOTE: I have modified your form a bit as well as the download script, but if you do it like this, it should work. In fact, I would create a new blank page, with no styles or other fluff and see if you can get it to work with just these basics. This script is tested and does work, so if it fails, you have implemented it incorrectly or your server is misconfigured in some way.

php- How to record which user clicked on a link to download a file

If you want it to be purely PHP, as suggested, just use the task_id of the row in your file table. Here is a basic example, noting I have reorganized some elements to help keep your script cleaner. Ideally you will want to keep the functions on a different page and include them when you want to use them. Keeps your script cleaner and more easily readable.:

# Better to make a function/class to do your database so you can reuse it easily.
function getConnection( $servername = "localhost", $username = "root",$password = "",$dbname = "project_website1")
{
# Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
# Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

return $conn;
}

# Make a task retrieval function/class that will deal with getting the rows only
function getTasks($con,$id=false)
{
$sql = "SELECT task_id,file, description, title, deadline_claim FROM task";
# I am assuming your task_id values are numeric, so I don't sanitize here
if ($id) {
if(is_numeric($id))
# Append sql
$sql .= " WHERE `task_id` = '{$id}'";
else
# You shouldn't get this exception unless someone is trying to
# Manually put something else here via injection attempt
throw new Exception("Id must be numeric!");
}

$result = $con->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$new[] = $row;
}
}
# Send back rows
return (!empty($new))? $new : array();
}

# This is more of a listener, but it will cut down on some redundant check-script
function getFileId()
{
if(!empty($_GET['file']) && is_numeric($_GET['file']))
return (!empty($_GET['action']) && $_GET['action'] == 'download')? $_GET['file'] : false;

return false;
}

# As noted, you would include the functions here...
session_start();
# Get session id
$user_id = $_SESSION[ 'user_id' ];
# Get the database connection
$conn = getConnection();
# If there is a download
if(!empty($_GET['action']) && $_GET['action'] == 'download') {
# Get the tasks, could be based on id or all
$tasks = getTasks($conn, getFileId());
# Save to the database, make sure that you either bind parameters, or
# check that the values are numeric (if they are supposed to be numeric)
# Also check the count here first for the task before inserting. Make an error if not.
# Usually means user is trying to manipulate the request
$conn->query("INSERT into downloads (`fileid`,`userid`) VALUES('".$tasks[0]['task_id']."','".$user_id."')");
# Download file. If you want to obfuscate the file, you would use
# download headers instead:
# http://php.net/manual/en/function.readfile.php
header('Location: '.$tasks[0]['file']);
# Stop execution
exit;
}

# Get all tasks
$tasks = getTasks($conn);
# If there are rows, output them
if (!empty($tasks)) {
echo "<table><tr><th>TITLE</th><th>DESCRIPTION</th><th>DEADLINE</th><th>TASK</th></tr>";
# output data of each row
foreach($tasks as $row) {
echo "<tr><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["deadline_claim"]."<td><a href='?action=download&file=" .$row["task_id"]. "'>CLAIM</td></a>";
}
echo "</table>";
} else {
echo "0 results";
}

$conn->close();

Final note, I have not tested this, so be aware of that.

PHP: Download a file on button click?

Try this

header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));

I think file_get_contents() function is no longer work with PHP 5.0.3

Change file name for download and start downloading it after click or delay

You will need two parts to do this effectively... In your displayed PHP file (let's call it download.php), you'll need to kick off a Javascript function that counts down for your customer to zero. When it reaches zero, it simply redirects to the real download location (let's call it realdl.php). This file would actually grab the file content and send it to the user when either redirected or clicked.

Here are some elements you would need in download.php:

<? $file_dl_url = "/realdl.php?id=FILEID"; ?>

<script language="javascript">
var elapsed = 0;
function countdown {
// see if 5 seconds have passed
if (elapsed >= 5) {
window.location = <?= $file_dl_url ?>;
} else {
// update countdown display & wait another second
elapsed++;
setTimeout("countdown", 1000);
}
}
setTimeout("countdown", 1000);
</script>

<a href="<?= $file_dl_url ?>">Click Here</a>

Then, all you would need in realdl.php is the following:

$file_contents = load_file_from_id($_GET['id']);
$file_name = determine_filename();

header("Content-Disposition: attachment; filename=$file_name");

echo $file_contents;

Of course, you need to provide the methods to get the file contents (either just read from disk or possibly database) as well as to determine the file name. To use time as a filename format, see http://us3.php.net/manual/en/function.strftime.php for the strftime function.

Depending on how the file is stored, you can be more effective, using fpassthru for local files, as an example. You also may want to send the Content-Length header if you can determine the file size prior to downloading (i.e. it is static content you are sending).



Related Topics



Leave a reply



Submit