Codeigniter rename downloaded file? - php

Let's say the user upload a zip file called codeigniter.zip. And my application saved it with name 1.zip that is the file's id in database table. Also it saved file's original name to the table. If the user download this file he download it by name 1.zip. How can i give this file to the user with name codeigniter.zip? Thank you.

You could do something like this:
$actual_filename = '1.zip'; // I assume this will come from some model's method
$desired_filename = 'codeigniter.zip' // same is assumed here
header('Content-Disposition: attachment; filename=' . $desired_filename);
echo file_get_contents('/path/to/' . $actual_filename);
Content-Disposition: attachment should make the browser prompt the user to download the file, and filename= tells the browser what to call the file [by default].

Related

How to send Download Link By hiding directory

I wanted to send my user download link when a user buys the product. I send the download link through mail. So when i send the download link i send it through like.. www.xyz.com/images/2343354.jpg
But i don't want let him know the directory structure. Means when a user tries to access the directory aftwards link /images/2343355 he could download others images that i don't want to give to that user.
Is there any way i can avoid by giving the user directory link to download ?
my images are inside the public/images directory as i have made a laravel application.
Provide hash url to the user like www.xyz.com/download?image=XNS2323NIEYEDUJES
You need to store the image name with related hash value in a table.
In the download page get the image request data and retrieve the original image name from db.
And the Make download with PHP download code.
<?php
//get original filename with hash name from fb and store in a variable
if($dboriginalfilename!="")){
$fileName = basename($_GET['file']);
$path = set ur path;
$filePath = $path.$fileName;
if(!empty($fileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;
} else {
echo 'The file does not exist.';
}
}
I think this will work for you. Thank you
Create a JavaScript function like this which will download file and user will not get to know what url is called.
Here is sample solutions which you can try
download
<script>
function downloadfile(filename){
var file_path = 'host/path/'+filename+'.ext';
var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.href = '';//remove path after download
}
</script>
In this code a normal link will be displayed without any href and download file.Then after on click of it you will pass only filename and file will be downloaded then after that if user hover over link no path will be displayed.
Here file name in on-click('filename) will be dynamic each time and directory path is static in your script.
Try this once.

how mySql Data store in unique excel file that should be created dynamically

I have a web page in which user was given certain input methods to fetch data from database. data will be displayed on web page.
I want to store data that user fetched data from my s-q-l database into an excel file.
command i'm using is given below
$excelquery1="SELECT * FROM excel12 INTO OUTFILE 'D:/Downloads/xyz.csv'";
$excelresult1=mysql_query($excelquery1);
it is running ok and data being fetched will be stored in a new file created in Downloads folder with a name xyz.csv
but user have to go manually to that location to check file.
how is it possible that user must be shown downloaded file in the download bar. + I also want to ask that if the xyz.csv is already present in the location when the query execute so in that scenario this query won't get execute saying file already present. so how to tackle this problem ?
how to give unique file name to the file that will be created..
This is the main idea. You need to adequate the code to your need
$file="/path/to/file".date("YmdHis").".csv"; //file location
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);

auto rename of file when its already exist.. PHP CODE

upload.php
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Choose a file: <input name="uploadedfile" type="file" /><br />
Choose a file1: <input name="uploadedfile1" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
^Image of the upload.php^
uploader.php
<?php
mysql_select_db("test");
$target_path = "uploads/" . basename( $_FILES['uploadedfile']['name']);
$target_path1 = "upload1/" . basename( $_FILES['uploadedfile1']['name']);
$currentfile = $_FILES['uploadedfile']['name'];
$currentfile1 = $_FILES['uploadedfile1']['name'];
$dbfiles = mysql_query("SELECT * FROM new WHERE amount='$currentfile' || amount='$currentfile1'");
if(mysql_num_rows($dbfiles) > 0 )
{
}
else
{
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "file1: ".$_FILES['uploadedfile']['name']."<br>";
$file1 = basename( $_FILES['uploadedfile']['name']);
mysql_query("insert into new (amount) values('$file1')");
}
if(move_uploaded_file($_FILES['uploadedfile1']['tmp_name'], $target_path1))
{
echo "file2: ".basename( $_FILES['uploadedfile1']['name']);
$file2 = basename( $_FILES['uploadedfile1']['name']);
mysql_query("insert into new (amount) values('$file2')");
}
}
?>
introduction and the problem
This code will allow the user to upload 2 files, then their respective file name will save to the new(name of table) , I need it to save in table so that i have history who was the uploader of the file and simply can retrieve it or download it. The first button is the uploadedfile where in the file will save in uploads folder, then the button below is the uploadedfile1 where in the file will save in upload1, when the user put 2 files in this 2 buttons, then the user click save, it will save to their prepared folder(uploads or upload1), when the user only attach one file whether in the button uploaderfile or uploaderfile1 and click Upload file/save/submit, it will still save its file name to table new and save the file in the following folder(uploads of upload1).
The Problem is when the user upload a same file name, For example abc.jpg is already exist in table new and in folder(uploads of upload1), but there some user also upload abc.jpg.. the problem is in the folder(uploads of upload1) the abc.jpg will only one(one pcs..) because same file name.. i think the solution is the rename, where in the abc.jpg that is currently uploaded will became abc_1.jpg, also in the table new abc_1.jpg will be save..
You shouldn't save the files by their original name.
It is better practise to assign the file a unique identifier in the database, and use this same identifier for the file name.
Then have a downloads page which retrieves the file path and original name from the database and send it to the user with readfile and set relevant headers:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize($file_path));
ob_clean();
flush();
readfile($file_path);
die();
This is also better from a security point of view as the users no longer need to know or have access to the file location on the server so if they upload anything malicious, they will be unable to call the file directly.
Edit:
To apply this, you will need to have a table for your file uploads with an autoincrementing ID field.
You can then insert the original filename and other relevant information into the database using mysql_query (as you are already using it in your example). You then need to pass the query into mysql_insert_id which will give you the unique identifier for the row you just inserted. Use this to name your file, followed by a '.dat' extension in your uploads folder.
When it comes to downloading, have a download page which takes an id by either query string or post parameter and then use this to look up the information in the database. You can figure out the filename given the ID as this is what you used to store it in the first place.
Once you have the file path and original name, you can use the code above to present the user with the download (after replacing $file_name and $file_location with your own parameters if you call them something else).
The downloads page will also need to handle any checks on whether or not the user is allowed to download the file.

PhP download link with variables

Ok, so I'm trying to create a download link generator on my site.
What I mean by that is this :
the user writes "list X" and the site lists every file in a given directory
every file has a number (from 0 to n)
when the user types : "download 5" for example
it redirects the user to a download script
the script makes it so that the user has a download "box" that pops-up
I first thought that I could create an array with every file name and then use the position in that array for the "download X" command.
So that, when he redirects the user to the download script, the variable with the name of the file that the user wants to download is "POST"ed to the download script and the header is changed in consequence.
So here are my two questions :
1) - How do you change the download script according to the users input ?
2) - The input field is already used for other purposes with a "$_SERVER['PHP_SELF']", so I don't know how to "POST" variables without a form ?
This is my simple download script :
<?php
header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');
readfile('huge_document.pdf');
?>
Thanks in advance !
Don't make them type in anything. Make each download a link they click on. In the link's URL you will have a query string with the download's unique identifier. Something like this:
Down file #6
downloadscript.php would then get the ID from the $_GET superglobal and you can go from there (using an array as mentioned in your example):
<?php
$download_id = (int) $_GET['id']; // 5
$files = array(
file1.pdf,
file2.pdf,
file3.pdf,
file4.pdf,
file5.pdf,
file6.pdf // This is the file they'll get
);
$filename = $files[$download_id];
// get the file name from your array or database
header('Content-disposition: attachment; ' . filename=$filename);
header('Content-type: application/pdf');
readfile($filename);
?>

Get output file with a .pdf extension in FPDF

This question is for those who have used PHP library FPDF (http://www.fpdf.org ) to generate PDF documents using PHP. I am generating a PDF file using the php file 'my_file.php'. I want users to be able to download that PDF file. But in the browser the see the file in the address bar as ..somepath..../my_file.php . I want them to see it as a file with .pdf extension. Any idea how this can be done ?
when you create the object and then try to make output like this
$filePath = "files/cache/myPdf.pdf";
$pdf=new FPDF('p');
...
$pdf->Output($filePath,'I');
you can change and send the file name
To force download:
$pdf->Output('D'); //Force download and set filename as 'doc.pdf'
or setting your own filename:
$pdf->Output('MyFilename.pdf','D');
Your browser shall not open another tab whit yourpath/my_file.php
You can't change the browser address bar, but you can change the address on your server. For example if you're using Apache, there's mod_rewrite which allows you to do such things.
If your problem is that when downloading the file, the browser wants to save it as .php, you could use those headers to force the download and a filename.
header('Content-Type: application/octet-stream');
header('Content-Length: ' . FILESIZE_HERE);
header('Content-Disposition: attachment; filename=' . FILENAME.pdf_HERE);

Categories