Images from database wont show, headers already sent [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
$sql="SELECT * FROM `blob` ";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)) {
$image=$row ['image'];
header("content-type: image/jpg");
echo '<img src="path/'.$image.'" width="360" height="150">';
}
This is the code i'm using to display the image uploaded to my database... however, i get the error message that the headers have already been sent... i have no idea what i'm doing wrong!
i can see on my website where my images are meant to be but no actual image!

In general:
When you get this message it seems that there is an output done before. It can even be a simple "whitespace" character like [:space:].
But:
In addition to that you seem to get some things wrong. You do create HTML (!) but you send a header-message that tells the browser that it get's binary data of an image.
So when you really have binary data in your database you have to output binary data and not any html "thingy". I really really recommend you to read a good book about how a server works and what header(..) actually does.
Please also have a look here:
php:Store image into Mysql blob, Good or bad?
http://pujanpiya.com.np/?q=node/25
PS: I did not get into any more detail about your question neither provide a solution because I do not think this would help you rather than solving this issue of misunderstanding temporarily.

Your code is totally wrong; storing images inside a MySQL database is a bad idea and you're using your image data as a path to a nonexistent image; if you still want to stick with the idea of having images in your database, here's example code that would work :
while ($row = mysql_fetch_array($query)) {
echo '<img src="data:image/jpeg;base64,'.base64_encode($row["image"]).'" />';
}
This encodes the image into base64 and then uses that as a data URI inside an img; no headers needed.
Also, mysql is deprecated; use mysqli or PDO instead.

The problem is that you're doing it in a while loop, which will be executed multiple times:
while($row=mysql_fetch_array($query)) {
$image=$row ['image'];
header("content-type: image/jpg"); // Headers are sent here
echo '<img src="path/'.$image.'" width="360" height="150">'; // Content here
}
When mixing headers like this, what you would normally want to do is put the header before any content. However in your case, this wouldn't make sense either because you are sending "content-type: image/jpg". If you are echoing an image to the browser using HTML, the content-type should be text/html (which is sent by PHP by default). So just leave that line out completely. If you are trying to send the actual binary contents of an image, then you wouldn't use an HTML tag, just send the Content-Type header and then echo the contents for one single image.

Related

PHP don't print MySQL image [duplicate]

This question already has answers here:
PHP display image BLOB from MySQL [duplicate]
(2 answers)
Closed 6 years ago.
Good Afternoon, y'all!!
I have a database with a table containing a row with 4 columns called "ID", "login", "pass" and "image"(BLOB). I have a system with users authentication and etc, and I want to implement the image registered by the user to be shown in the topbar. Everything's working pretty well so far, the only problem is that the database image is printing like this:
ÿØÿàJFIF``ÿÛC  %# , #&')*)-0-(0%()(ÿÛC (((((((((((((((((((((((((((((((((((((((((((((((((((
ÿÀ€€"ÿÄ ÿĵ}!1AQa"q2‘¡#B±ÁRÑð$3br‚ %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’
“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ ÿĵw!1AQaq"2B‘¡±Á #3R
ðbrÑ $4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹º
Detail: When I open the image selected to the database in NOTEPAD, it's the same shown above.
IMAGE.PHP
include "dbconnection.php";
$defaultpath = "img/avatar.png";
$sql = "SELECT * FROM `bg_users`";
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
if (!isset($_SESSION)) {
$_SESSION['UserImage'] = $result['image'];
print $_SESSION['UserImage'];
}
else {
echo "src='img/avatar.png'";
}
?>
Again, the interaction between PHP and MySQL is completly fine. The problem is that PHP is not printing the file as image. I can't make header("Content-type: image/png"); because the page i want to include image.php already have a header parameter.
Could't someone help me on this? I would be very pleased
Thank You!
First of all i wouldn't save images as blob in your database, easier to just store them in a folder and save the the path to it in the database.
If you want to do it your way, do the following:
echo '<img src="data:image/png;base64,'.base64_encode( $result['image'] ).'"/>';
This is a really bad practice though and might slow down the page load quite a bit. I'd suggest you re-evaluate you database structure and store the images directly and just save the path in the database

php headers instant download videos [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Force-downloading, from php file
(2 answers)
Closed 9 years ago.
I am trying to make a php script when you load on to that page it downloads a video. However since i do not know anything about headers it seems i can't figure it out so please explain why it works and how header works. I am trying to make the browser download video files.Can someone also explaain the headers and what they do please.
Here is my failing code:
<?php
//Outputing video name
$file_name = $_POST['FileToD'];
//outputting video extension e.g video/mp4
$file_ext= $_POST['FileExt'];
//where the file is kept
$file_path = 'mysever.myadress.com/media/movies/' . $file_name;
header('Content-Type:'.$file_ext);
header('Content-Length:' . filesize($file_path));
header('Content-Description: attachment; filename='.$file_name);
readfile($file_path);
?>
If you want to output a video, then don't start by outputting HTML and then switch to video data as part of the same file. (You can't set response headers after you've started outputting data anyway). Remove everything before <?php and after ?>
$file_url should be the path, on the server's file system, to the file you want to make available. It shouldn't be a URL (unless you want a really inefficient approach or need to proxy from a different server), and if it is a URL then it needs to start with the scheme (e.g. http://).
The content-type needs to be the actual content type of the video (e.g. video/mp4), not a file extension (and it doesn't make sense for it to be provided by the user).
You also need to sanitise the user data. At present (if the errors described above were fixed) then anybody could request any file that exists on the server.

Display image along with labels in php

I am retrieving an array of book objects with attributes like title,isbn and image. When I wish to display only labels using for loop it is displaying all entries. But when I try to display image, it only displays one. Also when I try to display both title and image, it says can
Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/BookStore/BooksResult.php:14) in /Applications/XAMPP/xamppfiles/htdocs/BookStore/BooksResult.php on line 15.
Below is the code.
foreach($booksArr as &$book)
{
$content = $book->Image;
$title=$book->s_Title;
echo $title;
header('Content-type: image/jpg');
{
echo $content;
}
}
The "Cannot modify header information..." problem is here:
header('Content-type: image/jpg');
Your PHP script is outputting HTML. You cannot change the content type of the output mid-stream. Instead, you should output an <img> tag that points to the image location.
UPDATE BASED ON COMMENT DATA:
If you need to serve your images as blobs from the database, you will need to create a separate script to fetch the images. First modify this one to reference the new script by creating an <img> tag with a src attribute that contains the path to your image-fetching script and the image ID:
<img src="/path/to/your/new/script.php?id=<?php echo $row_id; ?>" />
Substitute $row_id with the field data that uniquely identifies a book in your database.
Next, create the new image fetching script. It will contain three elements:
A line to get the id from the GET request:
$id = $_GET['id'];
An SQL statement to fetch the image blob based on the ID. (Remember to sanitize your input!)
A header() statement like the one you used in your original script
After the header() line, just output the blob, and your image will be displayed.
Try adding
ob_start()
At the beggining of the file
EDIT: Also, only modify the header information once, just call the header function once at the beggining of the file, after ob_start()
Headers may only be sent before any output is sent. You are echoing the title and then try to set the headers.
You are trying to send all the photos in one request. HTML doesn't work like that. You need to do something like this:
foreach($booksArr as &$book) {
$title=$book->s_Title;
echo $title;
echo '<img src="book_image.php?id=' . $book->id . '" alt="' . $title . '"/>';
}
and then handle the books in a separate request on book_image.php, where you would print out the appropriate header and content, something like this:
$id = $_GET['id'];
// get the book by id from db
header('Content-type: image/jpg');
echo $book->Image;
If you really want to understand this warning, and you want to work more with PHP in the future then you should start to learn how the HTTP protocol works. Its fun, and you will see much more clearly after:)
(this is just a general advice, not the exact answer to your question)

PHP Image content type problem

I have a specific problem, and cant get over it.
For my latest project I need a simple PHP script that display an image according to its ID sent through URL. Here's the code:
header("Content-type: image/jpeg");
$img = $_GET["img"];
echo file_get_contents("http://www.somesite.hr/images/$img");
The problem is that the image doesn't show although the browser recognizes it (i can see it in the page title), instead I get the image URL printed out.
It doesn't work neither on a server with remote access allowed nor with one without.
Also, nothing is printed or echoed before the header.
I wonder if it is a content type error, or something else.
Thanks in advance.
Possibly the image doesn't fit into memory. Or your PHP installation doesn't have permissions to make external HTTP calls. Anyway, I suggest you never use echo file_get_contents(), use readfile instead.
Also you should never use raw strings from $_GET or $_POST for file operations. Always strip null-bytes, slashes and double dots from user-provided filenames, or better yet, allow only alphanumeric characters.
I was doing something like this recently, but found this a slow method (I was doing 15+ on a page). This is slow because first your server has to download the image, and then send it to the client. This means for every image it is downloaded twice.
I came up with an alternative - redirection. This allowed the client machines to directly access the other site while hiding the real url in the HTML source code.
$r - is processed above the script, and validated to make sure it is ok.
$webFile = 'http://www.somesite.com/'.$r['type'].'/'.$r['productid'].'.jpg';
header('Location: '.$webFile);
exit();
Granted if someone put my image url in the address bar, it would redirect and the user would see the real url, but it made my page faster and I wasn't too worried about that.
You'll want to ensure that your script is not outputting any white-space. Check before and after the opening/closing PHP tags.
If that checks out, you'll want to ensure that allow_url_fopen is set to On in php.ini
try embedding your php file that retrieves the image as <img> in your html
getImage.php
header("Content-type: image/jpeg");
$img = $_GET["img"];
echo file_get_contents("http://www.somesite.hr/images/$img");
in your html file
<img src="getImage.php?img=IMAGEID">
Probably you get some errors and the image is not displayed. Try to turn off the errors like this first:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'Off');
Check that the variable exists in the query string, and use a regular expression to make sure that it doesn't contain anything other than alphanumeric characters or a period. Then use readfile() to stream the output to the browser.
// make sure the variable exists
if (isset($_GET['image'])) {
$image = $_GET['image'];
// make sure it contains only letters, numbers, the underscore, and a period
if (preg_match('/^[\w.]+$/', $image)) {
$file = "http://www.example.com/images/$image";
// send the correct header
header('Content-type: image/jpeg');
// stream the output
readfile($file);
}
}

How is $_GET set in this image-resize code?

I am working with a script for resizing images. I seem to be getting an error:
Error: no image was specified
Probably because of this code in the script(image.php):
if (!isset($_GET['image']))
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: no image was specified';
exit();
}
Here is what I'm doing(profile.php):
$your_image = $row['Image'];
$path_to_image = $row['PortraitPath'];
$width = 100;
$height = 100;
echo "<img src=\'/image.php/{$your_image}?width={$width}&height={$height}&cropratio=1:1&image={$path_to_img}\' alt=\'Alt text goes here.\' />";
Therefore, I am reading $your_image and $path_to_image from a MySQL table, and then putting it in the img source. As mentioned above, obviously, image is not set, that is why I am getting that first error. What I don't get is, how will the image actually even be set with my img src code? Aren't I simply displaying the actual image? Then how will image even be set if a picture is simply being displayed? Thank you.
If you want to source a php file instead an image, you need to tell your php file that the output will be an image.
You can do this using the php header() function, like this:
header('Content-type: image/jpeg');
Here is some reference: php header function
About the address you are point to, isn't a bit weird? You have a slash right after the .php, which suggest that you are trying to access some folder... Did you tested this url to see if a real image are being outputted on the screen?
Hope this can help you =)
The URl for the image contains ?foo=bar&this=that&image=path. These variables will be passed to the image.php script in the $_GET array.
As a word of warning, in your profile.php's code I saw this fragment:
image={$path_to_img}
Depending on how you deal with the value of $_GET['image'] this may result in a RFI vulnerability. The user could forge a GET request to image.php with their own "image" path.
A couple things that I noticed, I'm not sure how much of the code you modified before posting it here...
1a) Don't escape the single quotes if you are using double quotes to encompass it.
OR
1b) Change the escaped single quotes to escaped double quotes.
2) In the URL you are using $path_to_img but the variable you have defined is $path_to_image. Make them consistent.

Categories