In my website I want the users to download a music file when a button is clicked. The problem I am experiencing is that when the button is clicked the download starts but only 506 KB on a total of 4 MB are downloaded and when it is opened it shows unsupported format. I use this php download script with html form to make the download:
HTML FORM
<FORM ACTION="download.php" METHOD=POST>
<INPUT TYPE="hidden" NAME="music" VALUE= "music/<? print $file; ?>" >
<INPUT TYPE="SUBMIT" NAME="download" VALUE="Download">
</FORM>
PHP DOWNLOAD SCRIPT
<?php
$FileName = $_POST["music"];
$FilePath = "music";
$size = filesize($FilePath . $FileName);
header("Content-Type: application/force-download; name=\"". $FileName ."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". $size ."");
header("Content-Disposition: attachment; filename=\"". $FileName ."\"");
header("Expires: 0");
header("Cache-Control: private");
header("Pragma: private");
echo (readfile($FilePath . $FileName));
?>
Can you please point me to the problem?
Your code is looking for a file in a location like:
musicmusic/file.mp3
Assuming your file is actually stored in something like music/file.mp3, and variable $file contains something like file.mp3, you want to replace:
<INPUT TYPE="hidden" NAME="music" VALUE= "music/<? print $file; ?>">
with:
<INPUT TYPE="hidden" NAME="music" VALUE= "<? print $file; ?>">
and then replace this:
$FilePath = "music";
with:
$FilePath = "music/";
(or delete $FilePath at all)
Also, I would recommend you to check $_POST["music"] doesn't contain .. or start with / before you let anyone download any file from your server.
Related
I want user to click and download a .doc to wherever they want.. The files download but when you open it, Word says: 'Missing File C:\Users\MyName\style.css. I click OK and then it shows me a corrupted word document.
PHP
<?php
function download($pathToFile) {
header('Content-description: File Download');
header('Content-type: application/force-download');
header('Content-transfer-encoding: binary');
header('Content-length: '.filesize($pathToFile));
header('Content-disposition: attachment; filename="'.basename($pathToFile).'"');
readfile($pathToFile);
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['CVcrono'])){
download('../curriculum-vitae-modelo1-azul.doc');
}
elseif(isset($_POST['CVfun'])){
download('../curriculum-vitae-modelo1b-azul.doc');
}
elseif(isset($_POST['CVcomb'])){
download('../curriculum-vitae-modelo1c-azul.doc');
}
}
?>
HTML
<tr>
<td>
<input class='entButton' type='submit' name='CVcrono' value="Descargar">
</td>
<td>
<input class='entButton' type='submit' name='CVfun' value="Descargar">
</td>
<td>
<input class='entButton' type='submit' name='CVcomb' value="Descargar">
</td>
</tr>
Try insert
ob_clean();
ob_flush();
flush();
before
readfile($pathToFile);
Try changing the header to:
header("Content-type: application/vnd.ms-word");
Major Edit: I've updated my code to better include the Archive class, as well as the ZIP download. The table is written to the database just fine, but I get an error in my error log saying "No such file or directory." Where do I write the file per table?
Thanks so much for any help/suggestions!
Below is my code:
HTML Form
if($_POST['submit']){
if(empty($_POST['jobtitles'])) echo "<strong>Error: You have not entered a Job Title, please go back and enter one.</strong>";
else echo "<strong>Your documents are processing and being exported.</strong>";
}
?>
<body>
<center><strong><u>BLS Data Processor and Exporter</u></strong></center>
<form method="post" action="handler.php">
<p>Enter all of the desired jobs, each separated by a new line. Note: All jobs must be spelled exactly as contained in the BLS data</p>
<textarea name="jobtitles" rows="10" cols="50">
</textarea>
<p>Upon clicking submit, your tables will be generated and exported as a CSV file</p>
<p>Select the table types you would like to receive</p>
<input type="checkbox" name="tabletype[]" value="local">Local<br>
<input type="checkbox" name="tabletype[]" value="msa">MSA<br>
<input type="checkbox" name="tabletype[]" value="nmsa">NMSA<br>
<input type="checkbox" name="tabletype[]" value="state">State<br>
<input type="checkbox" name="tabletype[]" value="nat">National<br>
<input type="submit" value="Submit and Export">
</form>
</body>
PHP side
header("Content-disposition: attachment; filename=".$fileName);
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: application/zip;\n");
header("Pragma: no-cache");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
header("Expires: 0");
// Create the ZIP file
$zip = new ZipArchive;
$result_zip = $zip->open($fileName, ZipArchive::CREATE); // We open the file
if ($result_zip === TRUE) {
$pdo = new PDO("mysql:host=localhost;dbname=BLSdata","root","root");
$tableList = $pdo->prepare('SHOW TABLES FROM BLSdata LIKE "localTable" AND "msaTable" AND "nmsaTable" AND "stateTable" AND "natTable"');
$tableList->execute(array(''));
// For each table
foreach($tableList as $aTableList)
{
$content = export_table($aTableList[0]);
$fileName = $aTableList[0].'.csv';
$zip->addFile($fileName, $fileName);
}
$zip->close();
}
else
{
echo 'Failed, code:' . $result_zip;
}
readfile($fileName);
$deleteLocal = "DROP TABLE localTable";
$pdo->query($deleteLocal);
exit();
I am making a downloader for mp3 and mp4 and i want two php files in php with 2 buttons calling both php files but only the first php file works.
code for popup.php
<?php
include "downloadmp3.php";
include "downloadmp4.php";
?>
<html>
<head></head>
<body bgcolor="#E6E6E6">
<form method="post">
<label for="url">Download mp3:</label>
<input type="text" name="url" value="" id="url">
<input type="submit" name="submit" value="Download">
<hr>
</form>
<form method="post">
<label for="url1">Download mp4:</label>
<input type="text" name="url1" value="" id="url1">
<input type="submit" name="submit" value="Download">
</form>
</body>
</html>
code for downloadmp3.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$url = (isset($_POST['url']) && !empty($_POST['url'])) ? $_POST['url'] : false;
if (!$url) {
echo "Vul alstublieft een url in";
} else {
$source = file_get_contents($url);
$source = urldecode($source);
// Verkrijg de video titel.
$vTitle_results_1 = explode('<title>', $source);
$vTitle_results_2 = explode('</title>', $vTitle_results_1[1]);
$title = trim(str_replace(' – YouTube', ”, trim($vTitle_results_2[0])));
// Extract video download URL.
$dURL_results_1 = explode('url_encoded_fmt_stream_map', "url=", $source);
$dURL_results_2 = explode('\u0026quality', $dURL_results_1[1]);
// Force download van d video.
$file = str_replace(' ', '_', strtolower($title)).'.mp4';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: video/mp4");
header("Content-Transfer-Encoding: binary");
readfile($dURL_results_2[0]);
exit;
}
}
?>
and code for downloadmp4.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$url = (isset($_POST['url1']) && !empty($_POST['url1'])) ? $_POST['url1'] : false;
if (!$url) {
echo "Vul alstublieft een url in";
} else {
$source = file_get_contents($url);
$source = urldecode($source);
// Verkrijg de video titel.
$vTitle_results_1 = explode('<title>', $source);
$vTitle_results_2 = explode('</title>', $vTitle_results_1[1]);
$title = trim(str_replace(' – YouTube', ”, trim($vTitle_results_2[0])));
// Extract video download URL.
$dURL_results_1 = explode('url_encoded_fmt_stream_map', "url1=", $source);
$dURL_results_2 = explode('\u0026quality', $dURL_results_1[1]);
// Force download van d video.
$file = str_replace(' ', '_', strtolower($title)).'.mp4';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: video/mp4");
header("Content-Transfer-Encoding: binary");
readfile($dURL_results_2[0]);
exit;
}
}
?>
Updated:
Form submitted for MP3 form works.
But form submitted for MP4 doesn't works.
Please provide an solution to make it work.
Only first php file calls are working because of the following if condition:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
Since downloadmp3.php has been included first therefore it's if condition is giving the result.
Use proper form handler to make it work.
Also the best practice is to use unique names for the forms.
This code is working fine for me in all the browsers and the downloaded file is playing good :
download-audio.php
<?php
$file = $_GET['file'];
header ('Content-type: octet/stream');
header ('Content-disposition: attachment; filename='.$file.';');
header('Content-Length: '.filesize($file));
readfile($file);
exit;
?>
test.html
<a href='download-audio.php?file=duetsong.mp3'>Download Duet song MP3</a>
<a href='download-audio.php?file=duetsong.mp4'>Download Duet song MP4</a>
I have this form where you enter text into a text area and on submit php generates a text file which is supposed to contain the text that was entered in the text area.
But the problem is from the code i wrote, the text file does download but has no text in it.
So i change the text area into an input field with type text, and it returns the data in the text file, but with no line breaks. Here is my code
<html><body>
<form action="download.php" method="post">
<textarea id="output" name="output"></textarea>
<input type="hidden" name="op" type="hidden" id="fakeop" >
<input type="submit">
</body></html>
And the contents of php file are
<?php
$filename = 'random.txt';
$somecontent = $_REQUEST["output"];
!$handle = fopen($filename, 'w+');
fwrite($handle, $somecontent);
fclose($handle);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($filename);
?>
if i change to $somecontent = $_REQUEST["op"];
it does return the text file with the contents. but why not when its output.?
Hello Please Test the php page with below code
<?php
$filename = 'random.txt';
$somecontent = $_POST["output"];
!$handle = fopen($filename, 'w+');
fwrite($handle, $somecontent);
fclose($handle);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($filename);
?>
I have the following form:
<form action="download.php" method="get">
<input type="checkbox" name="file1" /> File1 <br/>
<input type="checkbox" name="file2" /> File2 <br/>
<input type="checkbox" name="file3" /> File3 <br/>
<input type="checkbox" name="file4" /> File4 <br/>
<input type="checkbox" name="file5" /> File5 <br/>
<input type="submit" name="mysubmit" value="Download!">
</form>
I cant then GET the ticked value:
<?php echo $_GET["file1"]; ?>
Gives the result: on
However want I want to be able to do is select those options, and each option relates to a PHP file, on Submit each file is combiled into a ZIP
Any help appreciated.
First, add a value field to your form fields and change them to an array:
<form action="download.php" method="get">
<input type="checkbox" name="file[0]" value="1" /> File1 <br/>
<input type="checkbox" name="file[1]" value="1" /> File2 <br/>
<input type="checkbox" name="file[2]" value="1" /> File3 <br/>
<input type="checkbox" name="file[3]" value="1" /> File4 <br/>
<input type="checkbox" name="file[4]" value="1" /> File5 <br/>
<input type="submit" name="mysubmit" value="Download!">
</form>
Next, in download.php:
if (!empty($_POST['file'])) {
// open zip
$zip_path = '/path/to/created/download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::CREATE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
// checkbox values dont matter because only checked boxes show up in POST data
foreach ($_POST['file'] as $key => $val) {
// generate filename to add to zip
$filename = '/path/to/php/file' . $key . '.php';
$zip->addFile($filename) or die ("ERROR: Could not add the file $filename");
}
$zip->close();
//===============
// force download
//===============
// assume you have a full path to file stored in $zip_path
if (!is_file($zip_path)) {
die('The file appears to be invalid.');
}
$zip_path = str_replace('\\', '/', realpath($zip_path));
$filesize = filesize($zip_path);
$filename = substr(strrchr('/'.$zip_path, '/'), 1);
$extension = strtolower(substr(strrchr($zip_path, '.'), 1));
// use this unless you want to find the mime type based on extension
$mime = array('application/octet-stream');
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.sprintf('%d', $filesize));
header('Expires: 0');
// check for IE only headers
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))) {
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
} else {
header('Pragma: no-cache');
}
$handle = fopen($filepath, 'rb');
fpassthru($handle);
fclose($handle);
} // close $_POST check
You can use isset($_FILES['file1']) to check if file1 is uploaded
Loop from file1 to file5
Save files from temporary paths to permanent ones
Zip them using http://php.net/manual/en/book.zip.php & http://php.net/manual/en/ref.zip.php
Optional: Delete the uploaded files (using unlink)
Force download the zip file to the browser. See this: http://php.net/manual/en/function.header.php
It's quite simple. Enjoy!