Returning white page? - php

I have built somekinda image-api-key for my website but it doesn't seem to work. I get an blank page, returning nothing! Whats wrong? Greetings.
if(isset($_GET['key']) && !empty($_GET['key'])){
$query = " SELECT
*
FROM
table
WHERE
apikey = '". mysql_real_escape_string($_GET['key']) ."'
";
$mysqlquery = mysql_query($query);
if($mysqlquery){
if(mysql_num_rows($mysqlquery) > 0){
if(isset($_GET['type']) && isset($_GET['image'])){
if($_GET['type'] == "gif"){
if($_GET['image'] == "1"){
header('Content-type: image/gif');
echo file_get_contents('path/to/image/1.gif');
}
elseif($_GET['image'] == "2"){
header('Content-type: image/gif');
echo file_get_contents('path/to/image/2.gif');
}
elseif($_GET['image'] == "3"){
header('Content-type: image/gif');
echo file_get_contents('path/to/image/3.gif');
}
elseif($_GET['image'] == "4"){
header('Content-type: image/gif');
echo file_get_contents('path/to/image/4.gif');
}
elseif($_GET['image'] == "5"){
header('Content-type: image/gif');
echo file_get_contents('path/to/image/5.gif');
}
else
{
die('Could not load image');
}
}
else
{
die('Could not load image');
}
}
else
{
die('Could not load image');
}
}
else
{
die('Api key was not correct');
}
}
else
{
die('Mysql query failed');
}
}
else
{
die('No api key was set');
}

You need to check your error logs/ensure you have logging turned on as it sounds very much like PHP is throwing an error. (N.B.: If this is a production environment, be sure to turn logging back off afterwards.)
At a guess if could be one of the paths that's incorrect or you've already output some data prior to attempting to set a header, but the error logs should make it pretty obvious what the problem is.

If PHP is throwing certain kinds of errors such as syntax errors it will output an error message and terminate without any other output. However, if display_errors is turned off in php.ini then not even the error message will be output and you'll just get a blank screen.
Alternatively, if you're trying to send a file that doesn't exist after you've sent the image/gif header then this could also result in a blank page. Look at the headers that got sent back. If you got an image/gif content type header back then the code is reaching a point where it's trying to send an image. The fact you don't actually get an image would suggest that there's no image file to send.

Related

style die() error message

How do I make the die() message to echo in a certain place in the HTML section of the same page?
$files = array();
$upload = $_FILES['upload']['tmp_name'];
foreach($upload as $uploaded){
if(!empty($uploaded)) {
if(isset($uploaded)){
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime= finfo_file($finfo, $uploaded);
switch($mime) {
case 'application/pdf':
break;
default:
die('pdf file only.');
break;
}
}
}
}
die will immediately stop execution and send anything in buffers to the browser.
Personally, I like to do something like this:
function halt($str="") {
if( $str) echo "<div class=\"server_notice\">".$str."</div>";
require("template/foot.php");
exit;
}
How about don't just use die, do something to insert html there and then die.
Alternatively, you have register_shutdown_function (Documentation: http://php.net/manual/es/function.register-shutdown-function.php) which will allow you to do things right after the script is ended with die;
There is no way to do that. die() or exit() will stop executing of your script.
Thouh, you can make some error reporting system.
$lastError = null
Then do what you want and set this error.
Then you can check it in some place:
if ($lastError == 2){
echo "The file is no in PDF format" ;
} //and so on.
Also you could create some constants like:
define("ERROR_WRONG_FORMAT", 2); //Make the error clear.
You'll need to echo out div tags and then position them using CSS.
die('<div id="error">pdf file only.</div>');
Then add the following text to your CSS:
#error{position:absolute;top:10;left:10;}
You'll need to change the top and left values depending on where you wnat them to be.
If you don't know what CSS is, I suggest you watch TheNewBoston's tutorials on YouTube!

PHP script header type image destroys session

I'm trying to write a small PHP script that uses a session to store a folder structure of images. Every time the side gets called it reads the next image out of session list and display it as content type of the side. When I call my script I sometimes get not the next image out of list but the next but one. When I write an output file to register every page request, I see that there were more than just one request. But if I look to my fire bug time line I don't see more than one request and there is no javascript running. If I show the image as part of an normal HTML page everything works gread. So what is going on here.
Would be nice if somebody can help me with this...
<?php
include("readDir.class.php");
define("IMAGE_SOURCE_PATH","img");
session_start();
//Inititalize new session context
try
{
if(!isset($_SESSION['id']))
initSessionConext();
}
catch (Exception $e)
{
exit();
}
$fotos = $_SESSION['fotos'];
//Handle wrapp around
try
{
if($_SESSION['id'] >= count($fotos))
initSessionConext();
}
catch (Exception $e)
{
exit();
}
$foto = $fotos[$_SESSION['id']];
if(strcasecmp($_SERVER['REQUEST_METHOD'],"get") == 0)
$_SESSION['id'] += 1;
//Error in session context return nothing
if(empty($foto))
exit(); //
switch(readDir::extension($foto))
{
case "png":
header('Content-Type: image/png');
break;
case "jpg": //Fall through to jpeg case
case "jpeg":
header('Content-Type: image/jpeg');
break;
}
$fp = fopen("test.txt","a");
fwrite($fp,$foto."\r\n");
fclose($fp);
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
readfile(IMAGE_SOURCE_PATH."/".$foto);
//echo $foto."<br>";
//echo '<img src="'.IMAGE_SOURCE_PATH."/".$foto.'" />';
//--------------- F U N C T I O N S -------------------------------
function initSessionConext()
{
$_SESSION['id'] = 0;
$_SESSION['fotos'] = getNewData(IMAGE_SOURCE_PATH);
}
function getNewData($path)
{
$extensions = array("jpg","png","jpeg"); //get data out of file system
$fotos = array();
$source = new readDir($path);
if(!$source->check())
throw new Exception('Could not find source for given path');
$fotos = $source -> readFilesWithextension($extensions);
if(!sort($fotos,SORT_STRING))
throw new Exception('Could not sort foto list in natural order');
return $fotos;
}
?>
So if I understand correctly, you're returning each image, one per time the image is loaded?
It seems likely to me that the browser is requesting the image twice: Once as a HEAD request, and the second time to get the content. This is commonly used to find out things like the Content-Length header before blindly downloading.
I would suggest making sure that strcasecmp($_SERVER['REQUEST_METHOD'],"get") == 0 before modifying the session.
Didn't solve the request problem at least. Use now time difference to differ between requests. Not nice but works out of the box...

Need help in accessing image from database

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.

content type not correctly set by php script

I have the following php code that runs after validation:
try {
if (isset($filtered) && !isset($errors)){
$p['email']=$filtered['email'];
# check if email exists
if ($user->userExists($p)){
$msg['error'] = false;
$msg['msg'] = 'This email address is already in our database';
} else {
# insert user data into database
$user->saveUser($filtered);
$msg['error'] = false;
$msg['msg'] = 'Successful! Go back to our homepage.';
}
} else {
# echo errors back
foreach ($errors as $value) {
$msg['error'] = true;
$msg['msg'] = $value;
}
}
I prepare the json data as follows:
# header encode
header('Content-type: application/json');
# return json encoded data
echo $encoded = json_encode($msg);
A direct array like this one below works fine.
header('Content-type: application/json');
$msg['error'] = true;
$msg['msg'] = 'Please enter an email address.';
echo $encoded = json_encode($msg);
I can't seem to figure out what the problem with my php logic could be. Kindly help.
The only difference I can see there is that in the version that works, you call header() before anything else.
Try moving
header('Content-type: application/json');
above the try/catch. I have a suspicion that the reason you are getting this problem is because you are implicitly accessing the array $msg before you have created it, which throws an E_NOTICE (or it might be E_STRICT, I can't remember) and causes something to be written to the output buffer, so the headers are sent, and you can no longer manipulate them - although if this were the case I would expect it to break your JSON as well...
Regardless, try the above and report back.

Handle error when getimagesize can't find a file

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}

Categories