I am doing an assignment for school where we are to make two php files. First file invokes session, generates a random 5 char string, and saves the string to the session array. The second script generates an image, and takes the string from the first file and incorporates it over the image to make a captcha.
I am having an issue passing the value to the second script. The session variable 'captcha_string' is fully visible in the first script, but is not passed to the second page. I am brand new at this, and frustrated. My understanding is, that as long as I start session, the entire $_SESSION array should be available. When I run the first script, I get a broken image tag, not the captcha i am hoping for. Hope this clears up my problem.
This is what I have done for the first file:
<?php
session_start();
$possible_chars = array_merge(range('A','Z'),range('0','9'));
shuffle($possible_chars);
$string = substr(implode($possible_chars),0,5);
$_SESSION['captcha_string']=$string;
?>
<img src="captcha_generator.php" alt="Weinerdog!" />
and this is the bit from the second file where I try to grab the $string (captcha_string), which is named "captcha_generator.php:
<?php
session_start();
putenv('GDFONTPATH=' . realpath('.'));
header("Content-type: image/png");
//import string for the captcha from $_SESSION
$string = $_SESSION['captcha_string'];
// Build an image resource using an existing image as a starting point.
$backgroundimage = "captcha_wiener.jpg";
$im=imagecreatefromjpeg($backgroundimage);
$colour = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
// Output the string of characters using a true type font.
// Above we set the font path to the current directory, this
// means that arial.ttf font file must be in this directory.
$font = 'arial.ttf';
$angle = rand(-5,5);
imagettftext($im, 120, $angle, 50, 250, $colour, $font, $string);
// Draw some annoying lines across the image.
imagesetthickness($im, 10);
for ($i = 0; $i <3; $i++) {
imageline($im, rand(100,50), rand(150,200), rand(450,550), rand(200,250), $colour);
}
// Output the image as a PNG and the free the used memory.
imagejpeg($im);
imagedestroy($im);
?>
This is, of course, strictly an exercise to make sure we can pass values using session. There is no problem with the rest of the code making the captcha, it has been tested and works.
You're echo-ing some values with a content-type set to image/png, hence either you'll have the error of headers already sent, or, if the text wasn't sent yet (because cached by PHP), you'll have a broken image and you won't be able to see the text.
Don't worry, it has happened to everyone including me :-)
Related
I'm fairly new to php but I'm trying to send an image to a buffer or some sort of temporary place where I can access later. The script I'm calling merges a bunch of images into one, then displays that image (see it in action here - change query parameters to change image). Here's a piece of my code so you have an idea of how that's happening:
$dest = imagecreatefrompng($img0);
$src12 = imagecreatefrompng($img12);
imagecolortransparent($src12, imagecolorat($src12, 0, 0));
//copy and merge
$src12_x = imagesx($src12);
$src12_y = imagesy($src12);
imagecopymerge($dest, $src12, 0, 0, 0, 0, $src12_x, $src12_y, 100);
// Output and free from memory
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);
However, this is an external script so I'd like to be able to pull that image from another page. I'm not sure what the best way to do it is... temporarily store it or pass the image back through. The one constraint is that the image has to exist before the content of the parent page is loaded. How can I make this happen?
If I understand correctly what you mean;
1) You want to pull the image from another website and save it to disk, you can do this;
file_put_contents("img.png", file_get_contents("URL-TO-IMAGE"));
2) You want to just display it? As the URL aboves headers are to display an image, you can put it right into an IMG tag.
<img src="URL-TO-IMAGE">
For starters, I am using the following:
php 5.3
PHPmailer - to send stmp email with google apps
GD to create the iamge
I am able to take a previously existing file, add text to that file and output to a browser.
I am able to send email with an existing embedded image using simple functions within phpmailer
I am NOT able to dynamically modify the first file, have it saved in memory, then embed THAT image in my email.
When creating my image, I am using a very basic sample script:
EDIT
I modified my code to the following: seems to run faster as well as easier to read. An actual file is created however whereas I would prefer a temporary file I could destroy after or simply use binary data. Is there a binary output function similar to imagegif()?
$photo = imagecreatefromgif('sample.gif');
imagealphablending($photo, true);
$fontsize = 20;
$font = '../times.ttf';
$fontcolor = imagecolorallocate($photo, 0, 0, 0);
$angle = 0;
$x = 100;
$y = 100;
$text = 'THIS IS A BLOB OF TEXT YO!';
imagettftext($photo, $fontsize, $angle, $x, $y, $fontcolor, $font, $text);
imagegif($photo, 'test.gif');
unfortunately, this wants to output my file to the browser, then proceed with the remainder of the script and send the email (without embedded image).
I know I am probably missing something simple but has anybody run into this issue before?
Firstly you need to a) save the image to temporary file using second argument of imagegif function; b) use PHP output buffering to capture the result sent to output and clean it from the response (see http://php.net/ob).
Afterwards you need to know how to embed the image as attachment to the email letter or copy it as real file with http address available and point the <img href=""/> to it.
$imageurl = "kaptka.gif";
$im = imagecreatefromgif($imageurl);
$b = imagecolorallocate($im, 0, 0, 0);
imagesetpixel($im, 5, 5, $b);
header('Content-Type: image/gif');
imagegif($im, "asd.gif");
kaptka.gif is normal gif image. I want to draw some pixels anywhere on the image. Asd.gif looks normal, but when i open the file it should show me both like asd.gif, but it shows just "IMAGE" text.
You are calling the function imagegif() with a filename. This will write the image to disc. To display the contents, simply call it without the filename: this will pass the contents to the output stream, which means it will be sent to the client's browser. One way to do both is to call it twice, once to save the file, and once to display it.
When saving the file, you can assign the result to a variable $foo=imagegif($im, 'bar.gif') and then check the result to see if the save was successful. A FALSE means it failed.
You say the image saved to the server is OK, so the reason you are getting an "IMAGE text" in your browser is probably because you are sending a PNG header, but no data (because of the way you called imagefig()).
I'm trying to add a captcha to a site somebody else has made.
I've been following this tutorial and if I make it in a separate file, it works just fine (so it's not an issue with the server setup)
However, when I try to add it to an existing page, it's not working at all. When I load the page in Internet Explorer, the source code is displayed with random characters where the image should have been displayed such as:
‰PNGIHDRé1°8ö[IDATxœÍ]kp×u>»X‹± (4 ›–9¦:‰-C£V™©4–[ÓL•4“Dm~„njR3ª]*qÒÚ‰£ŽãD–&~Ô±ØØŽ$
In Firefox, I get the message: The image “myurl” cannot be displayed, because it contains errors.
I'm assuming this is something to do with the headers, but I'm not really sure.
This is the code I'm using to create the image:
$md5 = md5(microtime() * mktime());
$string = substr($md5,0,5);
$captcha = imagecreatefrompng("./captcha.png");
$black = imagecolorallocate($captcha, 0, 0, 0);
$line = imagecolorallocate($captcha,233,239,239);
imageline($captcha,0,0,39,29,$line);
imageline($captcha,40,0,64,29,$line);
imagestring($captcha, 5, 20, 10, $string, $black);
$_SESSION['key'] = md5($string);
header("Content-type: image/png");
imagepng($captcha);
Any advice would be greatly appreciated. Thanks.
Those random characters are actually the contents of a PNG file.
What's happening is you're dumping the PNG data into your HTML file, rather than linking to it with an <img> tag.
You need to put the code into its own file and embed it like this:
<img src="image.php">
I've got the following function that generates and saves an image based a text parameter. How can I call this in my file? I tried
INCLUDE 'outPrice.php';
to link to the external PHP and called it with this command,
outPrice($text);
To which I got the following response.
Warning: Cannot modify header information - headers already sent
Any help would be appreciated.
function outPrice($textval){
$textcolor = '666666';
$font="bgtbt.ttf";
$size = 20;
$padding= 1;
$bgcolor= "ffffff";
$transparent = 0;
$antialias = 0;
$fontfile = $fontpath.$font;
$box= imageftbbox( $size, 0, $fontfile, $textval, array());
$boxwidth= $box[4];
$boxheight= abs($box[3]) + abs($box[5]);
$width= $boxwidth + ($padding*2) + 1;
$height= $boxheight + ($padding) + 0;
$textx= $padding;
$texty= ($boxheight - abs($box[3])) + $padding;
// create the image
$png= imagecreate($width, $height);
$color = str_replace("#","",$bgcolor);
$red = hexdec(substr($bgcolor,0,2));
$green = hexdec(substr($bgcolor,2,2));
$blue = hexdec(substr($bgcolor,4,2));
$bg = imagecolorallocate($png, $red, $green, $blue);
$color = str_replace("#","",$textcolor);
$red = hexdec(substr($textcolor,0,2));
$green = hexdec(substr($textcolor,2,2));
$blue = hexdec(substr($textcolor,4,2));
$tx = imagecolorallocate($png, $red, $green, $blue);
imagettftext( $png, $size, 0, $textx, $texty, $tx, $fontfile, $textval );
header("content-type: image/jpeg");
imagejpeg($png, "price".$textval.".jpg");
imagedestroy($png);
}
How are you invoking this file? If you are calling it inside of an <img> tag, or from a CSS directive, then do as C. Walsh says and check for whitespace in the file (tip: for binary data, don't include a closing ?> tag in your script) as well as a Byte Order Mark at the beginning of your file (use a HEX editor like PSPad for this).
You may also want to consider, since errors may occur during your image script's execution, wrapping the script contents in ob_start() and ob_end_clean(), where ob_end_clean() is called just before the headers are sent and the image is generated.
If you are invoking it directly from the file in which you wish to embed the image, then use the following HTML scheme:
<img src="data:image/png;base64,DATADATADATA" alt ="" />
Where DATADATADATA is the base64 encoded version of your image.
See:
Data URI Scheme
PHP Manual Entry for base64_encode()
The message means that the page has already sent some data to the browser – if you don’t think this should have happened then it could be some whitespace somewhere in your PHP files. You’ll need to find where it’s coming from and remove it.
If it does turn out to be whitespace then this thread might be helpful.
Using the header() function (third last line) after any content has been sent as response, is not possible, because headers need to be sent first in all http communications. Make sure that your php files don't have whitespace before <?php or after ?>
The error you're getting is caused by output being sent to the browser before you call "header" near the end of the function.
Chances are you've got some white space sitting outside of your first and last <?php ?> tags. When this happens, PHP automagically sends headers to the browser indicating that you're outputting an HTML document. Once this has happened, you can no longer alter the headers, and PHP issues an error.
Track down where the output is coming from; try viewing the source of the document, and making sure you have no leading/trailing whitespace in the files that are included.