Uploaded file is unable to read after downloading in PHP - php

I wrote php script to upload file from admin panel and to download for user.
Uploading was done successfully but after downloading the file, it is unable to read. if it is a image file or pdf file. The uploaded files are copied to xamp/htdocs/myproject/admin/documents. and the path is stored to mysql database. When i tried to download it the file size is different for uploaded file and downloaded file and it is unable to read.
The uploading script
if (isset($_POST['submit'])){
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name) {
$location = "documents/$name";
move_uploaded_file($tmp_name, $location);
$query = mysqli_query($con,"INSERT INTO posts (name,path) VALUES ('$location')");
}

Thanks everybody for helping me. i made changes for my script yesterday and it is working but the problem is that when i tried to add it to my project it is not working.
my uploads script(it is writen in myproject/admin/application.php)
if (isset($_POST['submit'])){
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name) {
$location = "documents/$name";
move_uploaded_file($tmp_name, $location);
$query = mysqli_query($con,"INSERT INTO posts (name,path) VALUES ('$location')");
}
download.php (Written in myproject/download.php)
<?php
include('includes/connect.php');
if (isset($_GET['dow'])) {
$path = $_GET['dow'];
$res = mysqli_query("SELECT * FROM posts WHERE path = '$path'");
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . basename($path) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
flush();
readfile($path); //showing the path to the server where the file is to be download
exit;
}
?>
The linking script to download.php b (written in myproject/viewprofile.php)
<?php
include('includes/connect.php');
$sql = "SELECT * FROM posts";
$res = mysqli_query($con, $sql);
$path = $row['post_path'];
echo "<a href='download.php?dow=$path' class='btn btn-dark btn-theme-colored btn-flat mr-5' style='width:100%; margin-top:5px;'> DOWNLOAD RESUME </a> <br>";
?>

Related

Download a zip file of blobs (from database) as images to my local storage using PHP

I have a form from which, we get the data from users. Images are stored as blob in database. Now, I want all of the responded images to my local storage (computer).
<?php
include 'config.php';
session_start();
$table_name = $_SESSION["table"];
$zip = new ZipArchive();
$ZipFileName = $table_name . '.zip';
if ($zip->open($ZipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) {
echo "Cannot Open";
}
$zip->addEmptyDir('newFolder');
$query = mysqli_query($con, "SELECT * FROM $table_name");
while($row = mysqli_fetch_assoc($query)) {
$temp = $row['student_id'] . '.jpg';
$zip->addFromString($temp, $row['photo']);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . $ZipFileName);
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-length: " . filesize($ZipFileName));
?>
Zip file is downloaded, but at the time of extraction it shows error. When I tried to download only one image it shows no preview.
How can I download all the blob files as images to my computer (a zip file)?

Creating zipped file of many pdfs automatically

I am trying to zip a series of pdf files automatically when a page loads. The files are based on a query. I can't seem to figure out the error. All of the pdfs are kept in the agreements folder and I want the zip file to just download on the viewer's computer. The error code that I get is:
agreements/Acadience_Cambridge_Post_1.pdfagreements/DoTheMath_Cambridge.pdfagreements/Edulog_Cambridge.pdfagreements/DESSA_Cambridge.pdfagreements/FuelEducation_Cambridge_signed.pdfagreements/LegendsofLearning_Dedham.pdfagreements/workforce19-22.pdfagreements/Ellevation_Dedham_Posting.pdfagreements/Yabla_Cambridge.pdfagreements/Breakthrough-2020.pdfagreements/Cedar-Labs-DPA.pdfagreements/Tutoring Plus.pdfagreements/Elefante Letrado_Brockton - post.pdfagreements/CollegeBoard_Cambridge_post_1.pdfagreements/LanguageConnections_post.pdfagreements/Flat_Westford - post.pdfagreements/Albert.io_Cambridge_post.pdfagreements/Starfall_Walpole.pdfagreements/Tynker_Milton - post_1.pdfagreements/WeVideo_CambridgeTEC_1.pdfagreements/Checkology_Dedham.pdfagreements/BabylonHouse _Cambridge_signed_4.pdfagreements/FreeMath_Westwood_Post.pdf
Warning: ZipArchive::close(): Failure to create temporary file: Permission denied in /var/www/html/extract_dpas2.php on line 36
Could not find Zip file to download
Here is the code I have:
<?php require_once('Connections/sdpc_i.php'); ?>
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
$sql = "SELECT * FROM data WHERE districtID = 457 and statusID=1 and signed_agreement_file != 'NULL'";
if ($result=mysqli_query($sdpc_i,$sql))
{
// $rowcount=mysqli_num_rows($result);
// printf("Result set has %d rows.\n",$rowcount);
//define array for storing files
$file = array();
while ($row = mysqli_fetch_assoc($result)) {
//give file name with extension
$name ="agreements/".$row['signed_agreement_file'];
//store file name in array
$file[] = $name;
// store file in one folder named 'files'
file_put_contents($name,$row["signed_agreement_file"]);
}
$zipname = "file.zip";
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($file as $f) {
echo $path = "".$f;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
//check zip file create or not and download it
if (file_exists($zipname)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($zipname).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname);
exit;
} else {
exit("Could not find Zip file to download");
}
mysqli_free_result($result);
mysqli_close($conn);
}
?>
Thank you in advance for you help.

How can I add a download button?

I have this code which outputs a QR code:
<?php
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('Soci', 'Nom', 'Cognoms', 'eCorreu')))
->from($db->quoteName('#__rsform_socis'))
->where($db->quoteName('username') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$codeContents = $db->loadObjectList();
$data .= "Soci NÂș: {$codeContents[0]->Soci}\n ";
$data .= "Nom: {$codeContents[0]->Nom} ";
$data .= "{$codeContents[0]->Cognoms}\n";
$data .= "e-correu: {$codeContents[0]->eCorreu}";
$tempDir = JPATH_SITE . '/images/';
$fileName = 'qr_'.md5($data).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = JUri::root() .'images/' . $fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($data, $pngAbsoluteFilePath);
}
echo '<img src="'.$urlRelativeFilePath.'" />';
?>
How can I add a download button so the user can download the code to the computer?
Thanks,
Dani
This is more of a HTML question, so lets get started: There is an attribute called "download" and you can use it like this:
echo 'Download QR';
It downloads the file as the name you supply here. So if the image url on your server is: wadAHEybwdYRfaedBFD22324Dsefmsf.png it would download the file as "qrcode.png". Unfortunately this is not supported in all browsers. Another easy fix is to make a form that has your filename as an action like so:
echo '<form method="get" action="'.$urlRelativeFilePath.'"><button type="submit">Download QR Code!</button></form>';
Another way (little more code) to do this is using PHP with some specific headers like this:
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_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"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
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;
// example: place this kind of link into the document where the file download is offered:
// Download here
?>
It works for large and small files and also for many different filetypes. Info found here: http://www.finalwebsites.com/forums/topic/php-file-download
Well, you are obviously creating a .png picture file of the QR code with your script. So simply add a link to the location of the picture:
echo "Download";
This will however just redirect the user to the picture in his browser.
If you want to force a download you will need to use PHP headers to send the file to the visitors browser.
For example make a script and call it download_code.php.
Then add:
echo "Download";
And in the download_code.php:
$handle = fopen("/var/www/yourdomain.com/images/" . $filename, "r");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Length: ' . filesize("/var/www/yourdomain.com/images" . $filename));
flush();
readfile("/var/www/yourdomain.com/images" . $filename);
fclose($handle);

File download from server using mysql and PHP

I have created a PHP page that allows users to download a file when they click the this link:
Download File
I have also created the download page that the link directs to:
<?php
if(isset($_GET['file'])) {
$fileID = $_GET['pubid'];
$filename= ($_GET['file']);
$path = "admin/pubfiles/";
$fullPath = $path . $filename;
mysql_select_db($database_connDioceseofife, $connDioceseofife);
$sql = "SELECT file FROM publications WHERE pubID = $fileID";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if($filename == NULL) {
die('No file exists or the name is invalid!');
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($fullPath);
}
?>
Now my problem is, when the download popup window come up, it reads that the file is of 0 bytes. And when downloaded, it can't open. i get the message that it is not a supported file type or its been damaged or corrupted.
Please any help would be much appreciated.
You're not doing anything with the query result in $row.
Use $row['file'] to get the actual file itself.
Thank you all for assisting me. I have been able to solve the problem after further reading. I have updated the initial script i wrote. what is above is now the working script.
What i did was to include $fullpath = $path . $filename then changed the header("Content-Disposition: attachment; filename=\"$filename\""); and then the readfile function from readfile($path) to readfile($fullpath).
Thanks again #nlsbshtr and everybody else for your help.

Rename file before downloading PHP

I'm currently making a file hosting website. I'm having a problem with renaming the file before the user downloads the file. When the file is uploaded the original name is saved in the mysql database and the file is renamed to a id.
<?php
require("includes/inc.php");
$id = trim(sanitize($_GET['id'])); //Receives the id of the file from the url
if($id) {
$fileid = mysql_query("SELECT * FROM files WHERE id = '$id'");
if (mysql_num_rows($fileid) != 1) {
header('Location: download.php?error=invalid_file');
exit();
} else {
while($info = mysql_fetch_array($fileid)) {
$fileid2 = $info['id'];
$filename = $info['name'];
$ext = $info['ext'];
$filesize = $info['size'];
$downloads = $info['downloads'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Location: uploads/".$fileid2.".".$ext);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Length: ' . $filesize);
}
?>
I would think your "while" loop and output would be something like this: (I also switched the $filename and $fileid2 in the headers)
while($info = mysql_fetch_array($fileid)) {
$fileid2 = $info['id'];
$filename = $info['name'];
$ext = $info['ext'];
$filesize = $info['size'];
$downloads = $info['downloads'];
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$fileid2.'.'.$ext.'"');
header('Content-Length: ' . $filesize);
readfile(uploads/".$filename.".".$ext);
I did not test this, so I hope it helps.

Categories