This question already has answers here:
How to force file download with PHP
(12 answers)
Closed 6 years ago.
I have files uploaded on server folder and its path is saved in database. sample view of table is:
id name resume
1 N1 resume/abc.doc
2 N2 resume/def.pdf
On a click of a button i wish to download the files (format of file would mostly be docx, pdf) from the server to the system. The code that i have written downloads a file but it is either empty or corrupted. Can anyone please tell how to download files from server
Download
download.php
$candidateid=$_GET['candidateid'];
$filename = "Filename.docx";
header("Content-Disposition: attachment; filename=\"$filename\"");
$flag = false;
$sql = "SELECT resume FROM candidates where id='".$candidateid."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
}
Using the candidateid you can fetch the file name from your table and then store in a variable and then write the code
$file = '/path/to/your/dir/'.$file;
if(!$file){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
Related
Im trying to hide the src url for a pdf file in an iframe / embed. Im not sure how.
I tried with all the previously exiting answers, but none of them are working.
<?php
$url = $_GET['url'];
?>
<embed id="renderedPrint" style="height:calc(100% - 4px);width:calc(100% - 4px);padding:0;margin:0;border:0;"></embed>
<script>
$(document).ready(function() {
var encryptedString = "assets/labels/" + "<?php echo $url; ?>" + ".pdf";
$("#renderedPrint").attr("src", encodeURIComponent(encryptedString));
});
</script>
But no matter which method i use (Obfuscator, php openssl_encrypt/decrypt), the output url is always visible.
I dont want users to find the iframe/embed url. I want to make it difficult to or even hide the url from the front-end.
The purpose is that i dont want users to have direct access to the generated pdf file. They may copy the iframe src url and send it to someone else. We cant stop them from downloading the pdf, but i dont want them to copy the source url from the server.
check this code
you should be add file address to DB
<?php
// get id to search on DB and get detail
$id = $_REQUEST['id'];
try {
$conn = new PDO("pgsql:host=$host;port=5432;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT url FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
// the address of file in server
$path = $row['url'];
$filename = basename($path);
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo 'check that file exists and is readable';;
}
?>
I have a local DB table in which many PDF links are saved around 15000. I want to download all that PDF on one click but my problem is its opening PDF not downloading. I was trying this method.
items = Array.from(document.getElementsByTagName("a"));
items.forEach(function(item) {
link = item.href;
if (link.substr(link.length - 4) == ".pdf") {
filename = link.replace(/^.*[\\\/]/, '');
item.download = filename;
item.click();
}
});
You can not download all files using only 1 click. Instead of You can use ZIP Archive Class in PHP.
Make one zip file of all available pdf and download it.
$files = array('pdf1.pdf','pdf2.pdf');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
And Headers Like
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
Thanks for your reply,
this code works for me with zip archive
$files = array('pdflink','pdflink');
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach($files as $file){
$download_file = file_get_contents($file);
$zip->addFromString(basename($file),$download_file);
}
$zip->close();
header('Content-disposition: attachment; filename=file.zip');
header('Content-type: application/zip');
readfile($tmp_file);
?>
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "https://vibrantgujarat.com/pressclippingsnew.htm"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
I Have a page which has more than 500 press clippings information along with date, name, media name and image path.
I want to download all of them using script but I Don't know how to write download script.
Here is link
Any help would be great.
Thank You.
Checkout the following function, which is not working fully, you need to try out some changes to it.
function saveImageAs(){
var images = document.getElementsByTagName("img");
for(var i=0;i<images.length; i++){
var imgOrURL= images[i].src;
window.win = open(imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 0);
}
}
<?php
set_time_limit(0);
//File to save the contents to
$fp = fopen ('download.zip', 'w+');
$url = "https://vibrantgujarat.com/pressclippingsnew.htm";
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);//get curl response
//done
curl_close($ch);
This will help you to download images and contents for the 1st page.
Hope this helps.
I need to store different types of documents inside the project folder in single button click using Angular.js and PHP. I am explaining my code below.
var fileData={'image':file,'regdoc':regDocs,'compRegDoc':compRegDocs};
$scope.upload=Upload.upload({
url: 'php/uploadAll.php',
method:'POST',
file: fileData
}).success(function(data, status, headers, config) {
console.log('file',data);
}).error(function(data, status) {
console.log('err file',data);
})
uploadALL.php:
<?php
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
header("HTTP/1.0 401 Unauthorized");
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
header("HTTP/1.0 401 Unauthorized");
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
//$today=('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
move_uploaded_file($file_tmp,"../upload/".$file_name);
echo " uploaded file: " . "upload/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
header("HTTP/1.0 401 Unauthorized");
$errors[]="No image found";
print_r($errors);
}
?>
Here I have one image and the other two are .pdf/docx type files. When the user clicks the submit button these 3 files should be stored inside upload folder.
// use this code in php page...
it's used to upload all file
if(isset($_POST['submit'])!=""){
$name=$_FILES['file']['name'];
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$temp=$_FILES['file']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"upload/".$name);
}
How to make live preview a PDF file in my local website ( no internet ) which is the PDF saved in Longblob? I use this script to download the PDF :
<?php
if(isset($_GET['id']))
{
include "../conn.php";
$query = "select * from file where id = '".$_GET['id']."'";
$result = mysql_query($query) or die (mysql_error);
$download = mysql_fetch_array($result);
$name = str_replace('%20', ' ',$download['file_name']);
$type = $download['file_type'];
$size = $download['file_size'];
$content = $download['file'];
header("Content-disposition: attachment; filename=\"".$name."\"");
header("Content-length: ".$size."");
header("Content-type: $type");
echo $content;
exit;
}
?>
I have use almost all open source PDF Viewer plugins like from http://viewerjs.org , but failed to display the wanted PDF file. Need your help guys..
you shoud have a pdf plugin and you should use code looks like :
header('Content-type: application/pdf');
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Disposition: inline;filename='document.pdf'");
header("Content-length: ".strlen($binary_contents_from_database));