PHP image does not show when using <img> - php

I have found a lot of posts that describe the same problem, but everything I tried failed.
For a profile page I am making people can upload 4 pictures. When no picture is available I want to show a default picture. My complete code is like this now:
$id = $_GET['ID'];
$link = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("xxx");
$sql = "SELECT * FROM profielen WHERE ID = $id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
if ($row['Foto4'] == NULL){
//echo '<img src="/img/noImage.jpg" />';
echo $row['Foto5'];
}
else {
echo $row['Foto4'];
}
In this form the code works, so I know that the if-statement is correct.
When I try to uncomment the commented line, it shows a broken link as the image.
I have tried with double quotes and then escape the double quotes within the img tag. I have also tried to call it as a variable and without a / before the img-path. And also just tried to say echo "No image", but it seems that if I do anything else than echo $row[x] it just does not work. When I try to display the image in HTML it works fine, so the name of the file is correct.
I am running out of ideas, so maybe someone can help?

The problem with your code is that you're sending HTML to embed an image back, when really, you should be sending image data back. You can solve this by redirecting the user to the "noImage.jpg", in this way the user will get an image back from the request and all will be fine :)
Code for this could look like this:
if ($row['Foto4'] == NULL){
header('Location: /image/noImage.jpg');
} else {
echo $row['Foto4'];
}

If you use the content type image/jpeg, the browser expects the raw binary data of an image. Instead, you give it HTML-code.
You can instead use the Location-header, which tells the browser to open another address.
header("Location: /img/noImage.jpg");
Remember that you cannot output any other data or write any other headers if you use this method.

Related

header("Content-Type: image/png"); php

when implement this code i have no image
<?php
include('confing.php');
echo '<img src="getImage.php?id=2" >';
?>
file => getImage
<html >
<body>
<?php
include('confing.php');
$id = $_GET['id'];
$sql="SELECT * FROM images WHERE id=$id ";
$result=mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
  // Set the content type header - in this case image/png
header("Content-Type: image/png");
echo $row['content'] ;
?>
body>
html>
body
html
body>
html>
body
html
body>
html>
body
html
The errors you are getting:
Undefined index ID: It would appear that you are calling it without passing the ID argument. Obviously you should check that. But also, you should add some error checking to your code to ensure that it doesn't crash if the ID is not passed, or if the ID is invalid.
Undefined variable $connection: Your database connection variable is not set. Maybe you config.inc include doesn't actually set the connection? Or maybe you've got the variable name wrong? You need to check your config.inc to find out why this is happening. In any case, this leads directly onto the next error...
mysqli_query expects connection parameter: Because the $connection variable is not set, your DB query can't be run. Some error checking here would be helpful, even if you do sort out the connection variable, as there may be other reasons the connection may fail.
mysqli_fetch_assoc expects result parameter: This occurs because the result variable is not set due to the query not being run. You should add some error checking for this as well, since there may be other reasons why a query fails to run.
The errors didn't even get as far as hitting the header() function call, which would also fail because the program has already output some content. You should remove the <html><body> tags from the top of the program, as they are not necessary for outputting an image; in fact, they would cause the image to be invalid.
Your line:
echo '<img src="getImage.php?id=2">';
will output this into your html page:
<img src="getImage.php?id=2">
Second, it will not load, execute and insert the result of getImage.php.
Here's a solution:
First page:
<?php
include('getImage.php');
$id = $_GET['id'];
$img = getImage($id);
echo "<img src='$img' >";
?>
getImage.php:
<?php
include('confing.php');
function getImage($id){
$sql="SELECT * FROM images WHERE id=$id ";
$result=mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
return $row['content'] ;
}
?>

Data wasn't able to retrieve from the previous page (PHP and MYSQL)

I researched here in stackoverflow trying to find whether someone is also encountering the same problem. I know it's kind of easy and even I really don't know what's the error because there's no problem with my query.
On the previous page, here's my code to retrieve the ID Number so I'll be able to select the data with that ID number:
<?php echo $row['place_name'];?>
I tried first to print the value of the place id and it works fine.
But when it was being called to the Package page, the data I want to show weren't displayed.
I look at the URL and it shows this after the package.php
place_id=
I don't know why it is blank, please check my code if there's missing or just wrong.
In my package page, here's the PHP code:
<?php
include("common/connect.php");
$place_id = $_GET['place_id'];
$result = mysql_query("SELECT * FROM package_items WHERE place_id = '$place_id'");
$row1 = mysql_fetch_array(mysql_query("SELECT place_name FROM packages WHERE place_id = '$place_id'"));
if($result === FALSE) {
die(mysql_error()); // for better error handling
}
?>
In HTML Code:
<h1><?php echo $row1['place_name'];?></h1>
<?php while($row=mysql_fetch_array($result)) {?>
<?php echo $row['item_title'];?>
<br>
Back
<?php } ?>
Please check my codes. Thanks.
You are not printing it.
Change
<?php $row['place_id'];?> // It will output nothing as no echo or print.
To
<?php echo $row['place_id'];?>
Rest of the code looks fine.
Three suggestions:
1)
$place_id = $_GET['place_id'];
Change to
$place_id = ! empty($_GET['place_id']) ? $_GET['place_id'] : ''; // To avoid any warning.
2) Don't feed variable from $_GET or $_POST to any SQL.
3) Don't use mysql_ functions as they are deprecated and will be remove in future versions of PHP.

PHP data retrieval from database and display

How do I Limit some information displayed from the database and add a link eg "More" to enable read all information in a drop down using PHP. such as what is on facebook (Read more...). I am dealing with a lot of content and I dont want it all displayed at once.
Here is part of the code
echo "<p>".$row['Firstname']." ".$row['Lastname']."</p>";
echo "<p>".$row["Course"]." | ".$row["RegID"]."</p>";
echo "<p>".$row["Email"]."</p>";
echo "<p>"."Tel:".$row["Telephone"]."</p>";
echo "<p>".$row["info"]."</p>";
The code is running well only that I want to limit the information
echo "<p>".$row["info"]."</p>";
so that not all is displayed
Thanks
Use Jquery-ui click on "view source" and you'll see it's very simple really, just set the row that you want as the header (what's clicked to show the rest) and store the rest in a div below.
Split info into two strings, one intro, and the rest. Display only the intro to begin with. Insert a link that displays the rest when clicked.
$intro = substr($row['info'], 0, 200);
$rest = substr($row['info'], 200);
echo sprintf(
<<<HTML
<p>
<span class="intro">%s</span><span class="rest" class="display: none">%s</span>
Show more
</p>
HTML
, htmlentities($intro)
, htmlentities($rest)
);
displayRest is a Javascript-function that, given a link, finds the previous span with class rest, shows it and removes the link. I leave it as an exercise to implement this in a way that fits your project. You can go with native Javascript, or use a library such as jQuery, YUI, MooTools, Prototype etc.
if(isset($_POST['more']))
{
$query="select col1,col2,col3, ... ,colN from tableName ";
}
else
{
$query="select col1,col2,col3 from tableName ";
}
//HTML
<form method="post">
<input type="submit" name="more" value="More" />
</form>
//PHP
$records=mysql_query($query);
while($row=mysql_fetch_assoc($records))
{
//Display
}
The limit must be fixed on the SQL request.
// If you want to transmit limitation with a GET PARAMETER.
// You can also $_POST ur data.
$limitation = $_GET['limit'];
//..... And in your SQL REQUEST
$sql = "SELECT * FROM your_table LIMIT 0 , $limitation";
//And in the link....
echo 'Show only 10 Results'
?>
You can optimize that and add security precaution to prevent errors when $limitation receive empty or non numeric parameters.
<?php if(isset($_GET['limit']) && !empty($_GET['limit']) && !preg_match(EXPRESSION, $_GET['limit'])){
//YOU CAN DO THE LIMITATION WHITOUT SQL ERRORS
}
else{
//ERROR DIRECTIVE
}
?>

permission denied while posting the form which contains textarea with html content

Ok, so here's my problem (which I've googled and no help):
I have a form which has the textarea element, and in it I want to write something like:
<table><tr><td>123</td></tr></table>
and click submit and i want it to be saved in database.
Now, my code is working if I enter nonHTML characters, but if I enter as above I get:
Forbidden
You don't have permission to access /xxx/sample_posteddata.php on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
My guess is that somehow my hosting has some security enbaled to disallow this?
I've tried to insert the exact text from the php admin interface and that works fine :?
EDIT: full source code of the file podaciEdit.php:
<?
require_once("_dal/CredentialsManager.php");
require_once("_dal/ProizvodRepository.php");
$repos = new ProizvodRepository();
if ( isset( $_POST["spremi"] ) ){
$sifra = $_POST["sifra"];
$naziv = $_POST["naziv"];
$slika = $_POST["slika"];
$podaci_full = htmlspecialchars($_POST["podaci_full"]);
$podaci_min = $_POST["podaci_min"];
$kategorija = $_POST["kategorija"];
$kategorija_naziv = $_POST["kategorija_naziv"];
if ($repos->updateProizvod ($sifra, $naziv, $slika, $podaci_full, $podaci_min, $kategorija, $kategorija_naziv))
echo "Podaci uspješno spremljeni!";
else{
echo "Greška prilikom spremanja podataka!";
}
echo '<br/>Kliknite ovdje za povratak.';
}
else if ( isset( $_GET["sifra"] ) ){
$sifra = $_GET["sifra"];
$proizvod = $repos->GetProizvod($sifra);
if ($proizvod){
$sifra = $proizvod["sifra"];
$naziv = $proizvod["naziv"];
$slika = $proizvod["slika"];
$podaci_full = $proizvod["podaci_full"];
$podaci_min = $proizvod["podaci_min"];
$kategorija = $proizvod["kategorija"];
$kategorija_naziv = $proizvod["kategorija_naziv"];
//$data = htmlentities($podaci_full, ENT_QUOTES, "UTF-8");
echo <<<qq
<form id="proizvodEdit" method="POST" action="proizvodEdit.php">
Podaci - tablica: (mozes resizeati po potrebi!)<br/>
<textarea class="podaci_full" id="podaci_full" name="podaci_full">{$podaci_full}</textarea>
<input type="submit" value="Spremi sve" name="spremi"/>
</form>
qq;
}
else
echo '<h2 class="title-page">Proizvod koji tražite ne postoji.</h2>';
}
else{
echo '<h2 class="title-page">Proizvod koji tražite ne postoji.</h2>';
}
If you are the owner of the website you can use htmlspecialchars() then save the output to the database. If you want to read it back and convert to html use htmlspecialchars_decode()
for a more accurate answer, you should post the code you use to save the data to the database.
I guess you got a 403 initially. This is an file permissions related issue, an apache error message, not a php one. Try to go directly to www.yourdomain.com//xxx/sample_posteddata.php and see if you can access the file. Maybe even try a GET param.
www.yourdomain.com//xxx/sample_posteddata.php?sifra=xxx
You should be able to access it. If not try
chmod +x /home/domain/public_html
404 is the error code for NOT FOUND. It means that your form is not pointing correctly to your php file or one of the includes fails. Check your paths.
Since your HTML is containing the keyword "table", my best bet would be that it is probably an issue related to mod_security or some other security tool which filters SQL keywords, in order to help prevent SQL injections. Try adding the below to your .htaccess:
SecFilterEngine Off
If it works this way, it's probably about mod_security. Note that you may not be able to disable it from your .htaccess file though.
Actually, the thing that helped resolve the issue was function stripslashes.
$podaci_full = stripslashes($_POST["podaci_full"]);

Image pathname from mysql php doesn't display the image

So after I store a pathname of an image file in mysql php, I am having difficulty retrieving that image to display. In other words, when I do an "inspect element" the "src" value is set. However, the image doesnt display and all that is left is a square box on the page. I tried using a default profile picture that is already set for the user, just to check if its a php assigning value problem. But its not. I also checked the file contents physically and all the files are uploaded fine. The only problem is getting it to display.
Here's how I do it.
Php for checking file upload
error_reporting(E_ALL);
if($_SERVER["REQUEST_METHOD"]=="POST"&&isset($_POST["savePersonalInfo"]))
{
if(isset($_FILES["ppFile"]))
{
$name=$_FILES["ppFile"]["name"];
$tempName=$_FILES["ppFile"]["tmp_name"];
$size=$_FILES["ppFile"]["size"];
$type=$_FILES["ppFile"]["type"];
if(($type=="image/jpg"||$type=="image/jpeg"||$type=="image/pjpeg")&&( ($size>0&&$size<=4000000000))
{
$dir="C:/xampp/htdocs/hcUsers/".$_SESSION['pin']."/profilePictures";
$realPath=$dir."/".$name;
if(is_dir($dir))
{
move_uploaded_file($tempName,$realPath);
$_SESSION["ppPath"]=$realPath;
$fileQuery="UPDATE `current users` SET `ppPath`='$realPath' WHERE `id`='".$_SESSION['pin']."' " ;
checkConnect(mysql_query($fileQuery),"query of $fileQuery");
}
else
{
mkdir($dir,0777,true);
move_uploaded_file($tempName, $realPath);
$_SESSION["ppPath"]=$realPath;
$fileQuery="UPDATE `current users` SET `ppPath`='$realPath' WHERE `id`='".$_SESSION['pin']."' " ;
checkConnect(mysql_query($fileQuery),"query of $fileQuery");
}
}
else
{
print "Error".$_FILES["ppFile"]["error"];
}
}
?>
Php for retrieving the image pathname and displaying the image
<?php
session_start();
connectDatabase();
$query="SELECT * FROM `current users` WHERE `email`='".$_SESSION['email']."' AND ` `password`='".$_SESSION['password']."' ";
$result=mysql_query($query);
checkConnect($result,"query of $query");
$row=mysql_fetch_assoc($result);
$_SESSION["pin"]=$row["id"];
$imgPath="http://www.metalmusicarchives.com/images/covers/avariel-no-end-in-sight(demo)-20110719103608.jpg";
if($row["ppPath"]!="")
{
$imgPath=$row["ppPath"];
$_SESSION["ppPath"]=$imgPath;
}
?>
<p><img src="<?php echo $imgPath ?>" alt="" type="image/jpeg" class="profilePic" >
In the end the 'src' value is set but the image won't display.
Please help.
This is a part of your code:
$dir="C:/xampp/htdocs/hcUsers/".$_SESSION['pin']."/profilePictures";
$realPath=$dir."/".$name;
if(is_dir($dir))
{
move_uploaded_file($tempName,$realPath);
$_SESSION["ppPath"]=$realPath;
$fileQuery="UPDATE `current users` SET `ppPath`='$realPath' WHERE `id`='".$_SESSION['pin']."' " ;
This way, when retreiving ppPath from the database and trying to display it in a browser, the src of the image will point to C:/xampp/etc. That won't work, since your visitors don't have access to that directory. Neither do you, from a browser's perspective. Change it to a relative URL.
Furthermore I see a lot of duplicate code and you're abusing session variables, but that's offtopic.

Categories