allow user to download after submitting form data - php

I have to allow a user to download after he has submitted his USER data.
I've created three pages,
will display files available for download(catalogue_downloads.html)
will take in USER data (form_collecting.php)
will take user data validate it send it to an email address and redirect to downloads page (mail.php)
The schema is so catalogue_downloads.html->form_collecting.php->mail.php->catalogue_downloads.html
I am able to redirect to catalogue_downloads but how can I make the user download the file he requested via PHP
Thank you
Regards
Vinoth

http://php.net/manual/en/function.readfile.php read the first part (forcing a download), you can read a file and then sending it to the user via the headers. Thus you don't have to give away your file structure (and perhaps even letting the file outside your website's root/public_html).

You can't feed the user multiple files, so unless you compress them server side in a single archive you have to show him the links to the files.
However, you're not limited to a link to the actual file, you can link to a "dowloader page" which feeds the user a single file when called so unauthorized users can't access the files (see PENDO's answer on how to do that).

you can user below code if needed..
$root = $_SERVER['DOCUMENT_ROOT']; $site = '';
$folder = "path where you want to store downloaded files";
$fullPath = $root.$folder.'/'.$_REQUEST['filenm'];
//$_REQUEST['filenm'] = file name which you want to download.
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower(html);
header("Content-type: application/".$ext);
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment;filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
} } fclose ($fd); exit;
Thanks.

Here is the deal:
When redirecting from catalogue_downloads.html to form_collecting.php, give your catalog a unique ID and post it to form_collecting.php. Keep a hidden input field in your form which will keep the previously posted catalog ID. When the form is posted and validated start the process of mail.php. When mail is successful, read the catalog ID and redirect your user to the catalogue_downloads.html.
Hope this will help you out.
Regards

Related

Is it possible to send a header from a PHP file, that does absolutely nothing

On a page where I offer music sample downloads, I have several <a> tags whose href points to a PHP file. Various data included as GET vars allow the proper file to be downloaded. Normally the PHP will respond with typical download headers followed by a readfile(). (the code for that is below, FYI). This results in a clean download (or download / play dialog box on some browsers). By "clean", I mean the download is completed with no disturbance in the visitors page.
However, in the unlikely event that the requested file is unavailable, I don't know what to do. I know it should not happen, but if it does I would like the download link to simply do NOTHING. Unfortunately since it is an <a> tag referencing a PHP file, doing nothing results in the browser clearing the page, with the URL of the PHP file in the address bar. Not a good visitor experience! So I'd like way to avoid disturbing the page and doing NOTHING if there is is an errant request. I'll use javascript to alert the visitor about what went wrong, but I can't have the errant file request clear the page!
I thought I'd had a solution by issuing a header('Location: #'); when the script detected an impossible file download. But after a few seconds the browser cleared the page and put up a message indicating the page "redirected you too many times." (indeed, my script log fills up with over 100 entries, even though i only clicked the tag once.)
So far the only solution I have that works (works in the sense of NOT disturbing the visitors page if an "unavailable" file is requested) is to point my download headers at a "dummy" file. An actual "silence.mp3" or "nosong.mp3" file. But is there a way to call a header() that does nothing to the calling page? Simply calling exit or exit() won't work (the visitor page is redirected a blank.)
Not that it matters, but this is the code I normally call in response to the d/l request...
function downloadFile($path) {
$path_parts = pathinfo($path);
$ext = strtolower($path_parts["extension"]); // don't need this.
$fsize =fileExists($path);
if ($fsize == 0)
{
header('Location: #'); // this doesn't work!!! (too many redirectcts)
exit;
}
//$dlname = $path_parts['filename'] . "." . strtolower($path_parts["extension"]);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: filename=\"" . $path_parts["basename"]."\"");
header("Content-Type: application/x-file-to-save");
header("Content-Transfer-Encoding: binary");
if($fsize) header("Content-length: $fsize");
$bytesRead = readfile($path);
return $bytesRead;
}
If you are using HTTP/1.x with a standard anchor tag, without JavaScript or other client-side interception. An HTTP/1.0 204 No Content status header will cause the user-agent to simply seem like nothing happened when clicking a link that returns a 204 status header.
HTTP/1.0 204 No Content
The server has fulfilled the request but there is no new information
to send back. If the client is a user agent, it should not change its
document view from that which caused the request to be generated. This
response is primarily intended to allow input for scripts or other
actions to take place without causing a change to the user agent's
active document view. The response may include new metainformation in
the form of entity headers, which should apply to the document
currently in the user agent's active view.
Source: https://www.w3.org/Protocols/HTTP/1.0/spec.html#Code204
This is also compatible with the HTTP/1.1 protocol.
I recommend using output buffering to ensure no other content is being sent by your application by mistake. Additionally there should be no need to send a Content-Length header.
function downloadFile($path) {
if (!is_file($path) || !($fsize = filesize($path))) {
header('HTTP/1.0 204 No Content');
exit;
}
$path_parts = pathinfo($path);
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: filename="' . $path_parts['basename'] . '"');
header('Content-Type: application/x-file-to-save');
header('Content-Transfer-Encoding: binary');
header('Content-length: ' . $fsize); //fsize already validated above.
return readfile($path);
}
Performing the file checks before creating the links is the simplest way to do this.
If I understand your request correctly you have files that you wish to allow a client to download, and links to PHP scripts that download certain files.
The problem with your implementation is that when the file is empty, the PHP script still must load and change the content of the clients page(from the action of loading the script), which is the incorrect behavior (correct being no action at all).
Since you are using tags on the main download page, really the only way to not change the content of the page in the case of a missing file is to compute the content of the tags in advance. With a simple PHP function you could check the contents of a list of files and their directories, and then generate links for the ones that exist, and blank links for the ones that do not.
Overall, I think separating the functionality of checking whether a file exists and actually downloading the file to a client is the only way to allow the functionality you desire.

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.

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.

Prevent downloading media unless the user has filled in a form

Im making a website for a band, and they are giving out their EP for free, but they want it so the user has to enter their email address before downloading... How would this be done in php?
The downloadable should be placed out of the reach of web user but within your PHP script reach. Then once user is done filling form, you can then force download the file contents by opening it locally using say "fopen".
Update (Adding Sample Code):
Suppose the file is "txt.txt" which could be in your script reach. You will open it, read and then put the contents after calling header and telling it that its an attachment (force download)
$done = true;
if($done == true){
$filename = "txt.txt";
$conn = fopen($filename,"r");
$contents = fread($conn, filesize($filename));
fclose($conn);
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="downloaded.txt"');
echo $contents;
}
If you're storing the emails somehow, then simply set a $_SESSION value when they submit their email, and when writing the page, if the part of the $_SESSION value has been set, then provide a link to the media.
To start a session & set the value:
session_start();
$_SERVER['hasEmail']=true;
And in the page:
session_start();
if ($_SERVER['hasEmail']) {
//Provide link
}
You could then also have the media link take you to a PHP script which uses fopen() or similar to get the file from another location on your filesystem out of reach of the user, such as one under .htaccess blocking, and it'll only provide the media is the $_SESSION value is set.

File open/save as dialog and mime types

I am working on a simple document management system for a site - the user can upload around 20 different file types and the docs are renamed then stored in a folder above www, an entry is created in a docs table to capture meta data entered by the user and the item is then retrieved via another php file so the stored location for the files are hidden from the user.
When a user clicks to download a file using a simple a href it calls, for example, "view.php?doc=image.jpg" - when they do this currently the file opens in the browser so a jpg opens a window with pages of "wingdings" like characters etc.
I would like to be able to force a open/save dialogue box so the user decides what to do and my app doesn't try to open in the browser window with the above results.
From a previous posting I found I know I cannot pass the mime type in the "a href" tag so what other options do I have? Could I put header information into the below view.php file, for example?
$_file = $_GET['doc'];
$filename = './dir/'.$_file;
if (file_exists($filename)) {
echo file_get_contents('./dir/'.$_file);
} else {
echo "The file $_file does not exist";
}
;
You could use get_headers() to get the MIME type header of the desired file, and then use header() to output those headers into the file you're showing.
Alternatively, to simply force downloads, this:
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
Should do it.

Categories