PHP - download dialog box for given videos url - php

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.

Related

Issue in php with "header"

I am developing an android app that download songs(so type of data is blob) from db.
I have the following download image code example:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select * from images where id = '$id'";
require_once('dbConnect.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
How do I change "header" and "echo"(under header) to download an mp3 audio file ?
You'll want to send the following header for a .mp3 file:
Content-Type: audio/mpeg3
Refer to https://www.sitepoint.com/web-foundations/mime-types-complete-list/ for a good list of MIME types.

download button - save file to disk instead of opening

I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me

File Downloading error from database 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.

PHP export mysql data to excel sheet

I have a filter that the user selects or inputs information, and when they hit submit, a query is generated with this code:
<?php
function displayrecords(){
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$data3 = $_POST['data3'];
$sql_json = "";
$where = "";
if($data1 != ""){
$where = " `data1` = '".mysql_real_escape_string($data1)."'";
}
if($data2 != ""){
if ( $where != "" ) $where .= " AND ";
$where = " `data2` = '".mysql_real_escape_string($data2)."'";
}
if($data3 != ""){
if ( $where != "" ) $where .= " AND ";
$where = " `data3` = '".mysql_real_escape_string($data3)."'";
}
if ($where != "") $sql_json = "SELECT * FROM `database`" . " WHERE " . $where . ";";
$QueryResult = #mysql_query($sql_json) or die (mysql_error());
echo "<table>"
echo "<tr><th>Data1</th>" . "<th>Data2</th>" . "<th>Data3</th></tr>\n";
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row['data1']}</td>";
echo "<td>{$Row['data2']}</td>";
echo "<td>{$Row['data3']}</td></tr>\n";
};
echo "</table>"\n";
}
}
It then spits the data out with this:
<?php displayrecords(); ?>
There are no issues here. The query builder works. The data is rendered to the screen in the table.
What I need to do now is take the data that has been returned to the screen and export it to an excel sheet using another button in the same form as the other submit button. Here is the button that is in the same form:
<input class="btn btn-success btn-small" type="submit" name="get_report" value="Get Report" />
I don't know if I can use another submit button in the same form. I think on have to use a javascript onclick() function. I'm not sure. I just need to export the returned data to excel.
Can anyone help?
A few things to consider:
Don't use $_POST[] within a function. It limits the function to only dealing with POST. Rather, call the function with your POST data.
Have the data retrieved from the database and returned in its own function, something like getTableData(), so that your HTML and your spreadsheet scripts will be able to query the data independently without redundant code.
Also, it is always recommended to use mysqli_ or PDO over mysql_*, as mysql_ is deprecated.
I will not address the database query or the html table display in this answer, as it seems you are quite capable of handling that aspect of the task on your own.
With all that in mind, my method would be the following:
At the end of the HTML table, place a link to a csv file in a subdirectory like so:
<a href='download/some.csv?<?php echo 'data1='.urlencode($_POST['data1'], ENT_QUOTES).'&data2='.urlencode($_POST['data2'], ENT_QUOTES).'&data3='.urlencode($_POST['data3'], ENT_QUOTES).; ?>'>Download CSV</a>
Then, in your download folder, you'll need a .htaccess file with the following contents:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ getFile.php?file=$0 [QSA,L]
Also in your download folder, you'll place a getFile.php file that may look something like this:
<?php
$fileName = (isset($_GET['file'])) ? $_GET['file'] : false;
$data1 = (isset($_GET['data1'])) ? $_GET['data1'] : false;
$data2 = (isset($_GET['data2'])) ? $_GET['data2'] : false;
$data3 = (isset($_GET['data3'])) ? $_GET['data3'] : false;
if($fileName && $data = getTableData($data1, $data2, $data3)) //This would be calling your new function designed specifically to retrieve your data in a multidimensional array
{
header("HTTP/1.0 200 OK");
header("Content-Type: text/csv");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
foreach($data as $row)
{
foreach($row as $columnCount=>$field)
{
echo ($columnCount) ? ','.csvField($field) : csvField($field);
}
echo "\r\n";
}
}
else header("HTTP/1.0 404 Not Found");
function csvField($value, $textDelimiter = '"')
{
if (strstr($value, $textDelimiter) || strstr($value, ",")) $value = $textDelimiter.str_replace($textDelimiter, $textDelimiter.$textDelimiter, $value).$textDelimiter;
return $value;
}
?>
the .htaccess file passes the file name to your getFile.php script in a $_GET parameter. Your .csv file must not actually exist, so that .htaccess can redirect the request to getFile.php.
Make sure that in your getTableData() function the variables passed are properly protected against SQL injection.

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