I am new to web development and I am trying to put CAPTCHA into my website. I am stuck at this. And I couldn't find any help.
The following is my Form code:
<tr>
<td>
<img src="html-contact-form-captcha/captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
</td>
</tr>
<tr>
<td align="right"><b> Enter Image Text </b></td>
<td><input placeholder="Enter the code above here" id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</td>
</tr>
And on this same page I am trying to validate this CAPTCHA by the following code:
var cde = document.getElementById('6_letters_code');
if( cde.value == "" ||
($_SESSION['6_letters_code'] != $_POST['6_letters_code']) ) {
alert( "Code Matched!" );
//alert( "Code Doesn't Match! \n Code Not Entered!" );
return false;
}
And this is where I am getting my CAPTCHA: (captcha.php)
session_start(); // Staring Session
$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; // Initializing PHP variable with string
$captchanumber = substr(str_shuffle($captchanumber), 0, 6); // Getting first 6 word after shuffle.
$_SESSION["code"] = $captchanumber; // Initializing session variable with above generated sub-string
$image = imagecreatefromjpeg("bj.jpg"); // Generating CAPTCHA
$foreground = imagecolorallocate($image, 175, 199, 200); // Font Color
imagestring($image, 5, 45, 8, $captchanumber, $foreground);
header('Content-type: image/png');
imagepng($image);
Any help would be appreciated.
Thank you in advance.
In Javascript
If you want to evaluate that the captcha is correct in Javascript, which runs in your browser after the page was generated by PHP on the server, then Javascript will have to have the means to check it.
For this you have to use a session, in which you can store the captcha value. Use these steps:
At the start of the PHP file, that generates your form, you should select a captcha code. You store this in a session variable.
You produce a hash of the captcha in PHP and put it in a hidden field of the form. Give this field a proper id, so you can find it with Javascript.
$hash = sha1($captcha); // this is PHP code
Generate the image of the captcha, using the stored session variable.
Regrettably Javascript does not have any native hash algorithm. Other people have solved this:
http://caligatio.github.io/jsSHA/
So now you can also make a hash of the captcha, that was entered by the user into the form, in Javascript. All you need to do is to check it against the hash that PHP has put in the hidden field in the form. If they match the Captcha was correct.
As you can see, this is not really easy.
In PHP
It is easier to do the check in PHP after the form was submitted. I think I can assume your captcha.php works. In that you store $captchanumber in the session of the user. That was a good idea.
So you make the form, put the captcha in it, and let the user submit it. The check will now be done in PHP, like this:
$captchaNumber = $_SESSION['code'];
$userNumber = $_POST['6_letters_code']; // a name starting with number? eh??
if ($captchaNumber == $userNumber)
{
<.... the user did it correctly ....>
}
else
{
// it was the wrong code, back to the form
header('Location: '.<... url of form ...>);
}
The header() function should be used before any output. For starters I would suggest to submit the form to another PHP script. Once that works you can try an merge the form script and the submission script into one PHP script.
Please try the below code. I hope it work. I tried to write the code from scratch:-
<?php session_start();
// Staring Session
$im = imagecreate(90, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 0);
$captchaKey = substr(md5(time()), 0, 5);
$_SESSION["code"] = $captchaKey;
imagestring($im, 45, 20, 5, $captchaKey, $textcolor);
//header("Content-type: image/png");
$save = "captcha.png";
$x1 = imagepng($im, $save);
?>
<script>
function checkCaptcha() {
var cde = document.getElementById('6_letters_code');
if( cde.value == '<?php echo $_SESSION['code']; ?>
' ) {
alert( "Code Matched!" );
//alert( "Code Doesn't Match! \n Code Not Entered!" );
return false;
} else {
alert('Code not matched!')
}
}
</script>
<tr>
<td><img src="captcha.png" id='captchaimg' >
<br>
</td>
</tr>
<tr>
<td align="right"><b> Enter Image Text </b></td>
<td>
<input placeholder="Enter the code above here" id="6_letters_code" name="6_letters_code" type="text">
<br>
<button onclick="checkCaptcha()">
Click to check
</button><small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small></td>
</tr>
Related
I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.
How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>
I want to create a simple captcha verification form and it looks like this:
<form>
<br/>Captcha :<img class="captcha" src="<?php echo base_url('application/views/captcha/image.php')?>">
<br/><br/><input type="username" required class="i" name="captcha" id="i7" size="25"/>
<br><br><input type="submit" name="Submit" id="submit" value="Register"/>
</form>
Here's the image.php file:
<?php
session_start();
header("Content-Type: image/png");
$text = rand(1000,100000);
$_SESSION['code'] = $text;
$img = imagecreatefromjpeg("bg.jpg");
$font = "arial.ttf";
$R = rand(0,100);
$G = rand(0,100);
$B = rand(0,100);
$TxtColor = imagecolorallocate($img,$R,$G,$B);
imagettftext($img,rand(40,45),rand(0,1),rand(10,70),rand(38,50),$TxtColor,$font$text);
imagepng($img);
imagedestroy($img);
?>
It works fine outside Codeigniter. In Codeigniter, whenever I try to retrieve the value of $text from the session I get an error message as "Undefined index: code". If I use Codeigniter's userdata() method as following:
$this->session->set_userdata($text);
The captcha image doesn't even show.
In Codignitor you need to load session library before set the session:
$this->load->library('session');
Than you can set session by using array:
$array["code"] = $text;
$this->session->set_userdata($array);
When you need to print:
$this->session->userdata("code");
CI SESSION USER GUIDE
i want the value of $code variable to get on my other page--- captcha.php.
captcha_image.php
$captcha = new CaptchaCode(); //class defined in captcha_code.php
$code = str_encrypt($captcha->generateCode(6)); //function defined in captcha_code.php
$captcha1 = new CaptchaImages();
$captcha1-> GenerateImage($width,$height,str_decrypt($code));
captcha.php
<img style="cursor: pointer;width: 50px;height: 50px;" src="refresh.png" onclick="refresh_captcha();"/>
<input type="hidden" name="security_check" value="<?php echo $code; ?>"> // want value of $code here
<script type="text/javascript">
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = 'captcha_images.php';
jQuery("#captcha_img").attr("src",img.src);
}
</script>
I cant include captcha_images.php file in my code and even dont want it to be done using sessions, tried that way.If anyone has a solution for this, please help me to solve this issue.
Better solution is save code into SESSION.
For example:
captcha_image.php:
session_start();
$captcha = new CaptchaCode();
$code = $captcha->generateCode(6);
$captcha1 = new CaptchaImages();
$captcha1-> GenerateImage($width,$height,$code);
$_SESSION["captchacode"] = $code;
And check correctness after submit of the form:
session_start();
...
if($_SESSION["captchacode"]!=$_POST["security_check"]){
echo "Wrong captcha!";
}else{
// captcha is correct, process the form
}
If you cannot use cookies and session, you cannot get information from captcha_image.php which returns only image. You must generate information in else request, for example:
<img id="captcha_img" src="captcha_images.php?encoded_code=<?php echo $code ?>" onclick="refresh_captcha();"/>
<input type="hidden" id="captcha_hidden" name="security_check" value="<?php echo $code ?>">
<script type="text/javascript">
function refresh_captcha()
{
// generate_captcha.php returns only encoded captcha
$.get('generate_captcha.php', function(encoded_code) {
$('#captcha_hidden').val(encoded_code);
$('#captcha_img').attr("src","captcha_images.php?encoded_code="+encoded_code);
});
}
</script>
Here generate_captcha.php returns encoded captcha, captcha_images.php doesnt generate code, only decode code from hims parameter encoded_code and this code is also inserted into hidden.
I am working on a form which is validated with jQuery before being submitted. One of the fields is a captcha.
The idea is very simple, the captcha is shown as an image and also stored in a hidden field. When the user enters the captcha in the input field it should be equal to the value of the hidden field. This is the jQuery code I have;
<script>
$(document).ready(function(){
$("#register").validate({
errorElement: 'div', ignore: 'hidden',
rules: {
password: {
required: true
},
password2: {
required: true, equalTo: "#password"
},
agree: {
required: true
},
captcha: {
required: true, equalTo: "#captcha2"
}
},
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service"
}
});
});
</script>
The html code for the form is even simpler, but I will show only a part of it.
<p>
<img src='/includes/captcha.php' />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25"
class="require" minlength="5" />
<input type="hidden" name="captcha2" id="captcha2"
value="<?php echo $_SESSION['captcha'];?>" />
<?php echo $_SESSION['captcha']; ?>
Here is something weird. When I echo the session['captcha'] I get a different value than the value in the hidden field. I get the previous captcha when I echo it.
So let's say the captcha value is ABC. When I refresh the page the captcha+hidden field change into DEF. But when I echo session['captcha'] I still get ABC.
Why is this happening?
Here is the code of the captcha.php file;
<?php
session_start();
header("Content-type: image/png");
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$_SESSION['captcha'] = $string;
putenv('GDFONTPATH=' . realpath('.'));
$dir = 'musicals';
$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 129, 180, 79); // green
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir, $_SESSION['captcha']);
imagepng($image);
?>
The problem is that your captcha generation is within the image, and that this image is only accessed after the form has been accessed. Your captcha is generated AFTER you show the form, this is why it's always one step behind.
Aside from that, it's a bad idea to store the captcha solution in a hidden field. A person, or a bot, can simply parse the website's source code and extract and use it as the captcha solution.
Be sure that captcha.php is run before html code. It looks like captcha.php generates image and probably it is inserted as an img in HTML. Image is got after page loading (generating HTML) so captcha code in session is not regenerated.
I belive that you inserted hidden element with captcha as an example. It is bad idea to show captcha code as a hidden element in form.