Generate Download File Link in PHP

Generate download file link in PHP

$filename = 'Test.pdf'; // of course find the exact filename....        
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;

Name the above file as download.php

HTML:

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

That should do it.

How to create a download link for a file using PHP?

Find the solution here: http://www.ssdtutorials.com/tutorials/title/download-file-with-php.html

As the file which I want to download is dynamic associated with each job seeker's data. I used while loop for retrieving the file name from database.

    $result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$filename = $row[0];
echo "<p><a href='download.php?file=$filename'> Download Resume </a></p>";
}

How to force a file to download in PHP

If you want to force a download, you can use something like the following:

<?php
// Fetch the file info.
$filePath = '/path/to/file/on/disk.jpg';

if(file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);

// Output headers.
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);

// Output file.
readfile ($filePath);
exit();
}
else {
die('The provided file path is not valid.');
}
?>

If you simply link to this script using a normal link the file will be downloaded.

Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.

create, write and download a txt file using php

The correct way to do it would be:

<?php

$file = "test.txt";
$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt, "lorem ipsum");
fclose($txt);

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);

?>

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 link/request to download file then delete it immediately

There are a few components to getting this to work. Without knowing which framework you use, I'll use comments as placeholders.

There is no way to do it without using the header function, though.

Here is the source for a file that outlines the process:

<?php
$fileid = $_GET['fileid'];
$key = $_GET['key'];

// find the file in the database, and store it in $file
if ($keyMatches) {
// it is important for security to only use file paths from the database
$actualPath = $file->getPathOnDisk();

$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($fileInfo, $actualPath);

$fp = fopen($actualPath, 'rb');
header("Content-Type: " . $mime);
header("Content-Length: " . filesize($actualPath));
fpassthru($fp);
}
else
{
http_response_code(403); // forbidden
}

You'll use this by linking to download.php?fileid=1234&key=foobar, and generating the URL at the same time you generate the key and store it in the database.

For security, you'll keep the files outside of the web root, meaning they cannot be accessed through the web server without going through a script.

fpassthru is reasonably fast, and will not likely have a performance impact.



Related Topics



Leave a reply



Submit