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.
Related
So recently I started a project where I need to load some files. In these files I have colors that come via SQL;
The Problem is, I can only include one color in a file where they'll be used. The first file to be included will work properly, but the second one will not.
The weirdest thing is that if I try to add some echo, all included files will echo it, but only the first one in the order of the import will actually work. It's kind of complicate to explain, but some code can help:
Portifolio.php (where I will use the colors)
<?php
error_reporting(E_ALL);
include_once ('php/db.php');
include_once ('php/colors/accent.php');
include_once ('php/colors/primary.php');
$page =
<<<HTML
// Long HTML code here
<nav class="$primarycolor">
// More code
<a class ="$accentcolor">
accent.php:
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 2";
$getcolor = mysqli_query($conn, $sql);
echo "Accent.php included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$accentcolor = $row['color'];
}
}
mysqli_close($conn);
?>
primary.php
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 1";
$getcolor = mysqli_query($conn, $sql);
echo "Primary.php has been included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
}
mysqli_close($conn);
?>
db.php
<?php
$conn = mysqli_connect("localhost","mucap","pswd","webdata");
echo "DB included.";
if (mysqli_connect_errno())
{
echo "Error: " . mysqli_connect_error();
}
?>
In this case:
No errors are gonna be displayed.
$accentcolor will work
$primarycolor will simply pretend it does not exists
All files will echo what they were told to.
I did a lot of research and figured out it could be something with file paths, but I dont think so: Here goes (part of) my file structure:
I cant do [$DOCUMENT_ROOT] as this is not supposed to have a fixed path, long explanation.
What should I do?
Try replacing your statement with this:
if ($getcolor) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
} else{
echo"no results in row";
}
The simple if check is possible because the results of a search return "FALSE" if there's no data in the results.
The else statement is required just for verification purposes.
If you only expect 1 result, you can do "LIMIT 1" as well as eliminate the while statement.
If you don't want the script to run at all, you should use require_once, not include_once
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.
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
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.
Good day i have a problem with my php and can't find a solution
<?php
$pid = $_REQUEST['pid'];
$rs = mysql_query("SELECT image from images where patient_id='$pid'") or die(mysql_error());
while($row = mysql_fetch_assoc($rs));
{
$imagebytes = $row['images'];
header("Content-type: image/jpg");
echo $imagebytes;
}
?>
i call this to another php by
echo '<img src="myimage.php?pid=51">';
but i keep getting an error
"Resource interpretted as image but transfferd as MIME type text/html" i been stuck for a while now
Try this:
<?php
if( headers_sent() ) { die('headers already sent by something else'); }
else { header("Content-type: image/jpg"); }
$pid = intval($_REQUEST['pid']);
$rs = mysql_query("SELECT image from images where patient_id=$pid LIMIT 1") or die(mysql_error());
if($row = mysql_fetch_assoc($rs)) {
echo $row['image'];
}
exit;
It does the most basic of input validation so you don't get SQL injected, checks if something has already sent headers, and removes the inexplicable loop from your code.
Also, the likely reason it was dying is that you have SELECT image FROM images, but the field you were trying to access was $row['images'] which doesn't exist. That was likely printing an error message, causing the default text/html headers to be sent before your try to set the image/jpeg header.
Also, why was $pid in quotes in your query? Is it a string? Please tell me you're not storing integers as strings.