Mysql insert query runs many time on download after form submit - php

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.

Related

Php Textbox output is printing instead of downloading

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;

PHP Download Button Not Working Generate Empty File

I have two button in the form, one is to submit and second button download the output shown in the textarea.
The submit works fine but download button create empty file and does not write data of output text area.
Here is code:
<?php
error_reporting(0);
$mytext = "";
$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();
if(isset($_POST["submit"]))
{
for($i=0;$i<count($text);$i++)
{
$output[] .= trim($text[$i]) . ' Text added with output'.PHP_EOL;
}
}
if(isset($_POST["download"]) ) {
$handle = fopen("file.txt", "w");
fwrite($handle, implode($output));
fclose($handle);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment;filename='.basename('file.txt'));
header('Expires: 0');
ob_end_clean();
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
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>
You have to generate the output also if downloading (unless you take it from the second textarea), so use if(isset($_POST["submit"]) || isset($_POST["download"]) ) in the test, instead of only if(isset($_POST["submit"]))
The final code would look like this:
<?php
error_reporting(0);
$mytext = "";
$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();
/* CHANGED HERE */
if(isset($_POST["submit"]) || isset($_POST["download"]) ) {
for($i=0;$i<count($text);$i++) {
$output[] .= trim($text[$i]) . ' Text added with output'.PHP_EOL;
}
}
if(isset($_POST["download"]) ) {
$handle = fopen("file.txt", "w");
fwrite($handle, implode("\r",$output));
fclose($handle);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
ob_end_clean();
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
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>

downloads corrupt files from the file location on server

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.

Download script for PHP

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.

Download document from sqlite through website

I have store a sample document inside my local server named template.doc. Then I store the file directory inside my sqlite table. I manage to call out the path of the file directory but how can I allow the user to download it?
Codes
<form id="List" name="List" method="post" action="">
<select name="List" id="List">
<?php
if ($Choice !="No")
{
$path = $_SERVER['DOCUMENT_ROOT']."/WEB/";
$fullPath = $path.$_GET['$Choice'];
echo "<form id=\"form7\" name=\"form7\" method=\"post\" action=\"\">";
echo "<input type=\"submit\" name=\"Download\" id=\"Download\" value=".$fullPath."/>";
if (file_exists($fullPath))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fullPath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fullPath));
ob_clean();
flush();
readfile($fullPath);
echo "<label>".$fullPath."</label>";
echo "<input type=\"submit\" name=\"Download\" id=\"Download\" value=".$fullPath."/>";
exit;
echo '</form>';
}
}
?>
How to create a button below the list form and download the microsoft word? It now flushes out the Microsoft word text on the website now, not on the button.
Kindly advise if it's possible to do it. Just for local testing. Thanks alot!
You can use readfile and set the appropriate headers to force a download.
Example from readfile domestication page:
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
Your form should look something like this
<form name="download" action="download.php" method="post">
<input type="hidden" name="fileID" value="some file identifier" />
<input type="submit" name="submit" value="Download File" />
</form>
Then, in download.php
if(isset($_POST["submit"])) {
$file = $_POST['fileID'];
// download file
}

Categories