Dynamic Changes for Webmaster's Code - php

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);
?>

Related

How to detect if dompdf page is changed?

As per documentation, we print the page number on each pdf page but my problem is I want to use the PHP variables inside dom script tag which I can't do that.
<script type="text/php">
if (isset($pdf)) {
$font = $fontMetrics->getFont("Arial", "bold");
$pdf->page_text(555, 745, "{PAGE_NUM}", $font, 7, array(0, 0, 0));
}
</script>
#php
$page = "{PAGE_NUM}";// it prints the string "{PAGE_NUM}" but I want current page number here
#endphp
My problem is that I want to use this {PAGE_NUM} inside my normal #php laravel blade file tag so that I can be able to detect the page change. Is there any way to do this stuff?.

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>";
}
}

Embeding Google calendar with custom calendar colors

I've embeded a google calendar displaying multiple calendars in my website, but I want to have the calendars displaying in colors other than the default options.
The request URL contains a color parameter for each calendar, but doesn't seem to accept non default colors. (The rendered colors also don't seem to be the same as these)
Looking at the source; the colors for each event are defined by inline CSS, and do not appear to have class or ID attributes that could be used to style them via a CSS file.
I've tried using PHP to get the html of the calendar and then use string replace to change the colors (based on this answer) which works, except it doesn't change the colors
The PHP file I'm using:
<?php
$content = file_get_contents('https://www.google.com/calendar/embed?showTitle=0&showPrint=0&showTabs=0&showTz=0&height=750&wkst=2&bgcolor=%23FFFFFF&src=1.keswickscouts.org_5d750s21fh55t45nsh4i49co5g%40group.calendar.google.com&color=%23691426&src=1.keswickscouts.org_k8ai784s6meu1eh71fk21etseg%40group.calendar.google.com&color=%23182C57&src=1.keswickscouts.org_4omjhqh48ud1lkigino18dmid0%40group.calendar.google.com&color=%232F6309&src=06illa48gj7en6896jv32cm93c%40group.calendar.google.com&color=%23125A12&src=1.keswickscouts.org_m6mb8idejtptmfkve9gm6latd8%40group.calendar.google.com&color=%236B3304&src=1.keswickscouts.org_5uaafulf65hrc4b64j3bfa6660%40group.calendar.google.com&color=%235229A3&src=1.keswickscouts.org_qudhcb0ii68u6b5mgs2ase200o%40group.calendar.google.com&color=%23B1365F&ctz=Europe%2FLondon');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />',$content);
$content = str_replace('B5515D','CC9966', $content); //ASU
$content = str_replace('536CA6','099FF', $content); //Beavers
$content = str_replace('7EC225','33CC00', $content); //Cubs
$content = str_replace('125A12','006990', $content); //Eden
$content = str_replace('194D14','999966', $content); //Explorers
$content = str_replace('8C66D9','4D2177', $content); //Group
$content = str_replace('E67399','006666', $content); //Scouts
echo $content;
?>
Any sugestions? Simpler would be better
This is tricky because the Google calendar you link to loads its elements dynamically with javascript so there is nothing to be changed by the potential solution you post.
The HTML-only version of the calendar doesn't have the variety of colours you're looking for, so that won't work either.
Further complications arise because the javascript rebuilds the calendar's body when the user resizes or moves between months. So even if you get the colouring right for the page load, it may not stay the way you want it to.
One solution is to continue to import the calendar to a local page to avoid cross-site restrictions, then get things right on the page load and fight to keep them that way by continuously checking for changes. I'm not sure if there is a more efficient way:
LOCAL CALENDAR PAGE: cal.php
<?php
$content=file_get_contents("https://www.google.com/calendar/embed?showTitle=0&showPrint=0&showTabs=0&showTz=0&height=750&wkst=2&bgcolor=%23FFFFFF&src=1.keswickscouts.org_5d750s21fh55t45nsh4i49co5g%40group.calendar.google.com&color=%23691426&src=1.keswickscouts.org_k8ai784s6meu1eh71fk21etseg%40group.calendar.google.com&color=%23182C57&src=1.keswickscouts.org_4omjhqh48ud1lkigino18dmid0%40group.calendar.google.com&color=%232F6309&src=06illa48gj7en6896jv32cm93c%40group.calendar.google.com&color=%23125A12&src=1.keswickscouts.org_m6mb8idejtptmfkve9gm6latd8%40group.calendar.google.com&color=%236B3304&src=1.keswickscouts.org_5uaafulf65hrc4b64j3bfa6660%40group.calendar.google.com&color=%235229A3&src=1.keswickscouts.org_qudhcb0ii68u6b5mgs2ase200o%40group.calendar.google.com&color=%23B1365F&ctz=Europe%2FLondon");
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />',$content);
print $content;
?>
Calendar Display Page
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language='javascript'>
var oldhtml;
function swapcolors(oldcolor, newcolor){
console.log("Searching for " + oldcolor);
$('iframe#gcal').contents().find('.rb-n').filter(
function() {
console.log(this);
console.log($(this).css('background-color'));
console.log($(this).css('background-color')==oldcolor);
return $(this).css('background-color')==oldcolor;
}
).css({'background-color': newcolor});
}
function recolor(){
swapcolors('rgb(83, 108, 166)', '#099FF'); //Beavers
swapcolors('rgb(126, 194, 37)', '#000000'); //Cubs 33CC00
swapcolors('rgb(181, 81, 93)', '#CC9966'); //ASU
swapcolors('rgb(18, 90, 18)', '#006990'); //Eden
swapcolors('rgb(25, 77, 20)', '#999966'); //Explorers
swapcolors('rgb(140, 102, 217)', '#4D2177'); //Group
swapcolors('rgb(230, 115, 153)', '#006666'); //Scouts
}
function keepcolored(){
if( $('iframe#gcal').contents()!=oldhtml){
recolor();
oldhtml=$('iframe#gcal').contents();
}
}
$(document).ready(
function() {
$('iframe#gcal').load(recolor);
oldhtml=$('iframe#gcal').contents();
window.setInterval(keepcolored, 700);
}
);
</script>
</head>
<body>
<iframe id="gcal" style="width:100%;height:100%" src="cal.php">
</iframe>
</body>
</html>
Note that find('.rb-n') may need to be adjusted and that background colours are converted to RGB values (ala rgb(230, 115, 153)) before they are returned.
I can suggest you using two arrays an only one str_replace :
$search = array('B5515D', '536CA6', '7EC225');
$replace = array('CC9966', '099FF', '33CC00');
$content = str_replace($search, $replace, $content);
A much more complicated advise would be to use the google calendar API.

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.

Pass variable from image to next page

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.

Categories