I am very new to PHP. I am trying to make simple script which allows the users to download files from a webpage.
<?php
require_once('Connections/connection_psfriend.php'); ?>
$receivedfilerequest = addslashes($_REQUEST['filesource']);
$file_path = $_SERVER['DOCUMENT_ROOT'].'/'.'ps-friend'.'/' . $receivedfilerequest;
if(file_exists( $file_path)){
echo 'The file exists';
$size = filesize($file_path);
echo $size; //Its working perfectly fine till here.
exit;
}
But what do I do next so that this file is actually downloaded. I saw some tutorials and they use header("Location: ".$file_path); after this. But that's not working for me. What does this header function actually do, and what should be the code to actually download this file?
You can use the PHP's readfile (http://php.net/manual/en/function.readfile.php) to force a file download, if that's what you are trying to do. There is an example on that page shows you how to download an image.
The PHP header function sends a raw HTTP header to the client. The location header is usually used to redirect the client to a new page in PHP.
please refer this URL, it is used to download file
http://php.net/manual/en/function.readfile.php
Related
Can anyone tell me why I am unable to display a PDF file using PHP? It says LOADING in lower left corner which never goes away. I can use the control panel and view the pdf just fine, so I know it's a valid PDF file.
Here's the code:
<?php
session_start();
$path = '/show_bills/';
// The location of the PDF file on the server.
$filename = $path.$_SESSION['ShowID']."_show_bill.pdf";
header("Content-type: application/pdf");
header("Content-Length: " . filesize($filename));
readfile($filename);
exit;
?>
Thanks,
Vic
I am almost sure the file just does not exist. You have a trailing slash in the $path meaning the the script will look for the file in the very root of the server
You can check whether the file exists or not using file_exists function
http://uk3.php.net/manual/en/function.file-exists.php
Also, just try to output the file without specifying headers - probably it outputs a PHP warning
I'm sure this is a simple task, but on my wordpress site I want to create a download button that forces an .mp3 download, without opening a player (when left clicked), or the user having to right-click 'save target as'. I just need a straight forward button, that when left-clicked causes a file to be downloaded (as well as being easily trackable by Google Analytics).
Is a .php script required for this? You'd think this would be a very common function, and easy to solve....but I have spent hours on this and have been unable to get anything to work.
*if it's not obvious my coding skills are nearly non-existent.
I really appreciate anybody's time who can help me figure this out. Thanks!
***EDIT
Just found this on another post, but no comments if it would work or not. It was for a .pdf file though...
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'] ;
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
}
} else {
header("HTTP/1.0 404 Not Found");
echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";
}
?>
Save the above as download.php
Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.
You can use it like so:
Add the following link to your HTML file.
Download the cool PDF.
Well, this is possible, but you need to write a script to do it. This is a pretty poor (security and basic coding wise) from http://youngdigitalgroup.com.au/tutorial-force-download-mp3-file-streaming/
file: downloadit.php
<?php
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header ("Content-Length: ".filesize($file));
readfile($file);
exit;
?>
you would then place it into a publicly accessible folder and build your links as such:
http://www.yoursite.com/downloadit.php?file=/uploads/dir/file.mp3
what this does is tells the browser to treat the file as a stream of bytes, rather than a particular MIME type which the browser would ordinarily do based on the file extension.
I am coding a register form and need to include a pdf file next to a checkbox. The pdf file contains important information that the user needs to agree to before sending the form. When you click on the file name that appears next to the checkbox, the browser must ask you if you wanna view or download the file.
How do I realize this?
The way I would go about this is create a download directory "/downloads" and inside there put a php file named index.php with the following code
<?php
$file = 'http://example.com/download/' . $_GET['file']; //Thanks DanFromGermany!
if($file == 'http://example.com/download/index.php'){die;}
$file_headers = #get_headers($file);
if(substr_count($file_headers[0], '404 Not Found') || substr_count($file_headers[0], '410 Gone')){
exit;
} else {
if($file == 'http://example.com/download/index.php'){die;}
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$_GET['file'].";");
header("Content-Length: ".filesize($file));
readfile($file);
header('Location: http://example.com/thanks'); //send them to a thanks page or close the window, whatever works for you
exit;
}
?>
Place whatever files you want to be downloaded (read_this.pdf) Then link them as follows
Download this PDF
any filename you point to with the file being placed inside "/downloads" will force their browser to download it.
edit however I agree with Jeroen's suggestion about putting it in a scrollable div. to do this the file would need to be html though but you could use something like http://www.pdftohtml.net/ to make the html look just like the pdf did. I personally leave a website when it tries to force me to download something because you never know what it could be. I only use this method when giving someone a file to download. otherwise, hope this is what you were looking for.
This is one I just can't figure out: I have successfully built an upload feature on a web page to upload files to a MySQL Database. When I go on the server and open them via phpMyAdmin, they all look fine... txt, jpg, pdf, etc.
Yet, after putting together THIS thing (below) to download it, I get a strange problem: All of the text documents (and all other types of files, after I change the extension to 'txt') contain HTML code of the page itself, followed by the original content!
Also, different browsers display differently after the POST. When trying to download a txt file, IE will show the correct data in the ECHO on the page itself (no downloading) with an error message just before it:
Warning: Header may not contain more than a single header, new line detected. in C:\wamp\www\ace\dmain.php on line 82.
Line 82 is 'header("Content-length...'
Neither Firefox nor Chrome show anything. They just allow me to download it.
Here's the code:
<?php
if (isset($_POST['downloadid'])) {
$fileid = $_POST['downloadid'];
try {
$sql = "SELECT * FROM `datastore` WHERE `id` = '".$fileid."'";
$results = $pdo->query($sql);echo $sql;
while ($row = $results->fetch()) {
$filename = $row['filename'];
$mimetype = $row['mimetype'];
$filedata = $row['filedata'];
header("Content-length: strlen($filedata)");
header("Content-type: $mimetype");
header("Content-disposition: download; filename=$filename"); //disposition of download forces a download
echo $filedata;
// die();
} //of While
} //try
catch (PDOException $e) {
$error = '<br>Database ERROR fetching requested file.';
echo $error;
die();
} //catch
} //isset
?>
This:
header("Content-length: strlen($filedata)");
Is not going to produce what you expect. If you look at the headers in wireshark, or another method to view the request you will see that it does not contain an integer.
Use this instead:
header("Content-length: ".strlen($filedata));
After agonizing over fixing it in-place (that is, on the same page with the rest of the html and code), I decided to move it to a dedicated PHP page. After that, it worked fine.
Thanks for the comments!
here is good example and complete source
Here is a code which retrieves a file (say .doc) from a server, stores it in a temporary folder and then uses an api (say google viewer) to display it and then deletes it.
<?php
$body = "....."; //data from imap server
$name = "abc.doc";
$file = fopen("temp/" . $name,'w');
fwrite($file,$body);
fclose($file);
$url = rawurlencode("http://www.xxx.com/temp/".$name);
// I do not have a direct url to the file on the imap server, thus have to store it in a temporary folder
echo "<iframe src=\"http://docs.google.com/viewer?url={$url}&embedded=true\" width=\"100%\" height=\"100%\" style=\"border: none;\"></iframe>";
unlink("temp/".$name);
?>
Now the issue is that since the php script executes itself first and then echo's the buffer, the google viewer cannot find the file since its already deleted. Using flush() does not help either.
One work around is to remove the "unlink" command and create a cron-job to delete all files in the temp folder (say after every 2min). Is there a better way to do it?
I'd make the link to
echo "<iframe src=\"http://docs.google.com/viewer?url="http://www.domain.com/viewthis.php?name=abc.doc&embedded=true\" width=\"100%\" height=\"100%\" style=\"border: none;\"></iframe>";
then make viewthis.php stream the file... then as soon as it's served, you can delete it.
I assume (looking at the comment in line 2) that you are trying to view mail attachments. What you can do is dynamically create a file url for google to lookup the file. What you do is create a script, say 'view_file.php', which loads/downloads the file and pushes the file back, with some custom headers to tell the 'browser' (google) what kind of file it is. In this way you do not have to save the file. Downside is that the file will be accessible always from the outside, so you still should set a timer or something like that.
For an image you would do something like this:
$im = file_get_contents('http://www.site.com/url_to_your_image'); // or any other function to retrieve the image data itself
header('content-type: image/gif');
echo $im;
For any other file, just change the content-type header.