display a <img> from php( problem) - php

I wanna return a link inside to <img>. I dont know what is the problem.
categoria.php
<HTML>....
<img src="categoriaMAIN.php?type=celular">
</HTML>
categoriaMAIN.php
<?php
$varcate= $_GET['type'];
if ($varcate == "celular")
echo "http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg";
?>

categoriaMAIN.php
<?php
switch ($_GET['type'])
{
case 'celular':
header('Location: http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg');
break;
case '...':
header('Location: http://somesite.com/some/img/path/image.jpg');
break;
//...
}
Everyone else seemed to offer the readfile/grab and forward the content method. I thought I'd let the HTTP protocol do the work for us.

Well, the img tag is pointing to text, not an image.
Try:
header("Content-Type: image/jpg"); //tell the browser that this is an image.
$varcate= $_GET['type']; // you know this part
if ($varcate == "celular")
{
// readfile will grab the file and then output its contents without
// procressing it.
readfile("http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg");
}
Bit of a warning: if you don't output an image here, then the browser will probably complain about the image it is trying to load. You should add a default.
EDIT
Kristian made the point that this is a lot of work for the server and he is right. It would be much better if you could manage to make it so that the src of the img tag changed directly. The above, however, will get you where you are asking to go, though it may not be the best option.

The img tag has to point at the actual image - not a webpage containing the URL.
<img src="categoriaMAIN.php?type=celular">
has to get evalulated to
<img src="http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg">
It isn't being right now. How to accomplish this, greatly depends on the rest of your source code and what you actually are trying to accomplish.

This won't work! <img src="" searches for the image file, not its location! Try this:
categoria.php
<?php $varcate='celular'; ?>
<html>....
<img src="<?php include('categoriaMAIN.php'); ?>">
</html>
categoriaMAIN.php
<?php
if ($varcate == "celular")
echo "http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg";
?>

You give the img a PHP page as its src. So the browser is expecting that PHP page to return an image. Instead, you're having that page simply return a URL to the image. You'll have to change that so that you're actually echo ing the image data. I'm a little rusty will all this, but I think you'd do something like the following:
<?php
$varcate = $_GET['type'];
if ($varcate == 'celular') {
header('Content-type: image/jpg');
echo file_get_contents('http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg');
}
?>

If you really want to do it this way, your categoriaMAIN.php would need to look more like:
<?php
$varcate = $_GET['type'];
if ($varcate == "celular") {
header("Content-Type: image/jpeg");
echo file_get_contents("http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg");
}
?>
This will get the actual image data and return it to the browser as an image, which is what the browser needs.

Related

PHP check if file_exists without extension then Ajax a div with appropriate media tag (img or video) based on filepath

First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.

PHP image verification code is not displayed

Here is checks.php given by my teacher:
<?php
session_start();
header("content-type:image/png");
$image_width=70;
$image_height=18;
srand(microtime()*100000);
for($i=0;$i<4;$i++){
$new_number.=dechex(rand(0,15));
}
$_SESSION[check_checks]=$new_number;
$num_image=imagecreate($image_width,$image_height);
imagecolorallocate($num_image,255,255,255);
for($i=0;$i<strlen($_SESSION[check_checks]);$i++){
$font=mt_rand(3,5);
$x=mt_rand(1,8)+$image_width*$i/4;
$y=mt_rand(1,$image_height/4);
$color=imagecolorallocate($num_image,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));
imagestring($num_image,$font,$x,$y,$_SESSION[check_checks][$i],$color);
}
imagepng($num_image);
imagedestroy($num_image);
?>
And I use it by a img tag <img src="checks.php">, but the image doesn't display and no errors show. I remember I have tested it successfully on my experimental class. So I guess if I ignored something. Thanks for helping!

How do I call an iframe or something similar in PHP?

Hey how do I call an iframe or something similar in PHP?
I have found some code but I might be setting up wrong, this is the code that I found, code:
<iframe id="frame" src="load.php?sinput="<?php echo $_GET["sinput"]; ?> > </iframe>
Does anybody know any iframe PHP codes or something similar for PHP?
Some people are saying not to use iframes what is there from PHP?
There is no function to generate an iframe in PHP.
What you're doing is fine, but allow me to make a suggestion:
<?
$input = "";
if(isset($_GET['sinput'])) {
$input = htmlspecialchars($_GET['sinput']);
}
?>
<iframe id="frame" src="load.php?sinput="<?php echo $input; ?>">Your browser does not support iframes</iframe>
EDIT: actually
<?
$url = "load.php";
// Query Building Logic
$querys = array();
if(isset($_GET['sinput'])) {
$queries[] = "sinput=".htmlspecialchars($_GET['sinput']);
}
// Generate full URL
if(count($queries) > 0) {
$url .= "?" . implode("&", $queries);
}
?>
<iframe id="frame" src="<? echo $url; ?>">Your browser does not support iframes</iframe>
I think is better quality overall, but ill let that up to my peers to judge. This is just another suggestion, to generate the full usable URL to use in your HTML in a full logic block, rather than relying on information to be present and usable in the template (because if the element ['sinput'] in the $_GET array is not set for whatever reason, the page will outright snap on you.

to echo a <img > tag and send the code through email+ php

I have a php variable which contain the whole source code of image.What I want is to echo the tag with its attributes src,height & width and send the source code of image through mail (i.e ).
$imagename = abc.jpg;
$concatpath = SITE_URL."/uploads/affiliatesAdv/".$imagename;
$imagesrc = '<img src="'.$concatpath.'" height="200px" width="200px">';
Now when I echo $imagesrc it displays the image. How can I show the source code instead?
Try this,
echo "<pre>";
echo $imagesrc;
echo "</pre>";
You need to use html encoding.
Some thing like this
<img src="abc.jpg"/>
to
<img src="abc.jpg"/>
See the reference.
You can try this site to do it online..

PHP display image from Database(medium blob)

I currently have a database where i can store images in..
But the PHP page i created to display them... doesnt work.
But when i use the link as scr for a < img> it shows a empty image frame.
if i echo the image directly, i get a lot of strange signs
the way i want to display the images is:
< img src="image.php?image="'.$imageID.'/>
the code i use for displaying the image(image.php) is:
<?php session_start();
if(!isset($_GET['image']))
{
header("HTTP/1.0 404 Not Found");
}
else{
$link = mysql_connect('localhost', '45345345435435345', 'wewfsersdfds');
if (!$link) {
echo "error";
die;
}
$db_selected = mysql_select_db(Tha base, $link);
if (!$db_selected) {
echo "error";
die;
}
$nummer=(int)trim(stripslashes($_GET['image']));
$mynr=$nummer;
$sql="SELECT * FROM Foto WHERE fotonr=$mynr";
$result=mysql_query($sql);
if(!$result)
{
echo "error".mysql_error();
header("HTTP/1.0 404 Not Found");
}
else
{
$foto = mysql_fetch_assoc($result);
header("Content-type: ".$foto['type']);
echo $foto['image'];
}
}
?>
I tried a lot already but it wont work :(
i updated the code to the newest version.
Made mistakes with the sql(selected nothing/never do mysql_real_escape_string of a int)
Now it shows a straight line of characters, instead of an image, thats at least a improvement...
Can someone help me?
Thanx for your time!
Honestly, I know it can be tricky. I think it has to do with how your storing it, not how your outputting it. I have one example of storage from a recent project I can show.
$fp = fopen($image_path, 'r');
$image = fread($fp, filesize($image_path));
$image = addslashes($image);
fclose($fp);
// save $image into DB.
Not sure if you do similar with file_get_contents. How I output is similar to how you are doing it, only I use a ORM and a framework.
I suspect that your problem is in your conversion - perhaps between strings and images, or perhaps between the different image formats.
Have you tried saving the image gotten through image.php, and comparing the binary against the known-good image file? Perhaps once you do that, the answer will be apparent (e.g. wrong length, corrupted header, etc.)
You may want to consider a different database record. Most db's support storage of binary blob data, which you could more simply return. This would be simpler (and take less space in your db!) than using the php functions to stringify and imagecreatefromstring.
Also, I believe that you're attempting to use imagegif, imagejpeg, imaging to perform image format conversion for you. This isn't how I understand them to work, based on my reading at: http://php.net/manual/en/function.imagecreatefromstring.php. Try storing and retrieving the same format to tease out whether this is your problem.
Try looking at Content-type. I think it's case sensitive. Try Content-Type.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
$sql = "SELECT * FROM Foto WHERE fotonr=$mynr";
$result = $conn -> query($sql);
while ($row = $result -> fetch_assoc()) {
$img= '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'" width=350px0px height=300px/>';
}
echo $img;

Categories