I'm using the following code to create a captcha on my site, but when I try to read the value back from the session, it is always the previous captcha value.
<?php
session_start();
$captchaStr = md5(microtime() * mktime());
$captchaStr = substr($captchaStr,0,5);
$_SESSION["captcha"] = $captchaStr;
$captcha = imagecreatefrompng("../images/captcha.png");
$black = imagecolorallocate($captcha, 154, 32, 242);
$line = imagecolorallocate($captcha, 233, 239, 239);
// Draw lines
imageline($captcha, 0, 0, 39, 29, $line);
imageline($captcha, 40, 0, 64, 29, $line);
// Add captcha text
imagestring($captcha, 5, 20, 10, $_SESSION["captcha"], $black);
header("Content-type: image/png");
imagepng($captcha);
?>
Does anyone have any ideas why this is and how to fix it?
Cheers
I'm guessing you're trying to read back the captcha value from the page that contains the captcha value, something like this:
<?php session_start(); ?>
<img src="/lib/captcha.php" />
<?php echo "Captcha is: ", $_SESSION['captcha'] ?>
This would never work. PHP locks the session file by default, so your captcha script can not run until the above container page completes execution. As well, since the captcha is being fetched as a seperate call, the user's browser has to initiate a call back to the server to fetch the image. This will take on the order of seconds to complete, while the container page will be done within microseconds.
In other words, the captcha generator script will very likely NEVER start running until after the container script has completed, which means the container script will never see the new captcha string in the session file.
Related
First check this site: check this first plz
hi , Im from mexico and Im auto learning html, css, js and php, for personal purposes.
IM trying to add that code to my testing page, the example is Example 3 — Random Fact Generator (form). When you click the random generaton button, it makes random text appear the problem is..WHERE IS IT COMMING FROM? and xml? php server?...I dont know..I checked in ALL the code and nothing :(, I can add random text with other methods like JS with a case and a random.math but I prefer like that page, any sugestions? thx a lotssss
It comes from : http://juicystudio.com/experiments/ajax/form/fact.php
Go see http://juicystudio.com/experiments/ajax/form/script.js
So it comes from a PHP file. The PHP could be reading a XML file, a CSV file, a database, etc.
Let me know if you still have questions.
Edit:
If you don't want to overwrite the last fact you have to change this from script.js:
if (objCurrent)
objCurrent.parentNode.replaceChild(objReplacement, objCurrent);
else
{
var objContent = document.getElementById('content');
objContent.appendChild(objReplacement);
}
To
var objContent = document.getElementById('content');
objContent.appendChild(objReplacement);
Edit 2:
CSV file (test.csv)
1,test1
2,test2
3,test3
4,test4
5,test5
Here is the PHP adapt from the site you have supplied
<?php
$handle = fopen("test.csv", "r");
$array= array();
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
array_push($array,$data);
}
if(count($array) > 0){
$id = rand(0, count($array) -1);
echo $array[$id][1];
}
?>
It gets the text from http://juicystudio.com/experiments/ajax/form/fact.php
In this section, it opens a connection to that page:
if (objXMLRequest)
{
objXMLRequest.onreadystatechange = processResult;
objXMLRequest.open('GET', 'fact.php', true);
objXMLRequest.send(null);
}
When the connection's state change event fires, it calls the method processResult. That method checks that the readystate is 4 (completed) and the status is 200 (OK) and updates the text on the page.
You don't need a database or to read files to make that example page. The easiest way would be to create an array of facts and output one at random, like this:
<?php
$facts = array("fact 1", "fact 2", "fact 3", "fact 4", "fact 5", "fact 6");
$random_number = rand(0, count($facts)-1);
echo $facts[$random_number];
?>
I have an Android app that checks a URL which I control. However, I can't seem to set/pull the cookies onto/from the device. This works great on my desktop but not the phone itself.
The server-side code is
<?php
if(!$_COOKIE['test']) {
$newid=rand(1000,9999999);
echo base64_encode("$newid");
mysql_query("INSERT INTO `users` SET `id`='".$newid."', `channel`='0', `activation_date`=now(), `last_view`=now()");
setcookie('test', $newid, mktime (0, 0, 0, 12, 31, 3015));
} else {
echo base64_encode($_COOKIE['test']);
}
?>
I am NOT good with server-side technologies (have a hard time wrapping my mind around them at points). I am pretty decent with PHP.
I have a form that offers color options (now in drop-down format, but in future will be an image click). There are multiple choices in the form, for instance you can choose a frame color in one select menu, then choose a top color in another select menu in this illustration. Depending on which page you are on, there can be up to 12 of these choices, all named a,b,c,d...through l.
I have an image that is being created by phpgd library. Here is the current setup for the php gd:
$a = $_POST['a'];//1
$b = $_POST['b'];//2
$c = $_POST['c'];//3
$d = $_POST['d'];//4
$e = $_POST['e'];//5
$f = $_POST['f'];//6
$g = $_POST['g'];//7
$h = $_POST['h'];//8
$i = $_POST['i'];//9
$j = $_POST['j'];//10
$k = $_POST['k'];//1
$l = $_POST['l'];//12
$default = imagecreatefrompng('../configurator-testing/11ta-503/default.png');
$defaulta = imagecreatefrompng('../configurator-testing/11ta-503/black_a.png');
$defaultb = imagecreatefrompng('../configurator-testing/11ta-503/black_b.png');
header('Content-Type: image/png');
$x = imagesx($default);
$y = imagesy($default);
imagecopy($default, $defaulta,0, 0, 0, 0, $x, $y);
imagecopy($default, $defaultb, 0, 0, 0, 0, $x, $y);
imagepng($default);
imagedestroy($default);
imagedestroy($defaulta);
imagedestroy($defaultb);
Right now, it only posts a "default" image, which has a black frame, black top. What I want it to do is take the form input, and without refreshing the page or using a submit button, use the submitted values to change what image is created. File names are formatted according to the submitted value (ex. submitted black will correlate to files black_a.php and black_b.php, etc). Here is the form I am testing with:
<img src="config-gd.php"/>
<form id="configform" name="configform">
<label>Frame Color</label>
<select name="a" id="a">
<option value="black">black</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
<label>Top Color</label>
<select name="b">
<option value="black">black</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
Notice that it is pulling my image (phpgd) file in the first line above the form, so I want the choices to be processed through my phpgd script, and throw out the new color choices in the image above the form.
I can figure out how to get it to process in the phpgd script, no problem. I am having problems with the posting with no refresh and without a button part. Anyone know some jquery/ajax and willing to help? I've been trying to put something together off of tutorials on the web, i'm having an awful time.
I had found some simple functions to model after, and here is what I came up with, but I can't figure out how best to implement, and so far my efforts have not turned out:
function postImg(layer1, layer2){
$.ajax({
url: "config-gd.php",
data: {
id: layer1,
rate: layer2
},
type: "POST",
success: function(){
alert('Done!');
}
});
}
If I am right you want an image created by php to load on an event without page reload. I think it is simple.
==================edited part code is replaced==================================
Okay I see you need to send form data to php, it is trivial with Ajax, it's also easy to create the image too however what seems difficult for me is how to turn the raw data sent by php to a real image using js.
So I don't include the ajax here, however you can still sent the form data dynamically, without reload of course and get the desired image, using the src attribute of the image, check this code, maybe it can be of some help if customized to your needs.
image.php
if($_GET['color']=='red')
{$red=223; $green=32; $blue=3;}
else
{$red=0; $green=0; $blue=0;}
$im = #imagecreate(110, 20)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, $red, $green, $blue);
$text_color = imagecolorallocate($im, 233, 233, 231);
imagestring($im, 11, 5, 5, $_GET['txt'], $text_color);
imagepng($im);
imagedestroy($im);
?>
index.htm
<html>
<head>
<script type="text/javascript">
function updateImage(color)
{
var txt = document.getElementById("myTxtId").value;
document.getElementById("imgElement").src='image.php?txt='+txt+'&color='+color;
}
</script>
</head>
<body >
Write something here and I will get it back as an image created by php.<br>
<form >
<input type="text" name="txt" id="myTxtId">
<input type=submit value="Get it it black" onclick="updateImage('black');return false;" >
<input type=submit value="Get it it red" onclick="updateImage('red');return false;" >
</form>
<img src="" border=24 color=gold height="111" width="222" id="imgElement">
</body>
</html>
I have built a contact form using CakePHP following the tutorial at http://snook.ca/archives/cakephp/contact_form_cakephp
But would like to add a spam protector where the user is presented with a 5 letter character word such as BB42A that is random and the user has to type in before they can submit the form.
I have done some Googling but haven't found anything suitable online.
Any suggestions? Thanks
The one at the bottom of here is quite good: http://mattbrett.com/portfolio/hire/
I would suggest using an existing CAPTCHA library or service rather than rolling your own. No sense re-inventing the wheel.
One of the best is reCAPTCHA. Here's a good tutorial on implementing reCAPTCHA in Cake.
you can use actice/passive captchas with simple math questions like 2+3
http://www.dereuromark.de/2010/08/09/how-to-implement-captchas-properly/
how secure it needs to be is your decision. for most sites this is more than enough.
Actually - one of easiest ways I found to beat spambots was to have a hidden field in every contact form; and usually spambots would fill it whereas humans, as they can't see it, wouldn't be able to.
Try adding to your view:
//call it something along the lines of 'name' or 'email', and the
//real form field 'x1' or 'x2' etc
$this-Form->input('aformfield', array('class' => 'aformfield');
Make sure you hide it in your css:
.aformfield{display:none;}
In the controller before you send the email, check to see if the hidden field is filled:
if(!empty($this->data['Model']['aformfield'])){
$this->Session->setFlash('You shouldn\'t be able to fill out a hidden field');
$this->redirect($this->referrer());
}
It's not bullet proof and I'm sure spambots will ifnd a way around it but it's a good place to start if you don't want to do captcha's.
What you need is called captcha.
Google search for cakePHP + captcha should come up with some cakePHP plugins. I don't develop in cakePHP, so I can't tell more.
You can, of course, make your own captcha and then integrate it in your website.
To keep it short:
Generate a random string;
create an image with this string
(imagecreate function on php.net);
save the string as session
variable;
compare what user submitted with what's saved in session.
Code:
<?php
session_start();
function rand_str($length = 6,
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
{
$chars_length = (strlen($chars) - 1);
$string = $chars{rand(0, $chars_length)};
// Generate random string
for ($i = 1; $i < $length; $i = strlen($string))
{
// Grab a random character from list
$r = $chars{rand(0, $chars_length)};
// Make sure the same two characters don't appear next to each other
if ($r != $string{$i - 1}) $string .= $r;
}
return $string;
}
header("Content-Type: image/png");
$im = #imagecreate(100, 40) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0); // black
$text_color = imagecolorallocate($im, 255, 255,255); // white
$random_string = rand_str();
$_SESSION['captcha'] = $random_string;
imagestring($im, 5, 5, 5, $random_string, $text_color);
imagepng($im);
imagedestroy($im);
?>
I searched Google and Stackoverflow but could not find the answer. Probably it is because I am searching for the wrong question. Without the right question, it’s hard to get the right answers. So I hope someone can help me.
I have created a top 20 list where people can rank their favourite website (I know it is not that original, but I do it to learn php)
Websites can be added to a database and are sorted based on votes. Each website has its own unique ID in the database, name and position.
What I cannot figure out is how to do the following.
Next to the list displayed show a get code button. This button will create a code for an image file that can be display on any website. For example:
<img src="http://www.example.com/counter.php?id=47"/>
or even better
<img src="http://www.example.com/47.gif"/>
To do this I need to make a php code, that can take the id and turn it into a nice image file and there I am stuck. I have seen twitter, feedburner, Technorati and over 100 other websites do this, but I cannot find out how.
I found this code that fakes feedburner, but I cannot figure out how to turn it into what I need.
<?php
//Send a generated image to the browser
create_image();
exit();
function create_image(){
//Create the image resource
$image = imagecreatefromgif('image.gif');
//Create text color
$brown = ImageColorAllocate($image, 0, 0, 0);
//Check for the get parameters
if (isset($_GET['count']) && is_numeric($_GET['count']))
$rank = $_GET['count'];
else
$rank = 20;
// Some Alignment Calculations
$bbox = imagettfbbox(8.5, 1,'verdana.ttf', $rank);
$xcorr = 0 + $bbox[2]; $xcorr = 31 - $xcorr;
//Add the number in brown color to the image
imagettftext($image,8.5,0,$xcorr,16,$brown,'verdana.ttf',$rank);
//Tell the browser what kind of file is come in
header("Content-Type: image/gif");
imagegif($image);
//Free up resources
ImageDestroy($image);}?>
Based on
www.mygeekpal.com/how-to-fake-your-feedburner-subscribers/
Using the above code and naming it counter.php I can fetch the position from the database and create
<img src='http://www.example.com/counter.php?count=".$array ['position']."' />
This takes the positon of a website from the database ($array has already been made to fetch) and creates an image with the position nr.
Works fine, but once the postion changes based on user ratings, the image will not show the correct data.
I hope someone can help. Thank you.
Summery
Basically what I am try to make is something that will show the most recent data, based on the ranking of the website. Just like showing the number of twitter followers, for example http://twittercounter.com/counter/?username=labnol or feedburner followers on http://feeds.feedburner.com/~fc/labnol
Both are images that show a number based on information in a database. But I want to create my own image, based on the rank of the website in the database.
Looking at your code it should update everytime the page is reloaded. Clear your browser cache.
If this fails i would check from where it is getting the Get['count'] data which im assuming is the Rank number of the site.
Can you check that the Get['Count'] data is updating as it should ?
Im not sure using an ARRAY in the URL is a good idea, why not use Sessions ?
This link might be of interest.
Sorry i have not been of more help.
This is what I have so far (I cannot edit this question from this computer, due to different cookies).
This is based on the help from
How to fetch data from database and display it in PHP?
thanks to
https://stackoverflow.com/users/353790/robertpitt
This seems to work
<?php
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM domains WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
}
$img_number = imagecreate(110,24);
$image = imagecreatefromgif('image.gif');
$backcolor = imagecolorallocate($img_number,254,46,212);
$textcolor = imagecolorallocate($image, 0, 0, 0);
imagefill($image,0,0,$backcolor);
$number = $user['position'];
Imagestring($image,9,26,4,$number,$textcolor);
header("Content-Type: image/gif");
imagegif($image);
ImageDestroy($image);
?>