The file moves to desired location and opens in the folder but when i download it downloads a corrupt file
I have tried all the suggestions from the existing posts but it doesn't seem to do the trick.
<?php
$error = "error";
$con = mysqli_connect('localhost','root','') or die($error);
mysqli_select_db($con, 'folder') or die($error);
$sql = "SELECT * FROM documents";
$res = mysqli_query($con, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Photo<br><br>
<?php
while ($row = mysqli_fetch_array($res)) {
$id = $row['id'];
$name = $row['name'];
$path = $row['path'];
echo $id." ".$name." <a href='download.php?dow=$path'>Download</a><br>";
}
?>
</body>
</html>
The upload code is:
<?php
$error = "error";
$con = mysqli_connect('localhost','root','') or die($error);
mysqli_select_db($con,'servicereport') or die($error);
if (isset($_POST['submit'])) {
$doc_name = $_POST['doc_name'];
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name) {
$location = "documents/$name";
move_uploaded_file($tmp_name, $location);
$query = mysqli_query($con,"INSERT INTO documents(name,path) VALUES ('$doc_name','$location') ");
header('location:photos.php');
}
else
die("please select a file");
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="doc_name">
<input type="file" name="myfile">
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
The download code is:
<?php
include('inc/db.php');
if (isset($_GET['dow'])) {
$path = $_GET['dow'];
$res = mysqli_query("SELECT * FROM documents WHERE path = '$path' ");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length:'.sprintf("%u", filesize($path)));
set_time_limit(0);
readfile($path);
}
?>
Please add these two lines of code after 'set_time_limit(0);' & before 'readfile($path);', because these functions are necessary for removing unnecessary data or preventing from corruption.
Find the code below, which are to be added:
ob_clean();
flush();
I hope, this will solve your problem.
Related
This problem is different of the other question problem. That problem was about IF condition. But this problem, instead of downloading file, it is printing on next page. Please don't confuse this question with others.
I have wrote a script which download output of text box. This script works fine on local server, it download the file successfully but when I put script on live server, the download file does not work. When download output button is clicked, instead of downloading file the output of page is shown on next page.
See live script here: http://www.globalitsoft.net/scripts/test.php
Here is the code of script:
<?php
error_reporting(0);
$mytext = "";
$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();
if(isset($_POST["submit"]) || isset($_POST["download"]) ) {
for($i=0;$i<count($text);$i++) {
$output[] .= trim($text[$i]) . ' AAAAA'.PHP_EOL;
}
}
if(isset($_POST["download"]) ) {
ob_clean();
$filename = "file-name-" .date('mdY-His'). '.txt';
$handle = fopen('php://output', "w");
fwrite($handle, implode($output));
fclose($handle);
header('Content-Description: File Transfer');
header("Content-type: application/force-download");
header("Content-Type: application/octet-stream charset=utf-8");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen(implode($output)));
readfile($filename);
exit();
}
?>
<form method="POST" action="test.php">
<textarea name="inputtext" rows="10" cols="100" placeholder="Enter Any Text!" required><?php if(!empty($_POST["inputtext"])) { echo $_POST["inputtext"]; } ?></textarea>
<br><br>
<input type="submit" name="submit" value="Do it!">
<br><br>
<p>Output goes here. </p>
<textarea name="oputputtext" rows="10" cols="100" ><?php echo implode($output);?></textarea>
<input type="submit" name="download" value="Download Output">
</form>
This works for me:
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);
header('Content-Type: application/octet-stream');
//You dont need to enclose the filename value in quotes
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Mysql run more than once while i try to download with download manager.
if(isset($_POST["fname"]) && isset($_SESSION['token']) && $_POST["token"] == $_SESSION['token']){
// after submit it runs two times
$sql = "INSERT INTO testpage SET
username = 'test',
name = 'xyz'
";
if(!mysqli_query($db_conx, $sql)){
echo mysqli_error($db_conx);
exit;
}
$fullPath = 'user/pdf/xyz.pdf';//let the path is this
$basefile_name = "abcd" ;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($basefile_name.".pdf"));
header('Content-Transfer-Encoding: binary');
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache");
header('Expires: 0');
header('Content-Length: ' . filesize($fullPath));
ob_clean();
flush();
readfile($fullPath);
exit;
}
if (function_exists('mcrypt_create_iv')) {
$token = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$token = bin2hex(openssl_random_pseudo_bytes(32));
}
$_SESSION['token'] = $token;
and the html part is
<div class="container">
<form method="post">
First name: <input type="text" name="fname"><br><br>
Last name: <input type="text" name="lname"><br>
<input type="hidden" name="token" value="<?php echo $token; ?>">
<input type="submit" value="Submit">
</form>
</div>
Still have problen even after adding token where i am wrong .
thanx in advance . php mysql.
Why when i try to export MySql table to CSV with header('Content-Disposition:attachment; filename="'.$filename.'"'); It doesn't get done properly:
it does create the CSV file
however it does it on the beginning of the file, where the page code is
and after the code the is table content
This is the code witch exports it:
$this->view->table = $model->info('name');
$is_csv = $this->_getParam('csv');
if ($this->_request->isPost() && $is_csv) {
$fichier = 'file.csv';
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="'.$fichier.'"');
$fp = fopen('php://output', 'w+');
$data = $model->fetchAll();
foreach ($data as $fields) {
fputcsv($fp, $fields->toArray());
}
fclose($fp);
}
And here i'm calling this with button:
<form method="post">
<input type="hidden" name="table" value="<?php echo $this->table ?>" />
<button type="submit" class="btn" name="csv" value="csv">
<?php echo Core_Locale::translate('CSV')?>
</button>
</form>
put this code up in your application then application create view.
I had same issue but i solved it this way..
i put peace of code to function/block and place it over echo or render html
put exit; on the end of function/block
if(isset($_POST['submit'])) {
$csv = new Csv();
$filename = $csv->generateFileDate();
if($filename !== false) {
$data = file_get_contents($csv->folder .'reports/'. $filename);
header('Content-Type: application/csv; charset=utf-8');
header('Content-Disposition: attachement;filename="'.$filename.'";');
echo $data;
exit;
}
}
?>
<!doctype html>
<html lang="us">
<head> .........
hope this help to you
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>
This is the code for the upload form to enable me to upload an image to the database
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This is the code that I have in a in a file called file_uploader.php. When trying to complete this I get the error Could not copy file!
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "databasehostdetails" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
You need to use tmp_name. Also, what is databasehostdetails? The second parameter is the destination (where you want to copy the file to).
copy($_FILES['file']['tmp_name'], DESTINATION_PATH);
Here is a simple way to do this. I am giving you my script
index.html
But be carefull:
It is not recommended since it is to costly for your database to store files
Fix any sql injection vurnelabilities. I my self don't know how to do this. You can make a research and fix it.
Also check out here Storing Images in DB - Yea or Nay?
However the code works pretty good if it not a large scale application and no sql injection attacks could happen.
<html>
<body>
<form method="post" enctype="multipart/form-data" action="doupload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
<input name="upload" type="submit" id="upload" value=" Upload ">
</form>
</body>
</html>
doupload.php
<?php
include("config.php");
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload set name='".$fileName."', size='".$fileSize."', type='".$fileType."', content='".$content."'";
mysql_query($query) ;
?>
getuploaded.php
<?php
// select records from database if exists to display
include("config.php");
$query1 = "SELECT id, name FROM upload";
$result1 = mysql_query($query1) or die('Error, query failed');
if(mysql_num_rows($result1)>0)
{
while(list($id, $name) = mysql_fetch_array($result1))
{
?>
<?php echo $name;?> <br>
<?php
}
}
?>
download.php
<?php
//header("Content-type: $type");
include("config.php");
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
config.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'uploadfile';
mysql_select_db($dbname);
?>
Createing the table
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);