Dnt allow user to access document from url - php

I want the log in user can access the PDF file and anonymous user can not access the file from browser like www.domain.com/pdf/name.pdf
My pdf file is getting corrupted.It is gets failed when clicked for download.
I have created pdf folder in that kept my all pdf.
I have html code
<ul>
<li>
Test
</li>
</ul>
check.php file
if($_SESSION[login]==true){
$file_url = 'http://domainname.com/pdf/example.pdf';
$filename='example.pdf';
header("Content-Disposition: attachment; filename=" . urlencode($filename));
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file_url));
$fp = fopen($file_url, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
}
ht.access
RewriteEngine on
RewriteRule .* check.php

Just add a function in your php file as below:
function protect_page(){
if(logged_in()===false){
header('Location: protected.php');
exit();
}
}
Check whether the user is logged in by doing
$_SESSION[login]==true
Write the above protect_page() function on the page that has link to your pdf.
And you're good to go.

Related

Force Download an External or Internal File

Force Download a External or Internal File like jpg
Example method 1 for external or internal file:
https://example.com/photos/photo.jpg/download?force=true
https://pixabay.com/images/download/wintry-69661.jpg?attachment
Another, this method will generate the download link
https://www.pexels.com/photo/2755165/download/
I know this method 2: but I need the above method 1.
https://download.example.com/images/download.php?file=9284.jpg
I have multiple codes to force download like method 2. But I need method 1.
I'm using this PHP to force download for method 2
<?php
if(!empty($_GET['file'])){
$fileName = basename($_GET['file']);
$filePath = '/home/download.example.com/images/'.$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: image/jpeg");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
}
?>
Thank you

Detect if php is called from a src?

So here's a question. Can a php script detect how it is being called? For example if it is called through <img> it will return an image, or if it is being called through <video> it will return video, or if it is called through <audio> it will return audio, or if it is called directly by typing in http://www.example.com/callme.php it will return some text.
The content from this callme.php would be provided through the following method:
header("Content-Disposition: attachment; "
.sprintf('filename="%s"; ', rawurlencode($_REQUEST['F']))
.sprintf("filename*=utf-8''%s", rawurlencode($_REQUEST['F'])));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
flush(); // this doesn't really matter.
$fp = fopen($file, "r") or die("DEAD");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
No this is not possible, at least not without some additional parameters in the URL.
Consider the following HTML
<img src="/callme.php?target=img" />
With the following PHP:
if ($_GET('target') == 'img') { ... }

PHP: How to hide URL

I have the following download.php script to download a file, which works great:
<?php
header("Content-Type: application/octet-stream");
$file = $_GET["file"];
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
?>
What I want to achieve is to hide the URL where this file is located, so that when the user clicks a link such as <a target="_blank" href="http://domain.com/files/download.php?file=filename.pdf">Download file</a>, a new tab opens up with no URL and starts downloding the file. What is actually happening is the new tab opens and the file download starts but the URL bar is displaying http://domain.com/files/download.php?file=filename.pdf.
If this cannot be done with php, how can I achieve this? I have seen several downloads where the URL is not shown, so I know this is somehow possible.
EDIT: Here is the reason I want to do this: We will send a html mailing with a link to the file download, and the website where this file download is hosted is not the website from the company which sends the mail.
As always, thank you very much.
A typical way doing this, is to place the files you want to provide for download outside your docroot.
Your download script should know about this place and has to process the requested filename considering this.
For example:
path/in/your/system/docroot/download.php
and
path/in/your/system/files/filename.pdf
If someone is requesting download.php?file=filename.pdf your script has to look up in path/in/your/system/files/ for this file and has to handle it.
You can create a new window with iframe content to that URL.
var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));
win.document.body.innerHTML = "<iframe src='YOUR URL'></iframe>";
If you remove the target="_blank" no new tab will be opened and the file will just be downloaded.
In the end, it's not possible because the user can open Google Inspector and check the Network tab.
Edit: If that's the case, you would use JavaScript:
Edit 2: In case the popup is blocked by the browser or addon, use a fallback:
Edit 3: In case JS is disabled:
<head><meta http-equiv="refresh" content="5;http://domain.com/files/download.php?file=filename.pdf">
<script>
var win = window.open("http://domain.com/files/download.php?file=filename.pdf");
if (!win) {
window.location = "http://domain.com/files/download.php?file=filename.pdf";
}
</script>
</head>
Edit 4: If you don't want the user to see the domain of the user site at all, get your PHP script to download the file and then output that to the user:
header("Content-Type: application/octet-stream");
$file = $_GET["file"];
$file = 'http://otherdomain.com/location/' . $file; // This line should suffice for all that you're trying to do
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
Submit the form as POST and use $_REQUEST to get the file:
$file = $_REQUEST["file"];

php download file: header()

I need some eduction please.
At the end of each month, I want to download some data from my webserver to my local PC.
So, I've written a little script for that, which selects the data from the DB.
Next, I want to download it.
I've tried this:
$file=$month . '.txt';
$handle=fopen($file, "w");
header("Content-Type: application/text");
header("Content-Disposition: attachment, filename=" . $month . '.txt');
while ($row=mysql_fetch_array($res))
{
$writestring = $row['data_I_want'] . "\r\n";
fwrite($handle, $writestring);
}
fclose($handle);
If I run this, then the file is created, but my file doesn't contain the data that I want. Instead I get a dump from the HTML-file in my browser..
What am I doing wrong..
Thanks,
Xpoes
Below script will help you download the file created
//Below is where you create particular month's text file
$file=$month . '.txt';
$handle=fopen($file, "w");
while ($row=mysql_fetch_array($res)){
$writestring = $row['data_I_want'] . "\r\n";
fwrite($handle, $writestring);
}
fclose($handle);
//Now the file is ready with data from database
//Add below to download the text file created
$filename = $file; //name of the file
$filepath = $file; //location of the file. I have put $file since your file is create on the same folder where this script is
header("Cache-control: private");
header("Content-type: application/force-download");
header("Content-transfer-encoding: binary\n");
header("Content-disposition: attachment; filename=\"$filename\"");
header("Content-Length: ".filesize($filepath));
readfile($filepath);
exit;
Your current code does not output a file, it just sends headers.
in order for your script to work add the following code after your fclose statement.
$data = file_get_contents($file);
echo $data;

Download counter of exe file in PHP

I have a problem with counting downloads of file. There will be no problem if a link to the download file would look like this: http:// your.site.domain/download.php?file=filename.exe&customer=ABC_423. However my customer want to count statistics from link like this: http:// your.site.domain/downloadsfolder/ABC_423/filename.exe and also he needs to hotlink that link on other sites.
I think there would be solution in .htaccess file, but I don't know how to make a proper redirect.
My PHP script looks like this:
session_start();
define('SERVER_NAME', 'www.siteaddress.domain');
define('DOWNLOAD_PATH', 'http:// siteaddress.domain/versions/download');
define('DOWNLOAD_FILE', 'Setup.exe');
$filename = DOWNLOAD_PATH . '/' . $_GET['customer'] . '/' . DOWNLOAD_FILE;
$headers = get_headers($filename);
if ($headers[0] == 'HTTP/1.1 200 OK'){
// file exists, begin download procedure
if(isset($_GET['customer'])){
// begin update statistics
// mysql query to update specified row
}
// headers for downloading file
header("Content-Type: application/force-download");
header('Content-Type: application/x-unknown');
header("Content-Type: application/octet-stream");
//header("Content-Type: application/download"); // not sure if needed
header("Content-Disposition: attachment; filename=".basename($filename).";");
header("Accept-Ranges: bytes");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".remote_filesize(SERVER_NAME, $filename));
ob_clean();
flush();
readfile($filename);
exit;
}else{
echo 'File not found';
exit;
}
This is a simple RewriteRule in .htaccess. Something like this:
RewriteEngine On
RewriteRule ^/downloadsfolder/(.*)/(.*) /download.php?file=$2&customer=$1 [L]
Observe how a random char sequence is detected with (.*) and then used with $1 and $2 for each detected item in the translated URL.
Hope that helped!

Categories