Image download function - php

So i made a image hosting site and im trying to add in a option to download the image. I have a s script and it works, just that all my images are stored in folders by date. so on the script its just a static url. How do i make this into like a function to add it into the actual image page, like "www.mysite.com/view-image/123456.png?download"
heres the code :
<?php
if (!$filename) {
// if variable $filename is NULL or false display the message
echo $err;
} else {
// define the path to your download folder plus assign the file name
$path = 'image.uploads/' .$imagedate/'.$filename;
// check that file exists and is readable
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo $err;
}
}
?>

If I got your question right, you want files to be downloaded when a user navigates to the path..
You can use .htaccess to force download the file rather than viewing it in browser..

Related

how to download file in php

I want to download image file in php.
<?php
if(isset($_REQUEST["file"])){
$filepath = BASE_URL.'assets/uploads/save_template_images/template1_221594899972.png';
// Process download
if(file_exists($filepath)) {
echo $filepath;
exit;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
die();
} else {
echo $filepath;
exit;
http_response_code(404);
die();
}
}
?>
In my index page, I have an anchor tag and if click on anchor tag then above code run. I am not showing anchor tag because, I put the $filepath static value in above code. When I run above code then it goes on else condition. I think, full path of project is not taking by above code. If I put image in same folder then it downloads.
First ensure allow_url_fopen setting in php.ini file is turned on. After that Use this code to download your file:
<?php
$url = 'https://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg';
$file = './files/'.basename($url);
file_put_contents($file, file_get_contents($url));
?>
For successful download, files directory must be exists. But I think it would be inefficient to add directory existence check as I think you already know where to save the file you are downloading.

Force File Download From Remote Server Downloads a Corrupted ZIP - PHP

I am working on making a very simple password protected "file downloader" that force downloads from a remote server (mediafire) after entering a password it seems to work but the file is always corrupted, anytime I try to open it, windows says: "Windows cannot open the folder the compressed(zipped) folder 'C:/users..' is invalid".
Here is the code for the download script:
$yourfile ='http://www.mediafire.com/file/filelinkhere';
ob_start();
if(isset($_POST['submit'])) {
$password = $_POST['password']; // required
if ($password <> "somepasswordhere") {
echo "<script type='text/javascript'>alert('//error: incorrect password//')</script>";
header( "Refresh:0; url=https://www.home/transfer.php", true, 303);
} else {
$filename = basename($yourfile);
header('Content-Transfer-Encoding: binary');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$size = filesize($yourfile);
header('Content-Length: '.$size.'');
readfile($yourfile);
exit;
}
}
Using advice from another related stack question I made sure that content-length header uses a real string, because filesize returns an integer. Does anyone know why the download is still coming through as corrupt?

PHP: Download file from Server

I have tried all sorts of codes I've found but nothing has worked for me...
When I use readfile() or fopen() or something like this:
function makeDownload($file, $dir, $type) {
header("Content-Type: $type");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($dir.$file);
}
... A download is started but the file is always empty...
here's the last code I've tried:
$filename = "gandalf.jpg";
// define error message
$err = '<p style="color:#990000">Sorry, the file you are requesting is unavailable.</p>';
if (!$filename) {
// if variable $filename is NULL or false display the message
echo " filename NULL";
echo $err;
} else {
// define the path to your download folder plus assign the file name
$path = 'upload/'.$filename;
// check that file exists and is readable
if (file_exists($path) && is_readable($path)) {
echo "file exists";
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: image/png');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error message if file can't be opened
//readfile($path.$filename);
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo $err;
}
}
This is the source of my code: Source code
I hope you can help me :)
I use google chrome
I need your help for this little project: Link to Project
When you click on a file in the drop down appears "herunterladen" (download in german) here is where I want to start the php download code
I just need the most basic download function for PHP... why is there an upload example on w3schools but NOT a download example? oO
$fileSource= $_GET['fileSource']; //If you are passing the filename as a URL parameter
$fileSource= "sample.pdf" //If the filename is fixed in the current folder
if($fileSource) {
$filesize = filesize($fileSource);
$path_parts = pathinfo($fileSource);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to
force a download
header("Content-type: application/pdf"); // add here more headers
for diff. extensions
break;
default:
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
if($filesize) {
header("Content-length: $filesize");
}
readfile($fileSource);
exit;
}

php download link to rar

I'm creating a website on my localhost that should let people download some .rar files.
In my index I've created some tags like this:
$filename = "Test001.rar";
'.$filename.'';
This is just an example of one single file, but in my php file 'download.php' I've got the problem when I want to download the .rar file
This is download.php
<?php
echo "Welcome to Knowledge!";
if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file'])
{
$file = $_GET["file"];
$path = 'C:\xampp\htdocs\TestSite'."\\".$file;
}
$err = $path.'Sorry, the file you are requesting doesnt exist.';
if (file_exists($path) && is_readable($path))
{
//get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/x-rar-compressed, application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($filename);
}
?>
It opens the stream in the right way, but I get that the file size is about 200 bytes and not the full length that is about 200MB.
How can I fix this problem?
Remove the echo statement, there should not be any output before the headers. Change readfile($filename) to readfile($file)

How to download zip file without downloading entire directory path too? (PHP)

I have the following zip download function:
$file='myStuff.zip';
function downloadZip($file){
$file=$_SERVER["DOCUMENT_ROOT"].'/uploads/'.$file;
if (headers_sent()) {
echo 'HTTP header already sent';
}
else {
if (!is_file($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($file)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($file));
header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
readfile($file);
exit;
}
}
}
The problem is when I call this function, I end up downloading not just myStuff.zip, but the complete directory path with all the folders. I'm on a Mac using XAMPP so this means I get the following:
/applications/xampp/htdocs/uploads/myStuff.zip
meaning i get a folder called applications with all the subfolders and then inside all of them I get myStuff.zip.
How can I just download myStuff.zip without its directories?
Try this.
readfile(basename($file));
Ok, I answered my own question by using the code in this link: http://www.travisberry.com/2010/09/use-php-to-zip-folders-for-download/
Here's the PHP:
<?php
//Get the directory to zip
$filename_no_ext= $_GET['directtozip'];
// we deliver a zip file
header("Content-Type: archive/zip");
// filename for the browser to save the zip file
header("Content-Disposition: attachment; filename=$filename_no_ext".".zip");
// get a tmp name for the .zip
$tmp_zip = tempnam ("tmp", "tempname") . ".zip";
//change directory so the zip file doesnt have a tree structure in it.
chdir('user_uploads/'.$_GET['directtozip']);
// zip the stuff (dir and all in there) into the tmp_zip file
exec('zip '.$tmp_zip.' *');
// calc the length of the zip. it is needed for the progress bar of the browser
$filesize = filesize($tmp_zip);
header("Content-Length: $filesize");
// deliver the zip file
$fp = fopen("$tmp_zip","r");
echo fpassthru($fp);
// clean up the tmp zip file
unlink($tmp_zip);
?>
and the HTML:
Download All As Zip
The key step in getting rid of the directory structure appears to be the chdir(). It is also worth noting that the script in this answer makes the zip file on the fly rather than trying to retrieve a previously zipped file as I did in my question.

Categories