php script to update mysql table on click of link - php

I'm new to php and need help.
My link as below:
//create a path to download
echo '<a download="Final_File_'.$filenames.'" name="save" href="'.$DownDir. "/".$filenames.'" target="_blank"><img src="images/Save File.png"/></a>';
//Query
$Query = 'UPDATE `tbl_download_log` SET `User_Id` = `User_Id`, `path` = `$DownDir. "/".$filenames`';
Saves a file on the click of the ImageLink and need to update the a table in MySQL DB named tbl_download_log with the 'user ID' & 'Download link' at the same time.
I established the connection and got the user ID as well.
Please help me to update both the thing in db table.
Updating new script in it.
<?php
$DownDir = "http://localhost/SGA-INTRANET/".$kmsroot. "/". $user. "/". $bu. "/". $client. "/". $project."/Final";
$filenames = "file.xlsx";
$pathDown1 = $DownDir. "/".$filenames;//download path
//using download functionality of HTML 5
echo '<a download="Final_File_'.$filenames.'" name="save" href="'.$pathDown1.'?id='.$name.'&filepath='.$pathDown1.'" target="_blank"><img src="images/Save File.png" title="Download the file"/></a>';
?>
<?php
$ide = $_GET['id'];//EmployeeID
$file = $_GET['filepath'];// Path
if(isset($ide) && isset($file))
{
if(file_exists($file))
{
//save log to DB table 'tbl_km_file_download'
$mysqli = new mysqli("localhost", "USERNAME", "PASSWORD", "DBNAME");
$mysqli->query("INSERT INTO `tbl_km_file_download` (`name`, `filename`) VALUES ('$ide', '$file')");
}
}
?>
which is downloading files but not updating the DB table.
Please see the images.
Please help.

You can pass data through the href with query strings.
Example
echo 'CLICK THE LINK';
$file should be a root-relative path, starting with a /.
Then in download.php:
<?php
$id = $_GET['id'];
$file = $_GET['file'];
if(isset($id) && isset($file)) {
if(file_exists($file)) {
//connect to database .... (I show it with PDO)
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', USERNAME, PASSWORD);
$stmt = $db->prepare("INSERT INTO `tbl_download_log` (`User_Id`, `path`) VALUES (?, ?)");
$stmt->execute(array($id, $file));
//download the 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, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
} else echo "The file does not exist.";
} else echo "An error occurred.";
Hope this helps.

Related

Uploaded file is unable to read after downloading in PHP

I wrote php script to upload file from admin panel and to download for user.
Uploading was done successfully but after downloading the file, it is unable to read. if it is a image file or pdf file. The uploaded files are copied to xamp/htdocs/myproject/admin/documents. and the path is stored to mysql database. When i tried to download it the file size is different for uploaded file and downloaded file and it is unable to read.
The uploading script
if (isset($_POST['submit'])){
$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 posts (name,path) VALUES ('$location')");
}
Thanks everybody for helping me. i made changes for my script yesterday and it is working but the problem is that when i tried to add it to my project it is not working.
my uploads script(it is writen in myproject/admin/application.php)
if (isset($_POST['submit'])){
$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 posts (name,path) VALUES ('$location')");
}
download.php (Written in myproject/download.php)
<?php
include('includes/connect.php');
if (isset($_GET['dow'])) {
$path = $_GET['dow'];
$res = mysqli_query("SELECT * FROM posts WHERE path = '$path'");
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . basename($path) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
flush();
readfile($path); //showing the path to the server where the file is to be download
exit;
}
?>
The linking script to download.php b (written in myproject/viewprofile.php)
<?php
include('includes/connect.php');
$sql = "SELECT * FROM posts";
$res = mysqli_query($con, $sql);
$path = $row['post_path'];
echo "<a href='download.php?dow=$path' class='btn btn-dark btn-theme-colored btn-flat mr-5' style='width:100%; margin-top:5px;'> DOWNLOAD RESUME </a> <br>";
?>

PHP File download script does not work when clicked. But works when URL is accessed on the browser

I got a weird problem. I have a php code that downloads a zip file. The code is called from another php page when a link is clicked. The link passes 4 parameters. the first parameter is the file1, second is file2, 3rd is the id in the database, 4th is the location code. This works perfectly in one of my pages. But when I tried to call this from another page using different parameter, the script fails. Checked the file directory permissions and ownership, everything is okay. And the files I am trying to download are there. When I tried to access the link directly, it downloads the file. Weird... here is the download.php
if(isset($_GET['download_file'])&&isset($_GET['download_file2'])&&isset($_GET['id'])&&isset($_GET['loc'])){
$id=$_GET['id'];
$loc=$_GET['loc'];
switch ($loc) {
case 1:
$path = "../uploads/b2ho/";
break;
case 2:
$path = "../uploads/ho2b/";
break;
default:
exit;
}
$dt_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']);
$dt_file = filter_var($dt_file, FILTER_SANITIZE_URL);
$fd_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file2']);
$fd_file = filter_var($fd_file, FILTER_SANITIZE_URL);
$dt_fullPath = $path.$dt_file;
$fd_fullpath = $path.$fd_file;
$zipname = 'BISAR.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$zip->addFile($dt_fullPath,$dt_file);
$zip->addFile($fd_fullpath,$fd_file);
$zip->close();
if (file_exists($zipname)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($zipname));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname);
exit;
$x=true;
}
if($loc==1){
if($x==true){
$stmt = $conn->prepare("UPDATE rfc_bisar_b2h_upl_log SET bisar_proc_status='Pending',bisar_proc_down_date='$date',bisar_down_by='$userid' where bisar_upl_id=?");
$stmt->bind_param('s',$id);
$stmt->execute();
mysqli_close($conn);
header("Refresh:0");
}
}
if($loc==3){
if($x==true){
$stmt = $conn->prepare("UPDATE rfc_bisar_h2b_upl_log SET bisar_proc_status='Pending',bisar_proc_down_date='$date',bisar_down_by='$userid' where bisar_upl_id=?");
$stmt->bind_param('s',$id);
$stmt->execute();
mysqli_close($conn);
header("Refresh:0");
}
}
if(file_exists($zipname)){
unlink($zipname);
}
}
Try to check broken link parameters. I think that link is invalid (one of query string parameters has invalid name and isset condition does not pass)
Thanks for all the help guys. Resolved this issue by adding a target="_blank" on my anchor tag where I call the download.php . It is really weird why php does not allow me to download the file on the same page but instead requires me to open a new tab.
change $zipname = 'BISAR'.zip'; to $zipname = 'BISAR.zip';
at top you have locations 1 and 2 and at the bottom 1 and 3
use case or else instead of bottom location if case
Notice: Undefined variable: date
Undefined variable: userid
Call to undefined method PDOStatement::bind_param() should be bindParam
changewhere bisar_upl_id=? to where bisar_upl_id=:bisar_upl_id
change $stmt->bindParam('s ',$id) to $stmt->bindParam(':bisar_upl_id',$id)
mysqli_close() expects parameter 1 to be mysqli, object given. Should be $stmt->closeCursor(); butt this is not even required
DB table create statement:
CREATE TABLE `rfc_bisar_b2h_upl_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bisar_proc_status` varchar(45) DEFAULT NULL,
`bisar_proc_down_date` varchar(45) DEFAULT NULL,
`bisar_down_by` varchar(45) DEFAULT NULL,
`bisar_upl_id` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
DB table fill:
INSERT INTO `rfc_bisar_b2h_upl_log` (`id`, `bisar_upl_id`) VALUES ('1', '1');
and here is working php code:
$_GET['download_file'] = 'xxxx.php';
$_GET['download_file2'] = 'xxxx2.php';
$_GET['id'] = 1;
$_GET['loc'] = 1;
$date = 1;
$userid = 1;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_GET['download_file']) && isset($_GET['download_file2']) && isset($_GET['id'])){
$id = $_GET['id'];
$loc = $_GET['loc'];
switch ($loc) {
case 1:
$path = "../uploads/b2ho/";
break;
case 2:
$path = "../uploads/ho2b/";
break;
default:
die('wrong location passed');
}
$dt_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']);
$dt_file = filter_var($dt_file, FILTER_SANITIZE_URL);
$fd_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file2']);
$fd_file = filter_var($fd_file, FILTER_SANITIZE_URL);
$dt_fullPath = $path.$dt_file;
$fd_fullpath = $path.$fd_file;
$zipname = 'BISAR.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$zip->addFile($dt_fullPath,$dt_file);
$zip->addFile($fd_fullpath,$fd_file);
$zip->close();
if (file_exists($zipname)) {
$quoted = sprintf('"%s"', addcslashes(basename($zipname), '"\\'));
$size = filesize($zipname);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
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: ' . $size);
flush();
readfile($zipname);
$x=true;
}
if($loc==1){
if($x==true){
$stmt = $conn->prepare("UPDATE rfc_bisar_b2h_upl_log SET bisar_proc_status='Pending',bisar_proc_down_date='$date',bisar_down_by='$userid' where bisar_upl_id=:bisar_upl_id");
$stmt->bindParam(':bisar_upl_id',$id);
$stmt->execute();
header("Refresh:0");
}
}else{
if($loc==2){
if($x==true){
$stmt = $conn->prepare("UPDATE rfc_bisar_b2h_upl_log SET bisar_proc_status='Pending',bisar_proc_down_date='$date',bisar_down_by='$userid' where bisar_upl_id=:bisar_upl_id");
$stmt->bindParam(':bisar_upl_id',$id);
$stmt->execute();
header("Refresh:0");
}
}
}
if(file_exists($zipname)){
unlink($zipname);
}
}

Download Blob file with php ( mysql )

I have a MySQL database where I have a table call for example "ALL" can contain a blob files.
In the table i have stored the: size of the file, the type, the name and the content.
The problem come when i try download the blob file.
This is my script:
<?php
$connection = mysqli_connect("localhost","user","password",dbname)
or die('Database Connection Failed');
mysqli_set_charset($connection,'utf-8');
$query = "SELECT * " ."FROM ALL WHERE id = '25'";
$result = mysqli_query($connection,$query)
or die('Error, query failed');
list($id, $user_made, $title, $category, $sub_category, $text, $type, $date, $time, $namefile1, $typefile1, $sizefile1, $contentfile1, $namefile2, $typefile2, $sizefile2, $contentfile2, $namefile3, $typefile3, $sizefile3, $contentfile3) = mysqli_fetch_array($result);
echo $id . $namefile1 . $typefile1 . $sizefile1;
header('Content-Length: '.$sizefile1);
header('Content-Type: '.$typefile1);
header('Content-Disposition: attachment; filename="'.$namefile1.'"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
ob_clean();
flush();
// echo $contentfile1;
mysqli_close($connection);
exit;
?>
But the page output only the echo of "$contentfile1" and "$id . $namefile1 . $typefile1 . $sizefile1".
Everyone can help me?
Thanks
Add this code before ob_clean.
$context = stream_context_create();
$file = fopen($filename, 'rb', FALSE, $context);
while(!feof($file))
{
echo stream_get_contents($file, max_bytes_to_read);
}
fclose($file);
You can get more information about stream_get_contents at http://php.net/manual/en/function.stream-get-contents.php

Blank Download Page [PHP]

Recently moved a site over to a new server and now for some reason the download page is no longer downloading the purchased files.
When the download page is reached it is simply blank. I have changed the filename directory to use home/mastetu8 instead of home/mastvoic which was the last directory. Any idea on why the page is blank when trying to download?
Here is the download_process.php file currently running this piece:
<?php ob_start(); ?>
<?php require_once('../Connections/admin.php'); ?>
<?php
$orders_id = $_GET['orderid'];
$id = $_GET['id'];
mysql_select_db($database_admin, $admin);
$query_rsOrdersDetail = "SELECT * FROM orders_detail LEFT JOIN media ON orders_detail.product_id = media.sortorder WHERE orders_detail.orders_id = '$orders_id' AND orders_detail.id = '$id'";
$rsOrdersDetail = mysql_query($query_rsOrdersDetail, $admin) or die(mysql_error());
$row_rsOrdersDetail = mysql_fetch_assoc($rsOrdersDetail);
$totalRows_rsOrdersDetail = mysql_num_rows($rsOrdersDetail);
// CHECK DOWNLOAD COUNT
if ($row_rsOrdersDetail['downloadcount'] <= 3) {
$filename_hires = '/home/mastetu8/public_html'.$row_rsOrdersDetail['filename_hires'];
if (file_exists($filename_hires)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filename_hires));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename_hires));
ob_clean();
flush();
readfile($filename_hires);
// UPDATE DOWNLOAD COUNTER
$downloadcount_new = $row_rsOrdersDetail['downloadcount'] + 1;
mysql_select_db($database_admin, $admin);
mysql_query("UPDATE orders_detail SET downloadcount='$downloadcount_new' WHERE id = '$id' AND orders_id = '$orders_id'", $admin) or die(mysql_error());
}
}
?>

How to download pdf files using php

I want to download pdf files or any other file but my main motive is to download pdf files. Is it possible instead of download we can see the pdf files on browser when user submit a query.
There is my upload code this works fine`
<!DOCTYPE html>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</body>
</html>
<?php
$uploadDir = 'C:\wamp\www\images\passport images';
if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dat";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO upload2 (name, size, type, path ) VALUES ('$fileName', '$fileSize', '$fileType', '$filePath')";
mysqli_query($conn,$query) or die('Error, query failed : ' . mysql_error());
echo "<br>Files uploaded<br>";
}
?>
**Now problem in download code**. Actually I want user submit a query in text box acc. to that text as well as it's image which is scanned So in pdf format shows to him
<?php
if(isset($_GET['id']))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dat";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_GET['id'];
$query = "SELECT name, type, size, path FROM upload2 WHERE id = '1'";
$result = mysqli_query($conn,$query) or die('Error, query failed');
list($name, $type, $size, $filePath) = mysqli_fetch_array($result);
header("Content-Disposition: attachment; filename='".$name."'");
header("Content-length: $size");
header("Content-type: $type");
echo "<a href=" . $uploadDir .($row['userfile']) . ">
{$row['userfile']}</a>";
exit;
}
?>
`
here is my download function that you can use to download any file.
function dawnload_file($path) {
if (file_exists($path) && is_file($path)) {
// file exist
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($path));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
set_time_limit(0);
#readfile($path);//"#" is an error control operator to suppress errors
} else {
// file doesn't exist
die('Error: The file ' . basename($path) . ' does not exist!');
}
}
and here is my function for opening pdf files in the browser online.
function read_pdf_online($path){
if (file_exists($path) && is_file($path)){
// file exist
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($path));
#readfile( $path );
else {
// file doesn't exist
die('File Not Found: ' . basename($path));
}
}
Your headers tell the browser that file data will follow:
header("Content-Disposition: attachment; filename='".$name."'");
[…]
But instead of the file data you just output a link:
echo "{$row['userfile']}";
This will result in error. You have two options to fix it. Either output the link without misleading headers. When user clicks the link server will send the file to the browser. If the mime type is known to the server it will set the headers for you.
Alternatively send file data instead of link after your headers (you can read and output your file data with readfile command):
header("Content-Disposition: attachment; filename='".$name."'");
header("Content-length: $size");
header("Content-type: $type");
readfile($uploadDir . $row['userfile']);

Categories