Pass variable from image to next page - php

Hey I have dynamic image begin created with imagecreate(), and I have random values being produced, and I want to pass that random number, to a variable, and use that variable inside the page where Im using the image source.
The image is on random.php, and Im using <img src="random.php" /> on page index.php if that matters, and I want to pass from random.php (the image), to index.php. I already tried sessions and cookies but when I refresh, its always 1 step behind what the image is producing...
Im using a for loop to echo random numbers, I need to pass those numbers to a variable. Basicly how do I get numbers outside an image, in real time, not 1 step back.

What about using a temporary session variable?
On your first page,
<?php
session_start();
$_SESSION['mykey'] = 'myrandomval';
session_write_close(); // Helpful if you're using a header redirect
?>
and on the second page
<?php
session_start();
$value = $_SESSION['mykey'];
?>

The problem you are having is that index.php is requested, then the browser realizes that random.php is needed, so- yes, random.php will be a step AFTER index.php...
If you switch your "random creation" logic around, (have index create the key stored in a session, which can then be read from random.php) it may solve your problem.

Instead of passing variables from the page to the image, you could set the random number generator seed to the same value on both scripts. Here is a full sample:
<?php
function randomcolor()
{
srand( $_SERVER['REQUEST_TIME'] );
$colors = array('red', 'green', 'blue', 'black', 'orange');
return $colors[ array_rand($colors) ];
}
$color = randomcolor();
if(isset( $_GET['image'] ))
{
header('Content-type: image/png');
$im = imagecreate(75, 50);
imagecolorallocate($im, 0xee, 0xee, 0xee);
$black = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 2, 10, 10, $color, $black);
imagepng($im);
exit;
}
?>
<p>color: <?php echo $color; ?></p>
<img src="test5.php?image=1" />
This is two separate requests being seeded with the REQUEST_TIME, which means array_rand will return the same value both times.

Related

Unable to retrieve a PHP value from another PHP file using the include command

So, yeah, I am a newbie and currently I am spending my whole morning trying to find a way to get a value from a php file into another one.
More specifically, I am trying to create a simple captcha system using mt_rand command. So I put, for example, the following code in the first php file:
form.php
<?php
$captcha = mt_rand(10000,99999);?>
and including the form.php in the other .php file which is designed to be the image in my form page. In other words, the $captcha variable needs to be used in the form.php file so that the code in the image is the same as the one it is going to be checked in form.php using if statements:
image.php (image.php is an IMAGE using imagepng() and other commands)
<?php
include('form.php');?>
So, the whole story is about: the $captcha include a random number ranging from 10000-99999 and after the form submission it is checked in the form.php but it is also included (must be* inlcuded) in the image.php to generate the image with the code inside it.
Even though, using the include() command didnt work for me.
I am willing to get a solution in PHP but any others are welcome too, of course.
NOTE: Wanna point that I tried to just generate a random number in the image.php to see if it can be generated and it works ok but it can't retrieve the value when I use the include command.
PS: I guess I am typing too much shit also (too big text, etc), that's because Im really confused right now.
So, If anyone has time to check the two PHP files throughly, here they are:
form.php
<?php
$captcha = mt_rand(10000,99999);
if(isset($_POST['submit'])){
if($_POST['response']=$captcha){
echo "Captcha verified successfully.";
}else{
echo "Wrong Captcha Input!!!</br>";
}
}
?>
<!DOCTYPE html>
<head>
<title>Report Cheater</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="" method="post"></textarea><br>
Captcha(*): <img src="image.php">
<br><input type="text" name="response"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
image.php
<?php
//CAPTCHA verification
header ('Content-Type: image/png');
//Image to be converted into captcha
$im = imagecreatetruecolor(180, 40);
//Captch Background
$im2 = 'capback.png';
//Creates an instance of the captcha background to be added to the captcha
$rsc = imagecreatefrompng($im2);
// Copy and merge
imagecopymerge($im, $rsc, 0, 0, 0, 0, 180, 40, 100);
//Colors to be used
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
//The captcha random number taken directly from report.php
include("form.php"); //works with $captcha = mt_rand(10000,99999); but not with the include("form.php");
// Font
$font = 'arial.ttf';
$x1 = mt_rand(29,41);
$y1 = mt_rand(42,58);
$x2 = $x1 + 1;
$y2 = $y1 + 1;
// Add some shadow to the text
imagettftext($im, 20, 0, $y2, $x2, $grey, $font, $captcha);
// Add the text
imagettftext($im, 20, 0, $y1, $x1, $black, $font, $captcha);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
imagedestroy($rsc);
?>
You compare two variables with ==
So change
if($_POST['response']=$captcha){
to
if($_POST['response']==$captcha){
First of all you must understand how capatcha system work
when you generate a hash or random numbers to use in capatcha
you must save it in the user session then use it in image and match it with user input.
In your code you generate two different numbers one in the image and then generated another one when you checked user input and this is logical error.
in image.php :
generate random number and you must start your file with session_start();
$capatcha=random(0,1000);
$_SESSION["capatcha"]=$capatcha;
then use $_SESSION["capatcha"] to generate image and then use it to verify user input
if(isset($_POST['submit'])){
if($_POST['response']==$_SESSION["capatcha"]){
echo "Captcha verified successfully.";
}else{
echo "Wrong Captcha Input!!!</br>";
}
}

Rotated image wont display in php

So i am trying to create a compass to show wind direction.
Function rotate($angle) {
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $angle, 0);
return $compass;
}
That will be displayed using some html that i am echoing. The variable angle is being passed from a database. The html on the php script looks like this:
<img src='".rotate($row['wind_dir'])."'/>
The image never displays, and clearly the browser does not know where it is.
When i view the html in my browser, the above line shows as
<img src="Resource id #4"/>
and when i click on it, it navigates to a 404.
What am i doing wrong? Have i forgotten a line in the image rotation function?
EDIT:
Having tried some of the responses below, i get an image, but it only shows as a black box!
EDIT2:
Well after much fiddling, it turns out all that was needed was to the third value of imagerotate() to -1 as follows:
$original = imagecreatefrompng("img/goog.png");
$compass = imagerotate($original, $angle, -1);
imagealphablending($compass, true);
imagesavealpha($compass, true);
header('Content-Type: image/png');
imagepng($compass);
imagedestroy($compass);
I posted a comment about using CSS or JS rotation instead but since then I've had a better idea.
The compass is always going to be Arrow.png in one of 360 positions.
Use a batch process in Photoshop or PHP to create 360 versions. One for each degree. Then you can just call Arrow_120.png for example for 120 degrees. You remove the issue with your existing code of creating images on the fly while avoiding compatibility issues with CSS / JS.
You have to execute the function and send header: try like below, say our php file name is rotate.php :
rotate.php
function rotate($angle) {
$original = imagecreatefrompng("test.png");
$compass = imagerotate($original, $angle, 0);
header('Content-Type: image/png');
imagepng($compass);
imagedestroy($compass);
}
if(isset($_GET['angle'])){
rotate($_GET['angle']);
}
THen in your html you can call the web resource i.e you php file as:
<img src="url_to_rotate.php?angle=90" />
Also remember to sanitize the GET input before executing it.
The displayed image should be a image file. To achieve this you should use imagejpeg();
So basically you should have 2 php files:
1: Creates the image file using your code and imagejpeg();
<?php
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $_GET['angle'], 0);
header('Content-Type: image/jpeg');
imagejpeg($compass);
?>
2: The php file that displays the image.
<img src='image.php?angle=".$row['wind_dir']."'/>
if you want just one file you could do the following:
<?php
$original = imagecreatefrompng("img/Arrow.png");
$compass = imagerotate($original, $_GET['angle'], 0);
ob_start();
imagepng($compass);
$stringdata = ob_get_contents();
ob_end_clean();
$imageData = base64_encode($stringdata);
$src = 'data: image/png;base64,'.$imageData;
echo '<img src="',$src,'">';
?>

Dynamic Changes for Webmaster's Code

First of all apologies, if the question title misleads you. Here is what I want to achieve.
I want webmasters to come to my site, copy a piece of code(basically it displays an image on the webmasters's website) and then paste it on their website for promotion of my website. I am good till this and have succeeded in doing so. Now, I want the image to have a dynamic rank that will be fetched from my website. So, when webmasters paste the code on their website, the rank displayed on the image(as a text) changes based on my Database setting.
Can anyone let me know how this can be achieved..
You can do an iframe as aniruddha suggested or you can also use javascript. See Twitter, Facebook, and Google Calendar on how their various widgets work.
I've provided some very simplified implementations for you to see how they work. But it's probably better to look at the examples mentioned above. Ignore the security issues in my examples here. Just wanted to show how it works on the simplest level.
iFrame Example
Client Code For Iframe Example:
<html>
<head>
</head>
<body>
<h1>User Website Title</h1>
<p>Some random user text</p>
<p>Iframe version here</p>
<!--This is the code that the client would paste in to their website -->
<iframe src="http:/your.domain.com/server_iframe_test.php?user=TestUser" height="30" width="500" scrolling="no" frameBorder="0"></iframe>
<!-- End client iframe code to paste-->
</body>
</html>
On your server, you can have page to use as the source for the iFrame. Here I'm calling mine server_iframe_test.php:
<?php
//Generating a random number to show that page will update on reload
$randomNumber = rand(1, 999);
//In the src of the iframe we will send a get parameter called user to determine which user we should look up
$data = array('user' => $_GET['user'], 'rank' => $randomNumber, 'image' => 'http://url/to/some/image.png');
?>
<!-- This is the output that will be generated in the iframe -->
<div class="widget_wrapper"><?php echo $data['user'] ?>: <?php echo $data['rank'] ?> and <? echo $data['image'] ?></div>
Javascript Example
For the javascript example it is possible to make ajax calls across domains using JSONP. You can read up on how it works here: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
Here is the client side for the javascript version:
<html>
<head>
<!-- I'm cheating here by including jquery in the head. My test script needs it-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<h1>User Website Title</h1>
<!--Code that user pastes into their page-->
<!--First get the script from your domain-->
<script src="http://your.domain.com/test_widget.js"></script>
<!--This code is also pasted by the client. We use this to set user name and then render the html. Also I added an id to the script tag here to know where to append the html. This is a more of a shortcut.-->
<script id="test_widget_script">
var widget = new testWidget('TestUser');
widget.render();
</script>
<!-- Widget will render html here -->
<!--End Code to Paste-->
<p>Some random user text</p>
</body>
</html>
Here is the server side js script called test_widget.js:
var testWidget = function(user){
var _user = user;
this.render = function() {
//We make a JSONP call here to our php script which generates the data for the user. Note the &callback?. We need to add this to make it a JSONP call.
$.getJSON('http://your.domain.com/test_js.php?user=' + _user + '&callback=?', function(data){
//Append html result after the js tag with the following id
$("#test_widget_script").after('<div class="widget_wrapper">' + _user + ': ' + data.rank + ' and ' + data.image + '</div>');
});
}
}
Here is the php file called test_js.php that will handle the request:
<?php
$randomNumber = rand(1, 999);
$data = array('user' => $_GET['user'], 'rank' => $randomNumber, 'image' => 'http://url/to/some/image.png');
//We need to make the content type javascript
header("Content-type: text/javascript");
?>
<?php //Here we take the name of the callback passed as a GET parameter and use it as a function to pass in our json data. We don't call the function in php, but when the text gets returned, jQuery knows how to handle the response. ?>
<?php echo $_GET['callback'] ?>(<?php echo json_encode($data); ?>);
I think a iframe is required with src of your server side script page which will fetch the rendered code with rank over the image from your server. The purpose of the iframe will be to render the whole html.
Modify the code from here http://php.net/manual/en/function.imagettftext.php
to make an image with your rank in it. Here is tested example based on that code, note you need GD and truetype for this. All you need do is send then a link and use a get variable to set which user so you can get the right ranking back from your DB. I won't code that part.
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw (your ranking)
$text = '21'; // <== change this as you need over time
// Replace path by your own font path
$font = 'arial.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

creating image with php problem

my index.php file i have somethingk like :
<?php
session_start();
$_SESSION[some_value] = 1;
?>
<img src="image.php" alt="some image"/>
<?php
$_SESSION[some_value] = 0;
?>
my image.php file i have look like ( basic code ) :
<?php
session_start();
header("Content-Type: image/png");
$im = #imagecreate(400, 20)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,"session value is : {$_SESSION[some_value]}", $text_color);
imagepng($im);
imagedestroy($im);
?>
Now, when i load my index.php page in browser the value in image is session value is : 0, how to make it to show 1 and then code in index.php to set it to 0 ( adding in image.php code to set value to 0 is not what i'm looking for )
You run into problems because in your code both scripts do not share the memory of the session even if both are using the $_SESSION array.
That's by the nature of how and when PHP stores the values of the $_SESSION array.
Instead you need a shared store like a database or shared memory to exchange values between your scripts.
The problem is that the browser loads image.php after index.php is loaded.
You can do something like this:
<img src="image.php?some_value=<?php echo $_SESSION[some_value]; ?>" alt="some image"/>
But it depends on your particular purpose.

PHP header, Content type: image not allowing text

I have a variable ($output) that is set to a string.
To mekt this string an image I'm using the PHP: GD Library.
In particular the imagestring() function, which I'm using with a very slight modification:
<?php
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, $output, $textcolor); #here is my string $output
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
This is working as expected: It turns $output into an image.
So, my problem is (or my best guess at least):
header('Content-type: image/png');
Which, doesn't allow me to output any html after that.
So I read this question, which asks if you can use two headers, which you can't, but the accepted answer recommends, something like this: <img src="my_img.php" />
This of course would be fine, except I don't know how would this solve my issues since, since even if I knew the source to this image (which I don't - so, that would be my first question, what's the path to the generated image*) I't would change the fact that the header is there and is not letting me output text.
So, I how would you approach this issue?
Thanks in advance!!
*I guess that would solve my issues since I could do this on an external file, and the just call the image (but maybe not since I would have to do an include and this would include the header too) as you see I'm a bit confused. Sorry :)
UPDATE:
So I'm seeing my question was confusing so I will add some more code to see if this clarifies my problem a little bit more:
<?php
$x = mt_rand(1,5);
$y = mt_rand(1,5);
function add($x, $y) { return $x + $y; }
function subtract($x, $y) { return $x - $y; }
function multiply($x, $y) { return $x * $y; }
$operators = array(
'add',
'subtract',
'multiply'
);
$rdno = $operators[array_rand($operators)];
$result = call_user_func_array($rdno, array($x, $y));
session_start();
$_SESSION['res'] = $result;
if ($rdno == "add") {
$whato = "+";
}elseif ($rdno == "subtract") {
$whato = "-";
} else {
$whato = "*";
}
$output = $x . $whato . $y . " = ";
?>
<form name="input" action="check.php" method="post">
<input type="text" name="result" />
<input type="submit" value="Check" />
</form>
I want $output to be a image so this got me trying to use the PHP:GD script above, but I can't make put in the same file because of the header.
You need to make a separate PHP script which serves the image, then make an <img> tag that points to this script.
You can send information to the script using the querystring in the image URL.
Morbo says: "Windmills do not work that way! Goodnight!"
Which means that you need to bone up on how this all works. This issue points to you having a basic misunderstanding of your tools. HTML can't contain images, it contains links to images. So your script needs to be included from another page via an image tag. (or CSS)
However, all this is a good thing. It means that this script can have dynamic elements that produce a new image each time it is called. Or that it could password-protect your images so only logged-in users can see it.
There are a host of ways to use this. And once you realize the image is like a page to php, this opens new routes. Php can output anything. Word docs, excel, pdf, css, even JS. all of which can be used to do cool things.
Just think of the image as a separate page. You'll get it. It'll just click into place in your mind. One of those big 'aha' moments.
First, the path.
From the manual :
imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )
It means that if you don't give a second argument (it is the case here), you don't have the path to a file but the data of the file / image ressource. The php file will be understand as a png file by the browser thanks to the header you give.
Second :
In your page (ie index.php), you could add this like that
<img src="myimg.php?output=[...]" />
and in your php script myimg.php you have it like this :
<?php
$output = $_GET['output'] // getting your text
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, $output, $textcolor); #here is my string $output
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
2 separates files.
You can send the image inline with echo '<img src="data:image/png;base64,'. base64_encode(imagepng($im)) .'" /> instead of <img src="my_img.php">.
Do not set a content-type header! Your output is text/html what you don't have to announce as it's the default in most server setups.
HTTP doesn't work that way. When your are serving image/png data, it as if you are serving a png file from the site, not an html file with an image in it. What are you trying to accomplish?
my_img.php is not source to your image. It is a source to the script generating that image, or reading it from file and outputting directly into browser. Obviously the approach with img src would be the best, because you'll hide all "boring" implementation of displaying image string behind browser's mechanisms.

Categories