I'm trying to develop a captcha class for my website everything was doing fine until I tried to embed the image generated with PHP GD inside my subscription form!
Here is the code of my class:
<?php
//captcha.php
header("Content-type: image/png");
class Captcha {
// some attributes bla bla
public function __construct($new_string_length,$new_width_picture,
$new_height_picture,$new_string_color) {
$this->string_length = $new_string_length;
$this->width_picture = $new_width_picture;
$this->height_picture = $new_height_picture;
$this->string_color = $new_string_color;
}
public function getString() {
return $this->string;
}
public function generateRandomString() {
$str = "";
$basket = "abcdefghijklmnopqrstuvwxyz0123456789";
$basket_length = strlen($basket);
srand ((double) microtime() * 1000000);
for($i=0;$i<$this->string_length;$i++) {
$generated_pos = rand(0,$basket_length);
$str_substr = substr($basket,$generated_pos-1,1);
if(!is_numeric($str_substr)) {
// if the character picked up isn't numeric
if(rand(0,1)==1) {
// we randomly upper the character
$str_substr = strtoupper($str_substr);
}
}
$str = $str.$str_substr;
}
$this->string = $str;
}
**public function generatePictureFromString($new_string) {
$root_fonts = '../fonts/';
srand ((double) microtime() * 1000000);
$list_fonts = array('ABODE.ttf','acme.ttf','Alcohole.ttf',
'Anarchistica.ttf','AMERIKAA.ttf');
$image = #imagecreatetruecolor($this->width_picture,$this->height_picture);
$noir = imagecolorallocate($image,0,0,0);
$clr = explode('/',$this->string_color);
$clr = imagecolorallocate($image,$clr[0],$clr[1],$clr[2]);
for($i=0;$i<strlen($new_string);$i++) {
imagettftext($image,rand(($this->height_picture/4.3),($this->height_picture)/4.2),
rand(-45,45),($this->width_picture)/(5*$this->string_length)+($this->width_picture)/($this->string_length)*$i,0.6*($this->height_picture),$clr,
$root_fonts.$list_fonts[rand(0,count($list_fonts)-1)],substr($new_string,$i,1));
}
imagepng($image);
imagedestroy($image);
}**
}
I willingly avoided to show some useless part of the class. The class itself works perfectly when I call the generatePictureFromString(..) method like this:
<?php
//testeur_classe.php
require_once '../classes/captcha.php';
$captcha = new Captcha(5,200,80,"255/255/255");
$captcha->generateRandomString();
$str = $captcha->getString();
$captcha->generatePictureFromString($str);
?>
But when I try to insert the picture generated in my form using:
<img src="<?php echo PATH_ROOT.'classes\testeur_classe.php'; ?>"/>
nothing is displayed!
How am I supposed to do that ?
Thank you!
OK: What do you see if you open classes\testeur_classe.php in the browser?
(p.s. the same question as Ryan Graham asked you in question comment)
OK: I think you must set correct headers before picture output like:
header('Content-type: image/png');
p.s.
This code works, just tried it on my machine. You must have bug on <img src="..." or <base href="" if you have one. Could you show us your html output so we can see what could be the problem?
You need to make sure that the image src is a valid URL to the script. Looking at the backslash in there my guess would be that that is in fact a filesystem path.
Related
I created a php page that print the barcode. Just to view it before i print it on an A4. Still in testing phase. The codes are as below.
<?php
include('include/conn.php');
include('include/Barcode39.php');
$sql="select * from barcode where b_status = 'NOT-PRINTED'";
$result=mysqli_query($conn,$sql);
echo mysqli_num_rows($result);
$i=0;
while($row=mysqli_fetch_assoc($result)){
$acc_no = $row["b_acc_no_code"];
$bc = new Barcode39($row["b_acc_no_code"]);
echo $bc->draw();
$bc->draw($acc_no.$i.".jpg");
echo '<br /><br />';
$i++;
}
?>
Without the while loop, it can be printed, but only one barcode. How to make it generate, for example in the database have 5 values, it will print 5 barcode in the same page. Thanks in advance
Try to use another bar code source. Because It is generate only one bar code per page. Can't able to create multiple bar code per page.
I know this is an older post but comes up in searches so is probably worth replying to.
I have successfully used the Barcode39 to display multiple barcodes. The trick is to get base64 data from the class and then display the barcodes in separate HTML tags.
The quickest way to do this is to add a $base64 parameter to the draw() method:
public function draw($filename = null, $base64 = false) {
Then, near the end of the draw() method, modify to buffer the imagegif() call and return the output in base64:
// check if writing image
if ($filename) {
imagegif($img, $filename);
}
// NEW: Return base 64 for the barcode image
else if ($base64) {
ob_start();
imagegif($img);
$image_data = ob_get_clean();
imagedestroy($img);
return base64_encode($image_data);
}
// display image
else {
header("Content-type: image/gif");
imagegif($img);
}
Finally, to display multiples from the calling procedure, construct the image HTML in the loop and display:
// assuming everything else has been set up, end with this...
$base64 = $barcode->draw('', true); // Note the second param is set for base64
$html = '';
for ($i = 0; $i < $numBarcodes; $i++) {
$html .= '<img src="data:image/gif;base64,'.$base64.'">';
}
die('<html><body>' . $html . '</body></html>');
I hope this helps anyone else facing this challenge.
Hello there i have a php file with the included:
The image shows properly when i access the PHP file, however when I try to show it in the HTML template, it shows as the little img with a crack in it, so basically saying "image not found"
<img src="http://konvictgaming.com/status.php?channel=blindsniper47">
is what i'm using to display it in the HTML template, however it just doesn't seem to want to show, I've tried searching with next to no results for my specific issue, although I'm certain I've probably searched the wrong title
adding code from the OP below
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
echo "<img src='$online' />";
} else {
echo "<img src='$offline' />";
}
The url is not an image, it is a webpage with the following content
<img src='offline.png' alt='Offline' />
Webpages cannot be displayed as images. You will need to edit the page to only transmit the actual image, with the correct http-headers.
You can probably find some help on this by googling for "php dynamic image".
Specify in the HTTP header that it's a PNG (or whatever) image!
(By default they are interpreted as text/html)
in your status.php file, where you output the markup of <img src=... change it to read as follows
$image = file_get_contents("offline.png");
header("Content-Type: image/png");
echo $image;
Which will send an actual image for the request instead of sending markup. markup is not valid src for an img tag.
UPDATE your code modified below.
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
header("Content-Type: image/png");
$image = null;
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
$image = file_get_contents($online);
} else {
$image = file_get_contents($offline);
}
echo $image;
I suppose you change the picture dynmaclly on this page.
Easiest way with least changes will just be using an iframe:
<iframe src="http://konvictgaming.com/status.php?channel=blindsniper47"> </iframe>
I am trying to parse html page of Google play and getting some information about apps. Simple-html-dom works perfect, but if page contains code without spaces, it completely ingnores attributes. For instance, I have html code:
<div class="doc-banner-icon"><img itemprop="image"src="https://lh5.ggpht.com/iRd4LyD13y5hdAkpGRSb0PWwFrfU8qfswGNY2wWYw9z9hcyYfhU9uVbmhJ1uqU7vbfw=w124"/></div>
As you can see, there is no any spaces between image and src, so simple-html-dom ignores src attribute and returns only <img itemprop="image">. If I add space, it works perfectly. To get this attribute I use the following code:
foreach($html->find('div.doc-banner-icon') as $e){
foreach($e->find('img') as $i){
$bannerIcon = $i->src;
}
}
My question is how to change this beautiful library to get full inner text of this div?
I just create function which adds neccessary spaces to content:
function placeNeccessarySpaces($contents){
$quotes = 0; $flag=false;
$newContents = '';
for($i=0; $i<strlen($contents); $i++){
$newContents.=$contents[$i];
if($contents[$i]=='"') $quotes++;
if($quotes%2==0){
if($contents[$i+1]!== ' ' && $flag==true) {
$newContents.=' ';
$flag=false;
}
}
else $flag=true;
}
return $newContents;
}
And then use it after file_get_contents function. So:
$contents = file_get_contents($url, $use_include_path, $context, $offset);
$contents = placeNeccessarySpaces($contents);
Hope it helps to someone else.
Good day!
Could anyone help me, there is a system where users do register via their desktop in a database hosted on the web, we are now developing the web interface of this system, then it has a certain functionality in the system where I have to display the photo user.
I do what normal SELECT in SQL Server, but upon the imagejpeg ($ img); it does not show the whole picture, just a piece of the picture. Could anyone help me? I'm looking for some tutorials on the web and they speak it is because of the size of the field. If the field is of type (image) and the return is in hexadecimal.
Below I tried to do a function with the help of a friend, but she also did not work:
<php
$id = (int)$_GET['id'];
$qryimg = mssql_query(gimage SELECT FROM user WHERE id = {$ id});
$resimg = mssql_fetch_array($qryimg);
$im1 = $resimg['gimage'];
header("Content-type: image/jpg");
$image='';
for($i=2; $i<strlen($im1); $i+=2)
{
$hex = $im1{$i} . $im1{($i + 1)};
$cod = hexdec( $hex );
$image .= chr( $cod );
}
echo $image;
#echo imagejpeg($image);
?>
Why doesn't the following code work? Can't you just echo the image.
<php
$id = (int)$_GET['id'];
$qryimg = mssql_query(gimage SELECT FROM user WHERE id = {$ id});
$resimg = mssql_fetch_array($qryimg);
$im1 = $resimg['gimage'];
header("Content-type: image/jpg");
print $im1;
exit;
What field type is gimage?
I am trying to create & save images from data in an email from the base64 data of an actual image that was in the html body that appears inline such as:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAE==">
But i'm trying to create them sequentially, as there could be more than one image tag in the html body, where the variable $html_part is the html body of the email.
I just need some assistance in coming to a solution on what i'm doing wrong.
$img_tags = preg_match('/<img\s+(.*)>/', $html_part, $num_img_tags);
$num_img_tags = count($num_img_tags);
echo $html_part;
for ($i = 1; $i <= $num_img_tags; $i++) {
preg_match('/<img\s+(.*)\s+src="data:image\/(.*);(.*),(.*)"\s+(.*)>/i', $html_part, $srcMatch);
{
foreach($srcMatch[4] as $im_data)
{
$ufname = "image0".$num_img_tags.".jpg";
echo "<h1>$ufname</h1>";
$im_data = base64_decode($im_data);
$im = imagecreatefromstring($im_data);
if ($im !== false) {
header('Content-Type: image/jpeg');
imagejpeg($im, $ufname);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
}
}
}
Your code is impossible - you cannot do a header() call after you've performed ANY output. You can also not output multiple images in the same 'document'. You also cannot output html (the <h1> stuff), images (header('Content-type:...'), etc... all within the same document.
As well, parsing/processing HTML with regexes is dangerous. A single malformation of the source document and your regexes will happily feast on garbage and produce garbage for you. Do not use regexes on html... every time you do, Alan Turing kills a kitten. Use a DOM parser instead.
Pretty sure you want to use a preg_match_all, not a preg_match
http://php.net/manual/en/function.preg-match-all.php
Also, solution using the above.
<?php
$html_part=<<<END
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=">
END;
preg_match_all('/<img.*?src="data:image\/.*;.*,(.*)".*?>/i', $html_part, $img_tags, PREG_PATTERN_ORDER);
echo $html_part;
$img_num = 0;
foreach($img_tags[1] as $im_data)
{
$ufname = "image0".$img_num.".jpg";
echo "<h1>$ufname</h1>";
$im_data = base64_decode($im_data);
$im = imagecreatefromstring($im_data);
if ($im !== false) {
imagejpeg($im, $ufname);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
$img_num++;
}