trouble in download window - php

[QUOTE=php_lover;4343082]Hi all , I've writen a piece of code downloading file from mysql , here is the code :
php code :
$query = "SELECT name, type, size, content ,downloaded FROM ".filtering($cat , 'str')." WHERE id = '".filtering($id , 'int')."'";
$result = mysqlquery($query) or die('Error, query failed !!!');
list($name, $type, $size, $content, $downloaded) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
nothing is fail , when I try this script on my local machine the download window appears to me that where I whould download the file but when I try it on my server the download window won't appear and the content of file is shown on browser
for example when I want download .rar file these codes appear exchange of downloading window :
EVئ€#% ئ€"% èï‹ ‹}3غYئD0 C‹uhSC Vèڈ …ہYY…¢ 9E„=‏ےے…ےj^‰uüŒQ‏ےےےujXè(üےے…ہY…=‏ےے…ےtےu3ہےuèûےےYYé%‏ےے‹Mٹ‹ٌë<:tFٹ„ہuُ€> „µ ‹ئ+ء= r¸ے P‹Eےu¬ Pèظ‹ ‹EFVئ€« è›چ ‹M‹uƒؤ‰پ¬ hSC Vè^ژ …ہYY…ئ 9E„†‎ےے…ےj[‰]üŒ‎ےےVjXèsûےے…ہY…‎ےے…ے…† hSC ے

Use the Content-Type value application/octet-stream to force the download:
The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data
in a file, with any Content-Transfer-Encoding undone, or perhaps to
use it as input to a user-specified process.

Related

Php header() User Agent Change

$file_name = $_GET['title'];
$file_url = $_GET['url'] . $file_name;
header('Content-Type: video/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
exit;
I'm using this code to download files in my site fetching from another websites.
It works if my url looks like:-
https://www.example.com/video_download.php?title=video.mp4&url=http://googlevideo.com/video/download/223689/289048
(example)
So, it starts downloading by fetching the video file from http://www.googlevideo.com/video/play/221589 to my site.
But my problem is that the file can be accessed if the person uses a PC.
Can I change the User Agent by using header()?
Is it possible?
So if I change the user agent into a PC user agent, so it can be downloaded from a mobile!
I'm sorry, but the User Agent has nothing to do with readfile() function. Readfile() will just throw the raw file input into your browser. Useful for e.g. rendering images through PHP to the client without having to expose the real file name.
Indeed, it is possible to render video to the client with readfile(), but using a HTML5 video tag will dramatically improve performance. This will also provide better mobile support.
Hope this helps you,
You can use stream_compy_to_stream
$video = fopen($file_url);
$file = fopen('videos/' . $title . '.mp4', 'w');
stream_copy_to_stream($video, $file); //copy it to the file
fclose($video);
fclose($file);
I wrote a class for downloading youtube video files. you can find it here.

Uploaded medium blob truncated on download

I upload a blob to my sql database table with a field that is defined to be of size medium blob. The blob is actually a pdf file of size 4.3mb. The file is uploaded via ftp. After upload, some php code inserts it into the database. I've checked the file within the ftp folder and I can view it correctly. I've checked the file (blob) within the database and I can view it correctly. Both sizes show 4.3mb. If I try to download the file using some code provided by another programmer (below), the file is truncated at about 300kb.
if (!($dbLink = mysql_pconnect($db_server,$db_id,$db_pwd)))
{
print("Failed to connect to database!<BR>\n");
exit();
}
if(!mysql_select_db($db_name,$dbLink))
{
print("Cannot use the database!<BR>\n");
exit();
}
$query = "SELECT name, type, content FROM table_name WHERE link_id = '" . $id . "'";
$result = mysql_query($query, $dbLink) or die('Error, query failed');
list($name, $type, $content) = mysql_fetch_array($result);
//header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
I checked my maximum packet size within MySQL and it appears to be about 256mb. My php.ini shows 10mb for posts. I'm at a loss as to why the file is truncated. Can someone please point me in the right direction to solve this?
The PDO interface between PHP and MySQL offers a streaming scheme for LOB-handling. Seeing as how the mysql_ interface was abandoned years ago by its developers, it might be worth trying this.
See this: http://www.php.net/manual/en/pdo.lobs.php
You might consider using code like this.
$db = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'username', 'password');
$query = "SELECT name,
type,
OCTET_LENGTH(content) AS length,
content
FROM table_name
WHERE link_id = :link_id
LIMIT 1";
$stmt = $db->prepare($query);
$stmt->execute(array(":link_id" => $id));
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $type);
$stmt->bindColumn(3, $length);
$stmt->bindColumn(4, $data, PDO::PARAM_LOB); /* binds as a stream */
if ($stmt->fetch(PDO::FETCH_BOUND)) {
header("Content-Type: $type");
header("Content-Length: $length");
header("Content-Disposition: attachment; filename=$name");
fpassthru($data);
}
Sorry to say I haven't debugged this. But it's a fairly common use case.
I have resolved this with a different methodology. No matter what I tried from several different examples, I could not get the suggested PHP code to stop truncating files. I stopped storing the file as an attachment in the database, and, simply stored it in a separate folder on the server. The database was updated to insert a "path" link for the file. I changed the php code to:
// Construct an HTTP header that will force the browser to display/download the file.
header("Location: ".$location);
ob_flush();
exit;
This forced a relocation to the actual file stored on the server. The file now opens in the browser. Note: I also had to change some html code to force the file to open in a new tab in the browser.

downloading files with audio/mpeg mime type

I am trying to download remote mp3 files with an audio/mpeg mime type instead of right clicking on the link then saving as. I have tried modifying the header content-type with php headers and then calling the file with readfile(). This worked very well but because of the readfile() command the files came out of my servers bandwidth. is there another way of changing the header without the cost of bandwidth? can i define how the browser handles with content type with javascript? has anyone had the same problem?
Thanks in advance.
By using the mime type audio/mpeg you tell the browser to "do your default action with this file". In example if you have an jpg file and set the mime type to image/jpeg the browser will read the jpg and display it inside the browser window.
The solution is to use the mime type application/data instead. This will download the file leaving the browser out of it.
That would be
header("Content-type: application/data");
== Updated ==
A more complete approach
header("Content-type: application/data");
header("Content-Disposition: attachment; filename=$this->filename");
header("Content-Description: PHP Generated Data");
readfile($this->file);
If you want a dynamic mime type reader you could use this
$type = $this->get_mime_type($this->filename);
header("Content-type: " . $type);
...
private function get_mime_type($filename) {
$fileext = substr(strrchr($filename, '.'), 1);
if (empty($fileext)) {
return (false);
}
$regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext)/i";
$lines = file("mime.types", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
if (substr($line, 0, 1) == '#') {
continue; // skip comments
}
if (!preg_match($regex, $line, $matches)) {
continue; // no match to the extension
}
return ($matches[1]);
}
return ("application/data"); // no match at all, revert to something that will work
}
And, to get a list of mime types you can check my lab version, save the displayed content and save it to a file named mime.types in the root of your website.
http://www.trikks.com/lab/mime.html
Have fun
I think what you need to do is this:
$pathOfAudioFile = '/path/to/my/file.mp3';
header('Content-Type: audio/mpeg');
header('Content-Length: '.filesize($pathOfAudioFile));
// This next line forces a download so you don't have to right click...
header('Content-Disposition: attachment; filename="'.basename($pathOfAudioFile).'"');
readfile($pathOfAudioFile);
Using Content-Disposition: attachment... forces a download box to appear instead of having to right click -> save target as.

Unable to download files- PHP

This is the code I am using. As suggested I have added the headers for content type and disposition.
<?php
header('Content-Disposition: attachment');
header('Content-Type: application/octet-stream');
$con = mysql_connect("localhost","root","admin");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("acl_cake", $con);
$result = mysql_query("select * from attachments");
while($row = mysql_fetch_array($result))
{
echo 'Download--'.$row[3].'<br>';
}
mysql_close($con);
?>
Prior to addition of headers, I would have a few links available on the webpage. Whenever I would click one of them, a new page is opened and content in that file is displayed in the new page.
Now after adding the headers, whenever I load a page, I get a popup which asks me to download my form rather than the file.
If I have the content-disposition:attachment; filename='file.txt', then on page load there is a pop up to download the file "file.txt", and none of the links are displayed onto the webpage.
I am not sure if I have made a mistake with something.
I am not sure if I have made a mistake with the headers.
you need to send the content-disposition header to force a download
header("Content-Disposition: attachment; filename=\"my.file\"");
also set the content type explicitly:
header('Content-Type: application/octet-stream');
Add header Content-Disposition: attachment. See http://apptools.com/phptools/force-download.php
if i understand you right, you wan't to give your users a link to download a text-file. if so, you can do this by setting an application/octet-stream-header for this file (e.g. using php).
note: in most cases, i think you shouldn't do this. it't the users choice how to deal with files that can be opened by the browser, and if the user wan't to download such files, hea can easily configure his browser to to this or that.

Export mySQL to excel or csv

I'm no php expert (a mere beginner) but need some help!
After hours searching Google and trying out about 100 different scripts, I finally found one that does what I need - almost.
Basically, my site has a button marked 'Export to Excel'. Visitor to site clicks button and a download begins containing all data from a specified table.
I found this on here - PHP code to convert a MySQL query to CSV
which does exactly what I want except the user sees the following error when trying to open the file:
Error - 'The file you are trying to open, 'export.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Wo you want to open the file now?'
User clicks 'Yes' and file opens with all data! Brilliant! Except users will not open the file with this error.
I would be very grateful if someone knows a way to fix this.
Many thanks
TT
Or, you could just change the script in the above solution to return a file with the .csv extension. .csv files are associated with Excel, so they should open directly.
Ok, this results from a feature specified by Excel 2007 called Extension Hardening. You can turn it off, but that can only be done client-side. If you click "OK" or "Yes" the file should open anyway. Check this blog post for more info.
EDIT: What this means is that Excel is finding that the file is of a different type (say HTML or CSV) that what is specified by the file extension. Therefore Excel wants to warn you that this file is not what it says it is. Unless you are going to create native Excel files on the server then prompt the user to download them, there is no getting around this error except for each user to turn off Extension Hardening on their own computer.
if you make the first letters “ID” of a text file Excel incorrectly
assumes you are trying to open an SYLK file.
Meaning if the first row & column value is "ID", Excel will throw this warning. Just change it from "ID" to anything else.
Credit: http://alunr.com/excel-csv-import-returns-an-sylk-file-format-error/
Dim objXL As Excel.Application
Dim objWkb As Excel.Workbook
Set objXL = New Excel.Application
'turn off excel warnings
objXL.DisplayAlerts = False
'Open the Workbook
Set objWkb = objXL.Workbooks.Open(fpath)
functions sendFile($filename,$content_type="application/ms-excel") {
header('Content-type: '.$content_type);
header('Content-disposition: Attachment; filename=' . $filename);
readfile($filename);
}
I had the same problem so I looked at the following link: PHP code to convert a MySQL query to CSV
I modified one of the answers to get the headers to work.
include('DBFILE.PHP');
$select="SELECT * FROM SOMETable";
$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
//This is what I changed...
$headers ="";
while ($property = mysqli_fetch_field($result)) {
$headers.= $property->name.",";
}
$headers.="\n";
//////
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
I Tested this and it works like a charm, you just need to add your db connection or include the db.php file that you have.
you can change the name of the file if you edit the following line
header('Content-Disposition: attachment; filename="export.csv"');
Change export to what ever name you like.

Categories