Rename file before downloading PHP - 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.

Related

Download multiple .txt files into .zip file with PHP

Now in system it is possible to download .txt file generated from MySQL table row. I am trying to make it possible to download all .txt files in one zip file. Actually, I stuck on the point where I am not sure if my approach is possible.
if (isset($_POST["ExportAll"])) {
$query = $con->query("SELECT id, filename FROM thistable");
$MultiArray = Array();
while($result = $query->fetch_assoc()){
$rowArray = Array();
$rowArray[] = $result['id'];
$rowArray[] = $result['filename'];
$MultiArray[] = $rowArray;
}
foreach ($MultiArray as $arg) {
$query = "SELECT * FROM thistable WHERE id LIKE '" . $arg[0] . "';";
$result = mysqli_query($con, $query);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $arg[1] );
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$output = fopen("php://output", "w");
while ($row = mysqli_fetch_assoc($result)) {
foreach(array_slice($row,2) as $line) {
echo ("$line \r\n");
}
}
fclose($output);
}
}
It is possible to put all $output values into some kind of $zipArray = Array() and then download it with header("Content-type: application/zip");
?
Yes you can download multiple text files as single zip file using php ZipArchive class. This is sample only you can try with your own scenario.
$zipname = 'sample.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$files_array = ["sample1", "sample2"]; // List of file names
foreach ($files_array as $file) {
$row = ["Line 1", "Line 2", "Line 3", "Line 5"]; // Assuming as your table row
$filename = $file.".txt";
$lines_to_add = "";
foreach(array_slice($row, 2) as $line) {
$lines_to_add .= $line."\r\n";
}
$zip->addFromString($filename, $lines_to_add); // Adding lines to file
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
unlink($zipname); // Remove zip file if you don't want be in server

PHP: Force download is downloading an empty file

The code below displays this:
/home/my_site/www/wp-content/uploads/2017/03/2017-03-17-my_file.mp3
As far as I can tell, this path is correct. Yet when I comment away the echo and download the file, it's an empty file. Why?
Code:
if (isset($_GET['file'])) {
clearstatcache();
$file_path = str_replace('http://www.example.com/', '', $_GET['file']);
$file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path . '.mp3';
echo $file_path;
if(file_exists($file_path)) {
$file_name = basename($file_path);
$file_size = filesize($file_path);
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$file_size);
header("Content-Disposition: attachment; filename=".$file_name);
exit();
}
else {
die('The provided file path is not valid.');
}
}
EDIT: this is what I have after KIKO Software's suggestion. Still downloads empty file.
<?php
if (isset($_GET['file'])) {
$file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['file'] . '.mp3';
//echo $file_path;
//$file_path = $_SERVER['SCRIPT_FILENAME'];
if (file_exists($file_path)) {
$file_name = basename($file_path);
$file_size = filesize($file_path);
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$file_size);
header('Content-Disposition: attachment; filename='.$file_name);
//readfile($file_path);
exit();
}
else {
die('The provided file path is not valid.');
}
}
?>
Simple example to download a file:
$content = 'This is the content.';
$size = strlen($content);
$name = 'test.txt';
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$name);
echo $content;
Make sure this works first. If it doesn't there could be a problem with the headers. Switch on error reporting and see: How to fix "Headers already sent" error in PHP
Then build up on that. Start by downloading the script itself:
$file_path = $_SERVER['SCRIPT_FILENAME'];
if (file_exists($file_path)) {
$file_name = basename($file_path);
$file_size = filesize($file_path);
header('Content-type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$file_size);
header('Content-Disposition: attachment; filename='.$file_name);
readfile($file_path);
exit();
}
else {
die('The provided file path is not valid.');
}
And only after that try to download something else.
By approaching the problem step by step it is easier to see where it goes wrong.

Uploaded file is unable to read after downloading in 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>";
?>

unknown file name change when file downloads

am using a script to download files from my site.
if (isset($_GET['file'])){
$file = $_GET['file'];
$query = "SELECT fileurl FROM dbname WHERE id='$file'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$filename = $row[fileurl];
send_download($filename);
}
function send_download($filename){
$file_path = $filename;
$file_size=#filesize($file_path);
header("Content-Type: application/x-zip-compressed");
header("Content-disposition: attachment; filename=$filename");
header("Content-Length: $file_size");
readfile($file_path);
exit;
}
It works great but the only caveat is that the file name is changed to some encryted string ie asdajkhasdkahdkasdakfsdhf.pdf how do I change this so that it downloads with the original name??? And if possible, append + to the spaces inbetween the file name ie My+File.pdf

How to upload and download files to/from mysql on PHP storing only path?

I am uploading file by storing its path in mysql in that way:
if(isset($_FILES['filefield']))
{
$file = $_FILES['filefield'];
$file_name = $file['name'];
$file_size = $file['size'];
$file_type = $file['type'];
$file_tmpname = $file['tmp_name'];
$upload_dir = "C:/xampp/htdocs/intranet/www/public/uploads/";
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$max_file_size = 10485760;
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions))
echo "only".$ext_str." files allowed to upload";
if($file['size']>=$max_file_size)
echo "only the file less than ".$max_file_size."mb allowed to upload";
$path = $upload_dir.$file_name;
if(move_uploaded_file($file_tmpname, $upload_dir.$file_name))
ORM::factory('files')->uploadFile($teacher_id, $file_name, $file_size, $file_type, $path);
else
echo "The file cant moved to target directory.";
}
How can I then download this file by its path? If my upload code is correct, of course.
Try this
$file = 'C:/xampp/htdocs/intranet/www/public/uploads/'.$file_name;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

Categories