File Downloading error from database php - php

I have read every tutorial I can find on this topic, but none of them helped fix my issue. I don't know why, but my code is just giving me an html file whenever I click on the download button, instead of downloading an image file.
HTML:
Download Now
PHP:
<?php
$id= $_GET['id'];
$con= mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno($con))
{
echo "<script type=\"text/javascript\">alert('Failed To connect to MySQL: "+"mysqli_connect_error();"+"');</script>";
}
else
{
$sql = "SELECT * FROM users_files WHERE file_id = ".$id;
$result = mysql_query($sql);
$row_cnt = mysqli_num_rows($result);
echo "<script type=\"text/javascript\">alert('".$row_cnt."');</script>";
if(!$result || !mysql_num_rows($result)){
echo "<script type=\"text/javascript\">alert('Invalid file chosen.');</script>";
//echo '<script language="javascript" type="text/javascript" >';
//echo ' window.location.assign("ViewMyFiles.php");';
//echo '</script>';
mysqli_close($con);
}
$curr_file = mysql_fetch_assoc($result);
$size = $curr_file['file_size'];
$type = $curr_file['file_type'];
$name = $curr_file['file_name'];
$content = $curr_file['file_content'];
header("Content-length: ".$size."");
header("Content-type: ".$type."");
header('Content-Disposition: attachment; filename="'.$name.'"');
readfile($content);
$_SESSION['email']=$nemail;
mysqli_close($con);
}
?>
I named the above PHP file getfile.php and I'm getting on download result as getfile.htm.

Debug!
Comment out the headers and see, what really gets to the client. Then comment them in and check in browser dev console (header + response).
You're also vulnerable to SQL injections.

Related

How to add image php file from MAMP server

I am trying to add image in MAMP server table & fetch it in PHP, and create json. But I am not getting how to add image in table and again it in file. I am new in PHP scripting. Please someone provide me right direction. I have added my PHP code & also MAMP table screenshot.
PHP Code file
<?php
$conn = mysql_connect("localhost:8888","asmita","asmita123") or die(mysql_error());
if($conn)
{
mysql_select_db("EmployeeInfo");
//echo "connected";
//echo $_SERVER['DOCUMENT_ROOT'];
}
else
{
echo "not connected";
mysql_error();
}
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
//echo $_SERVER['http://localhost:8888/images/index.jpg'];
//output need in JSON format for webservice ...
$empname= $result['Name'];
$empadd= $result['Address'];
$emppho= $result['Phone'];
$emppost= $result['Post'];
$empphoto=$result['Photo'];
$jsonArray[]=array("name"=>"$empname","address"=>"$empadd","phone"=>"$emppho","post"=>"$emppost","photo"=>"$empphoto");
}
echo json_encode($jsonArray);
?>
MAMP table data
Here I added image path. Is this correct? Thanks.
HTML Code
<input type="file" name="img_file" id="imageUpload">
PHP Code
$filename = $_FILES['img_file']['name'];
$src = $_FILES['img_file']['tmp_name'];
$folder = "/images/" ;
$move= move_uploaded_file($src,"$folder/".$image);
if($move!=false)
{
$pic = "http://localhost:8888/directoryName/images" .$filename; //This variable insert into Photo column
$query="Insert or Update Query for your table";
$rslt = mysql_query($query);
}
$data=array();
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
$data[] = $result;
}
echo json_encode($data);

PHP - download dialog box for given videos url

I am pretty new in php .so hopefully this all make sense . I am using below script to extract url from database.I want down-loader will popup in browser while reading the url from database....
$q=" Select url from videos where id = '".$_REQUEST['id']."' ";
$result=mysql_query($q);
while( $rows =mysql_fetch_assoc($result) )
{
$url=$rows['url '];
//here i want code to send this url to down-loader of browser..
//and browser should popup the down-loader
$myarray1=array("url "=>$url );
}
I have searched codes on google but i don't understand how to use for this scenario...
First of all, you need to fix the SQL Injection problem.
Use MySQLi instead of MySQL
Here's a code:
$request_id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
if(!empty($request_id)){
$mysqli = new mysqli("localhost", "user", "password", "database_name");
$request_id = $mysqli->real_escape_string($request_id);
$query = "SELECT url FROM videos WHERE id='" . $request_id . "'";
$query_result = $mysqli->query($query);
if(!empty($query_result)){
if($query_result->num_rows > 0){
$my_result_array = array();
while($row = $query_result->fetch_assoc()){
$my_result_array[] = $row['url'];
}
}
}
mysqli_close($mysqli);
}
Concerning the download problem, you need to redirect the user to a PHP page with a specific header
<?php
$file_name = "";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"" . $file_name . "\"");
header("Cache-Control: max-age=0");
?>
You need to add the $file_name and the specific Content-Type.
Here's a list of Content-Types: http://davidwalsh.name/php-header-mime
In order to redirect a user to the download page, you can use the PHP header() function.

blob in data module

I am using the data module in drupal 7 and i created a view which shows my table.
But I have a blob in my table and this is filling my page with content.Is there any way that I can get the blob to display as a link and the file must be downloaded when clicked.
Also is it possible for the data module to access tables in a different database than the default drupal database mentioned in settings.php.I added another database in the settings.php which has the required table but I am not able to adopt tables from there.(They do not show up in the orphaned tables list).Is there a place where I can change so that the data module only sees the new database and not the default database
Fixed the first problem by doing this in the theme.inc
if($vars['fields'][$field] == 'content')
{
$field_output = "<form action=\"download.php\"
method=\"POST\">
<input type=\"submit\" name=\"download\" value=\"Download\">
<input type=\"hidden\" name=\"did\" value=\"$num+1\">
</form>";
}
and download.php needs to have something like this
<?php
if(isset($_POST['id']))
{
$table = 'tablename';
$download_id = $_POST['id'];
$q="SELECT * FROM {$table} where id = $download_id";
$link = mysqli_connect(...);
$res = mysqli_query($link,$q);
if($res)
{
$row = mysqli_fetch_assoc($res);
$id = $row['id'];
$name = $row['name'];
$status = $row['status'];
$content = $row['content'];
header("Content-type: required type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
else{
echo "Cannot download";}
}
?>
I am still unable to fix the second problem.

Serving download after form submit w/ validation

I have created together a pretty simple Download Code redeemer in .php (thanks to help from here) and am having a hard time trying to figure out what the best way to serve a download is if the validation is successful. Basically -
User enters invalid code -> Page is refreshed with error message.
User enters valid code -> Give download 'Save as' -> refresh page.
At the minute I'm using http://www.zubrag.com/scripts/download.php to serve the file but once it has started downloading, my form refreshes the page but only half loads the content?!
This is the form with the PHP script I did.
<div class="dcrForm">
<p>Have a physical copy of this release? Claim your digital download by entering your Download Code below.</p>
<form action="index.php" method="post">
<input type="text" name="code" class="dcrInput" value="">
<input type="submit" name="harrisSubmit" class="dcrSubmit" value="Submit">
</form>
<?php
include("scripts/dcr_config.php");
$code="";
$log="";
if (isset($_POST['harrisSubmit']))
{
$code=$_POST['code'];
$link = mysql_connect($hostname, $dbusername, $dbpassword);
mysql_select_db("$databasename");
$query = "select count from $harris where code='$code'";
if ($q=mysql_query($query))
if ($r=mysql_fetch_array($q)){
if ($r[0]<3)
{
$subquery="update $tbname set count='".($r[0]+1)."' where code='$code'";
mysql_query($subquery);
?><script>window.location.href="download.php?f=test.txt";</script><?php
}
}
$log="<p>Invalid code. Try Again.</p>";
}
echo $log."";
?>
</div>
Does anyone have an ideas on what the best way to serve the download would be? I know that currently anyone who had the file location could download the file but I'm not sure how I could go about protecting i
I am glad you have made it this far!
If you are going to redirect the user to a download script, that script would need to have some sort of token attached to it as to prevent unauthorized downloads, basically re-verifying the code or token given.
In the above script, instead of outputting the javascript to redirect to the download script you could do this:
<?php
include "scripts/dcr_config.php";
$code = "";
$log = "";
if (isset($_POST['harrisSubmit'])) {
$code = trim($_POST['code']);
$link = mysql_connect ( $hostname, $dbusername, $dbpassword );
mysql_select_db ( "$databasename" );
$code = mysql_real_escape_string($code); // very important! protects against exploits
$query = "select count from $harris where code='$code'";
if ($q = mysql_query ( $query )) {
if ($r = mysql_fetch_array ( $q )) {
if ($r [0] < 3) {
$subquery = "update $tbname set count='" . ($r [0] + 1) . "' where code='$code'";
mysql_query ( $subquery );
$file = '/path/to/protecteddownload.txt';
// send file to browser as a download dialog
// no content can be output prior to these header() calls
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
header('Content-Length: ' . filesize($file));
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo file_get_contents($file);
exit; // terminate script
} else {
$log = 'Sorry, this code has already been redeemed.';
}
} else {
$log = 'Invalid download code. Try again.';
}
} else {
// query failed
$log = 'An error occurred validating your code, please try again later.';
}
$log = "<p>Invalid code. Try Again.</p>";
}
?>
<?php if (isset($log) && $log != ''): ?>
<strong class="error"><?php echo $log ?></strong>
<?php endif; ?>
<div class="dcrForm">
<p>Have a physical copy of this release? Claim your digital download by
entering your Download Code below.</p>
<form action="index.php" method="post"><input type="text" name="code"
class="dcrInput" value=""> <input type="submit" name="harrisSubmit"
class="dcrSubmit" value="Submit"></form>
</div>
The download script is probably similar to some of what I have above.
The key thing about this example is that the file you are serving with file_get_contents, is not accessible from the web. You only send it when a valid code is entered.
I have just 1 quick question, how big is this file? Could this be a case that the php timeout is being experienced while reading the file to the browser?
You could play around with the php settings to confirm this (http://php.net/manual/en/function.set-time-limit.php).
Just my 2 cents

How do I set a header() and echo an image using CodeIgniter?

I've written a method to set a header() to the appropriate file type of an upload stored in a database and then I would like to echo() the file.
The method is as follows inside a controller:
function view_upload( $id = 0 ) {
$id = $this->db->escape( $id );
$query = $this->db->query( "SELECT file_type FROM media WHERE id = $id" )->row();
$query2 = $this->db->query( "SELECT file FROM media WHERE id = $id" )->row();
header("Content-type: ".$query->file_type);
//die( "moo" );
echo( $query2->file );
}
Strangely as soon as I set the header() the rest of the method seems to be ignored, for example, if I uncomment the die() statement it doesn't die and it doesn't echo the image. If I remove the header() call I see the raw upload blob presented to the screen..
Is this something to do with CodeIgniter or have I made a PHP mistake?
EDIT:
I've changed the function and put it in a separate file outside of CodeIgniter but if I browse to it and pass in an $id it still doesn't display the image...
<?php
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
//connect to the db
$link = mysql_connect("localhost", "user", "pass") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("database") or die(mysql_error());
$id = $_GET['id'];
// get the file from the db
$sql = "SELECT file FROM media WHERE id=$id";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// get the file_type from the db
$sql = "SELECT file_type FROM media WHERE id=$id";
// the result of the query
$result2 = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
//ob_clean();
//die( mysql_result($result, 0) );
//header('Content-type:'.mysql_result($result2, 0));
header('Content-type: image/png');
//ob_clean();
echo mysql_result($result, 0);
// close the db link
mysql_close($link);
}
else {
echo 'Please use a real id number';
}
?>
die() on the two $result produces what I would expect but it's not displaying the page in the browser. Again if I add ob_clean() it says:
ob_clean() [<a href='ref.outcontrol'>ref.outcontrol</a>]: failed to delete buffer. No buffer to delete.
I've copied the code from here: http://www.phpriot.com/articles/images-in-mysql/8 if that helps at all..
It turns out that the image in the database was corrupt, and hence not displaying, because I had added addslashes() to the file contents (not really sure why, seem to remember reading it was useful in combating XSS vulnerabilities).
Removing that meant I had non-corrupt images stored and then they displayed okay.
First You need to start ob_start() just before on_clean() then you need to write like header().
Here is the follow.
ob_start();
ob_clean();
header ("Content-type: image/png");
?>
Try this let me know is this working or not hopefully it will help you.

Categories