Single Digit Captcha Match, PHP - php

I run a PTC website advertising websites for people. And i'm needing an easy to to lower or completely prevent bot usage.
After the advertisement counter is done counting down i would like a captcha to load.
But i don't want a captcha that you have to enter anything. Just a single mouse click.
If the captcha can be done in javascript that would be really great.
I'm looking for something sort of like this:
Counter:0 Select Matching Number: 7 [1] [0] [7] [2]
The user would have to click on the number in the box that matches the number.
Digits would be within 1-9.

Short of a full captcha you wont stop a determined bot.
A few ideas.
Allow 10 - 15 requests within 10 a minutes period, if it exceeds that, ask for captcha or block completely. Make sure this is IP based, because cookies/session wont work
Add some javascript to the form so that it cannot be posted without it. Most email collecting spam bots won't run javascript and give up. Generate a random string, store in $_SESSION on page request. Use javascript to add to the form post. if that string doesn't exist match on form post display a captcha.
Or use javascript to contstruct the form itself.
A determined scraper can get around most anything, but you just want to increase the cost of doing so.

I have made a CAPTCHA script. It's size, number of characters, and characters to choose from are customizable.
Here is captcha.php:
<?php
function generateCaptcha($num_digits, $challenge_num, $size, $chars, $incode = false) {
if(session_id() == '') session_start();
if(isset($_SESSION['captcha'])) unset($_SESSION['captcha']);
// You *must* type your own random salt here, *DO NOT* use this one.
$salt = 'H#(*h3^rh#(*E%h$W*WK#vMIv)%(D*(A&*W#A^D6#r4*I%u8tgsc#yejdi$d8dee';
$message = '';
if(isset($_POST['hash']) && isset($_POST['code'])) {
if(!empty($_POST['hash']) && !empty($_POST['code']) && !empty($_POST['correct_index'])) {
if(md5($_POST['hash'] . $_POST['code'] . $salt) == $_POST['correct_index']) {
$message = '<p>Correct!</p>';
} else {
$message = 'Incorrect code. Please try again.';
}
}
}
$code = '';
if($incode == false) {
for($i = 0; $i < $num_digits; $i++) {
$digit = substr($chars, floor(mt_rand(0, strlen($chars) - 1)), 1);
while(strpos($code, "$digit") !== false) {
$digit = substr($chars, floor(mt_rand(0, strlen($chars) - 1)), 1);
}
$code .= $digit;
}
} else {
for($i = 0; $i < $num_digits; $i++) {
$digit = substr($incode, floor(mt_rand(0, strlen($incode) - 1)), 1);
while(strpos($code, "$digit") !== false) {
$digit = substr($incode, floor(mt_rand(0, strlen($incode) - 1)), 1);
}
$code .= $digit;
}
}
$parts = str_split($code);
$width = $num_digits * $size;
$height = $size * 2;
$image = imagecreatetruecolor($width, $height);
$background = imagecolorallocate($image, floor(mt_rand(96, 255)), floor(mt_rand(96, 255)), floor(mt_rand(96, 255)));
imagefilledrectangle($image, 0, 0, $width, $height, $background);
$num_spots = floor(mt_rand($size * 2, $size * 15));
for($i = 0; $i < $num_spots; $i++) {
$color = imagecolorallocate($image, floor(mt_rand(30, 255)), floor(mt_rand(30, 255)), floor(mt_rand(30, 255)));
$x = floor(mt_rand(0, $width));
$y = floor(mt_rand(0, $height));
$ellipse_width = floor(mt_rand(0, $size / 2));
$ellipse_height = floor(mt_rand(0, $size / 2));
imagefilledellipse($image, $x, $y, $ellipse_width, $ellipse_height, $color);
$x1 = floor(mt_rand(0, $width));
$y1 = floor(mt_rand(0, $height));
$x2 = floor(mt_rand(0, $width));
$y2 = floor(mt_rand(0, $height));
imageline($image, $x1, $y1, $x2, $y2, $color);
}
$num_dots = floor(mt_rand($size * 50, $size * 80));
for($i = 0; $i < $num_dots; $i++) {
$color = imagecolorallocate($image, floor(mt_rand(30, 255)), floor(mt_rand(30, 255)), floor(mt_rand(30, 255)));
$x = floor(mt_rand(0, $width));
$y = floor(mt_rand(0, $height));
imagesetpixel($image, $x, $y, $color);
}
for($i = 0; $i < count($parts); $i++) {
$color = imagecolorallocate($image, floor(mt_rand(0, 150)), floor(mt_rand(0, 150)), floor(mt_rand(0, 150)));
$x = floor(mt_rand($size * 0.9, $size * 1.1));
$y = floor(mt_rand($size, $size * 2));
imagettftext($image, $size, floor(mt_rand(-10, 10)), $i * $x, $y, $color, 'Justus-Bold.ttf', $parts[$i]);
imagettftext($image, $size, floor(mt_rand(-10, 10)), $i * $x + floor(mt_rand(1, 7)), $y, $color, 'Justus-Bold.ttf', $parts[$i]);
imagettftext($image, $size, floor(mt_rand(-10, 10)), $i * $x + floor(mt_rand(1, 7)), $y, $color, 'Justus-Bold.ttf', $parts[$i]);
imagettftext($image, $size, floor(mt_rand(-10, 10)), $i * $x + floor(mt_rand(1, 7)), $y, $color, 'Justus-Bold.ttf', $parts[$i]);
}
$white = imagecolorallocate($image, 255, 255, 255);
$filename = md5(time() . $_SERVER['REMOTE_ADDR'] . mt_rand(0, 1000)) . '.png';
imagepng($image, $filename);
imagedestroy($image);
$file = file_get_contents($filename);
$imgsize = getimagesize($filename);
unlink($filename);
$captcha = 'data:' . $imgsize['mime'] . ';base64,' . base64_encode($file);
$challenge = array('captcha' => '', 'code' => null, 'size' => 0, 'digits' => 0);
if($incode == false) {
$challenge = generateCaptcha($challenge_num, 0, $size, $chars, $code);
}
$hash = md5($challenge['code'] . $salt);
$correct_index = array();
for($i = 0; $i < strlen($challenge['code']); $i++) {
$correct_index[] = strpos($code, substr($challenge['code'], $i, 1));
}
$result = array(
'captcha' => $captcha,
'challenge' => array($challenge['captcha'], $challenge['size'], $challenge['digits']),
'size' => array($imgsize[0], $imgsize[1]),
'hash' => $hash,
'code' => $code,
'message' => $message,
'width' => $size,
'digits' => $num_digits,
'correct_index' => md5($hash . implode('', $correct_index) . $salt)
);
return $result;
}
?>
...and here is captcha.html:
<!DOCTYPE HTML>
<!--
<?php
include 'captcha.php';
$captcha = generateCaptcha(4, 2, 100, '0123456789');
?>
-->
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Click-captcha test</title>
<style type="text/css">
#challenge, #captcha-img {
margin: 10px
}
#captcha-img {
overflow: hidden
}
.captcha-digit {
display: block;
float: left;
width: <?php echo $captcha['width']; ?>px;
height: 100%;
cursor: pointer
}
.captcha-digit-selected {
background: #ccc;
opacity: .75;
filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#f2cccccc', EndColorStr='#f2cccccc')
}
</style>
<script type="text/javascript">
var captchaLinks = [];
var digits = [];
var num_digits = <?php echo $captcha['challenge'][2]; ?> - 1;
addEvent(window, 'load', init);
function init() {
captchaLinks = ['<?php
$digits = array();
for($i = 'digit0'; $i < 'digit' . $captcha['digits']; $i++) {
$digits[] = $i;
}
echo implode("', '", $digits);
?>'];
for(var i = 0; i < captchaLinks.length; i++) {
//for(var link in captchaLinks) {
addEvent(document.getElementById(captchaLinks[i]), 'click', newCaptchaDigit);
}
}
function newCaptchaDigit(e) {
if(e.target.className == 'captcha-digit captcha-digit-selected') {
digits.splice(digits.indexOf(e.target.id.substr(-1, 1)), 1);
e.target.className = 'captcha-digit';
} else if(digits.length <= num_digits) {
digits.splice(num_digits, digits.length - num_digits, e.target.id.substr(-1, 1));
e.target.className = 'captcha-digit captcha-digit-selected';
}
document.getElementById('code').value = digits.join('');
}
function addEvent(elem, event, handler) {
if(elem !== null & typeof elem !== 'undefined') {
if(elem.addEventListener) {
elem.addEventListener(event, handler, false);
} else if(elem.attachEvent) {
elem.attachEvent('on' + event, handler);
} else if(elem['on' + event]) {
elem['on' + event] = handler;
}
}
}
</script>
</head>
<body>
<div>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div id="captcha">
<div><?php echo $captcha['message']; ?></div>
<div>Click the following number sequence:
<div id="challenge" style="width: <?php echo $captcha['challenge'][1][0]; ?>px; height: <?php echo $captcha['challenge'][1][1]; ?>px; background-image: url('<?php echo $captcha['challenge'][0]; ?>')"></div>
</div>
<div id="captcha-img" style="width: <?php echo $captcha['size'][0]; ?>px; height: <?php echo $captcha['size'][1]; ?>px; background-image: url('<?php echo $captcha['captcha']; ?>')">
<?php for($i = 'digit0'; $i < 'digit' . $captcha['digits']; $i++) { ?>
<a class="captcha-digit" id="<?php echo $i; ?>"></a>
<?php } ?>
</div>
</div>
<input type="hidden" name="hash" value="<?php echo $captcha['hash']; ?>" />
<input type="hidden" name="correct_index" value="<?php echo $captcha['correct_index']; ?>" />
<input type="hidden" name="code" id="code" value="" />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
Hopefully you will able to see what is going on, but I will explain it here. :-)
The function is called generateCaptcha, and it accepts the parameters $num_digits, $challenge_num, $size, $chars, $incode = false.
$num_digits: number of characters to put in the CAPTCHA
$challenge_num: number of characters to put into the challenge
$size: size of the CAPTCHA
$chars: what characters to include (e.g. for numbers: '0123456789')
$incode: this is just so the script can tell if it has been called by itself to generate the challenge or not. Don't set it.
So to create a CAPTCHA image with 4 characters, a 1 character challenge (like your question), size 30, and only with digits, use this code:
<?php
include 'captcha.php';
$captcha = generateCaptcha(4, 1, 30, '0123456789');
?>
Then the variable $captcha will end up something like this:
array(9) {
["captcha"]=>
string(118058) "data:image/png;base64,iVBORw0KG...kSuQmCC"
["challenge"]=>
array(3) {
[0]=>
string(76266) "data:image/png;base64,iVBORw0KG...kJggg=="
[1]=>
array(2) {
[0]=>
int(200)
[1]=>
int(200)
}
[2]=>
int(2)
}
["size"]=>
array(2) {
[0]=>
int(400)
[1]=>
int(200)
}
["hash"]=>
string(32) "81bc501400b8da366e70b26007cb2323"
["code"]=>
string(4) "4817"
["message"]=>
string(0) ""
["width"]=>
int(100)
["digits"]=>
int(4)
["correct_index"]=>
string(32) "17ae615be69c757505dc7f69fce2afb1"
}
If you need any more information, please ask in a comment.

Related

Wordpress problem with header('Content-type: image/png');

i'am trying to put a CAPTCHA in a wordpress custom plugin.
I did follow that tutorial :
https://code.tutsplus.com/tutorials/build-your-own-captcha-and-contact-form-in-php--net-5362
<?php
session_start();
$permitted_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
function generate_string($input, $strength = 10) {
$input_length = strlen($input);
$random_string = '';
for($i = 0; $i < $strength; $i++) {
$random_character = $input[mt_rand(0, $input_length - 1)];
$random_string .= $random_character;
}
return $random_string;
}
$image = imagecreatetruecolor(200, 50);
imageantialias($image, true);
$colors = [];
$red = rand(125, 175);
$green = rand(125, 175);
$blue = rand(125, 175);
for($i = 0; $i < 5; $i++) {
$colors[] = imagecolorallocate($image, $red - 20*$i, $green - 20*$i, $blue - 20*$i);
}
imagefill($image, 0, 0, $colors[0]);
for($i = 0; $i < 10; $i++) {
imagesetthickness($image, rand(2, 10));
$line_color = $colors[rand(1, 4)];
imagerectangle($image, rand(-10, 190), rand(-10, 10), rand(-10, 190), rand(40, 60), $line_color);
}
$black = imagecolorallocate($image, 0, 0, 0);
$white = imagecolorallocate($image, 255, 255, 255);
$textcolors = [$black, $white];
$fonts = [dirname(__FILE__).'/Acme.ttf'];
$string_length = 6;
$captcha_string = generate_string($permitted_chars, $string_length);
$_SESSION['captcha_text'] = $captcha_string;
for($i = 0; $i < $string_length; $i++) {
$letter_space = 170/$string_length;
$initial = 15;
imagettftext($image, 24, rand(-15, 15), $initial + $i*$letter_space, rand(25, 45), $textcolors[rand(0, 1)], $fonts[array_rand($fonts)], $captcha_string[$i]);
}
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
At first wordpress didn't find the font, but i manage to pass the error.
Then i call by shortcode the html. And i all i got is the alt and broken img. If i put directly the script in the function chrome tell me that my image contain errors. I did try to add utf8 encode and to pass the image without the header, none of that work.
public function CAPTCHA_shortcode_function() {
ob_start();
?>
<div class="elem-group">
<label for="captcha">Please Enter the Captcha Text</label>
<img src="CAPTCHA-generate-image.php" alt="CAPTCHA" class="captcha-image"><i class="fas fa-redo refresh-captcha"></i>
<br>
<input type="text" id="captcha" name="captcha_challenge" pattern="[A-Z]{6}">
</div>
<?php
$CAPTCHA = ob_get_clean();
return $CAPTCHA;
}
If you have any idea, something must be wrong ^^ Thanks a lot !
We did find a solution :
imagepng($captcha_image,"captcha_image.png");
$imgData = file_get_contents('captcha_image.png');
imagedestroy($captcha_image);
// $imgData = ob_get_clean();
return $imgData;
Then call it in the function like this
ob_start();
$imgData = $this->CAPTCHA_generate();
?>
<div id="CAPTCHA_box">
<label for="captcha">Entrez les </label><br>
<?php echo '<img class="captcha_image" src="data:image/png;base64,'.base64_encode($imgData).'" />'; ?>
<i class="fas fa-redo refresh_captcha"></i>
<br>
<input type="text" id="captcha" name="captcha_challenge" pattern="[A-Z]{6}">
</div>
<?php
$CAPTCHA = ob_get_clean();
return $CAPTCHA;

Blank pages when trying to do captcha

Hello i am learning php now and developing website for my education. I am facing problem if i try to add captcha image. I don't know where is the problem but instead of working captcha i get blank page.
I even tried few already done captchas from github but get same problem i think the problem could be with fonts but i am not sure "ts probably my stupidity and i am doing something wrong :D" . Anyway if anyone can help me with it it would be great.
code i tried to use:
captcha.php
<?php
class captcha {
private static $captcha = "__captcha__";
public static $font;
private static $width = 70;
private static $height = 70;
private static $font_size = 40;
private static $character_width = 40;
private static function session_exists() {
return isset($_SESSION);
}
private static function set_font() {
self::$font = self::$captcha;
$AnonymousClippings ='there is inserted chars from font you can';
self::$font = tempnam(sys_get_temp_dir(), self::$captcha);
$handle = fopen(self::$font,"w+");
fwrite($handle,base64_decode($AnonymousClippings));
fclose($handle);
return self::$font;
}
private static function get_random() {
$type = rand(0,2);
switch($type) {
case 2:
$random = chr(rand(65,90));
break;
case 1:
$random = chr(rand(97,122));
break;
default:
$random = rand(0,9);
}
return $random;
}
private static function generate_code($length) {
$code = null;
for($i = 0; $i < $length; $i++) {
$code .= self::get_random();
}
if(self::session_exists()) {
$_SESSION[self::$captcha] = $code;
}
self::$width = $length * self::$character_width;
return $code;
}
private static function get_width() {
return self::$width;
}
private static function get_height() {
return self::$height;
}
public static function image() {
$length = 6;
$code = self::generate_code($length);
self::set_font();
ob_start();
$image = imagecreatetruecolor(self::get_width(),self::get_height());
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, self::get_width(), self::get_height(), $white);
for($dot = 0; $dot < 2000; $dot++) {
$r = rand(0,255);
$g = rand(0,255);
$b = rand(0,255);
$dot_color = imagecolorallocate($image, $r, $g, $b);
$x1 = rand(0, self::get_width());
$y1 = rand(0, self::get_height());
$x2 = $x1 + 1;
$y2 = $y1 + 1;
imageline($image, $x1, $y1, $x2, $y2, $dot_color);
}
for($start = - $length; $start < 0; $start++) {
$color = imagecolorallocate($image, rand(0,177), rand(0,177), rand(0,177));
$character = substr($code, $start, 1);
$x = ($start+6) * self::$character_width;
$y = rand(self::get_height() - 20, self::get_height() - 10);
imagettftext($image, self::$font_size, 0, $x, $y, $color, self::$font, $character);
}
imagepng($image);
imagedestroy($image);
$source = ob_get_contents();
ob_end_clean();
unlink(self::$font);
return "data:image/png;base64,".base64_encode($source);
}
public static function get_code() {
if(self::session_exists()) {
return $_SESSION[self::$captcha];
}
return rand();
}
}
index.php file
<?php
session_start();
require_once("captcha.php");
if(isset($_POST['rCaptcha'])) {
echo captcha::image();
exit;
}
else if(isset($_POST["code"])) {
if($_POST["code"] == captcha::get_code()) {
echo "Good";
}
else {
echo "Bad";
}
echo "<br/>";
}
?>
<script>
function refreshCaptcha(target) {
var req = new XMLHttpRequest();
req.open("POST", window.location, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
target.src = req.responseText;
}
}
req.send("rCaptcha=true");
}
</script>
<form method="post" autocomplete="off">
<fieldset>
<legend>PHP Captcha</legend>
<input type="text" name="code" placeholder="Captcha Code" /><br/>
<img src="<?= captcha::image() ?>" onclick="refreshCaptcha(this)"
title="click to refresh" /><br/>
<input type="submit" value="Check" /><br/>
</fieldset>
</form>
For a start add those two lines in the beginning of your index.php file (after <?php):
error_reporting(-1);
ini_set('display_errors', 'On');
Then you will see the errors produced by php. It will be much more easy to debug your code!
In this case a semicolon is missing in line 16 in your captcha.php file:
$AnonymousClippings ='there is inserted chars from font you can'

Displaying generated PNG in PHP?

So I'm trying to get a generated UPC bar code to display on an index page. but all it does is output the PNG contents instead of displaying the PNG itself.
I'm not quite sure why its doing this. I'm guessing its some silly little thing i need to add but I have no clue what it would be. So any help would be appreciated.
INDEX CODE
<form method="POST">
<head>UPC Barcode and QRcode Generator</head><br>
<label for="">Type 11 Didgits Here => </label>
<input type="text" class="form-control" name="text_code">
<button type="submit" class="btn btn-primary" name="generate">Generate</button>
<hr>
<?php
//QR CODE
if(isset($_POST['generate'])){
$code = $_POST['text_code'];
echo "<img src='https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=$code&choe=UTF-8'>";}
//Barcode
include "generate.php";
$upc = new BC(null,4);
$number = $_POST['text_code'];
$upc->build($number);
echo "*".substr($code, 0,6)."#".substr($code, 6,6)."*";
?>
GENERATE CODE
<?php
class BC{//
private $height;
private $width;
private $barheight;
private $barwidth;
private $lable;
private $border;
private $padding;
private $mapcode;
private $rightmap;
private $code;
function __construct($lable=null,$barwidth=2) {//
$this->set_width($barwidth);
$this->set_lable($lable);
$this->padding = $barwidth*5;
$this->border =2;
$this->mapcode = array
('0' => '0001101', '1' => '0011001', '2' => '0010011', '3' => '0111101', '4' => '0100011',
'5' => '0110001', '6' => '0101111', '7' => '0111011', '8' => '0110111', '9' => '0001011',
'#' => '01010', '*' => '101');
$this->rightmap = array
('0' => '1110010', '1' => '1100110', '2' => '1101100', '3' => '1000010', '4' => '1011100',
'5' => '1001110', '6' => '1010000', '7' => '1000100', '8' => '1001000', '9' => '1110100',
'#' => '01010', '*' => '101');
}
public function set_width($barwidth) {//
if(is_int($barwidth)) {//
$this->barwidth = $barwidth;
}
else{//
$this->barwidth = 2;
}
}
public function set_lable($lable) {//
if(is_null($lable)) {//
$this->lable = "none";
}
else{//
$this->lable = $lable;
}
}
public function build($code = null) {//
if(is_null($code)) {//
$this->code = "00000000000";
}
else{//
$this->code = $code;
}
$this-> code = substr($code, 0, 11);
if(is_numeric($code)){//
$checksum = 0;
for($digit = 0; $digit < strlen($code); $digit++) {
if($digit%2 == 0) {//
$checksum += (int)$code[$digit] * 3;
}
else{//
$checksum += (int) $code[$digit];
}
}
$checkdigit = 10 - $checksum % 10;
$code .= $checkdigit;
$code_disp = $code;
$code = "*".substr($code, 0,6)."#".substr($code, 6,6)."*";
$this->width = $this-> barwidth*95 + $this->padding*2;
$this->barheight = $this->barwidth*95*0.75;
$this->height = $this->barwidth*95*0.75 + $this->padding*2;
$barcode = imagecreatetruecolor($this->width, $this->barheight);
$black = imagecolorallocate($barcode, 0, 0, 0);
$white = imagecolorallocate($barcode, 255, 255, 255);
imagefill($barcode, 0, 0, $black);
imagefilledrectangle($barcode, $this->border, $this->width - $this->border, -1, $this->barheight - $this->border - 1, $white);
$bar_pos = $this->padding;
for($count = 0; $count < 15; $count++) {
$character = $code [$count];
for($subcount = 0; $subcount < strlen($this->mapcode[$character]); $subcount++) {//
if($count < 7) {
$color = ($this->mapcode[$character][$subcount] == 0) ? $white : $black;
}
else{
$color = ($this->rightmap[$character][$subcount] == 0) ? $white : $black;
}
if(strlen($this->mapcode[$character]) == 7) {
$height_offset = $this->height * 0.05;
}
else {
$height_offset = 0;
}
imagefilledrectangle($barcode, $bar_pos, $this->padding, $bar_pos+$this->barwidth - 1, $this->barheight - $height_offset - $this->padding, $color);
$bar_pos += $this->barwidth;
}
imagepng($barcode);
}
}
}
}
?>
So this is the output
after adding the new code
To display an image in an HTML page, you need to use an <img /> tag. To display image contents in an <img /> tag, you need to use a Data URI Scheme.
You'll end up with something like this:
echo '<img src="data:image/png;base64,', base64_encode($the_png_contents), '" />';
I checked out your Q and in the comments you said it still is not working so I decided to have a look with you. I used your code as you posted in and used it on my own little environment to make it work. What I did is the following:
Changed I made in your index.php:
// Check if request method is post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check if both Generate and Text_code have been set
if(isset($_POST['generate']) && isset($_POST['text_code'])) {
// Set code used through the if statement
$code = $_POST['text_code'];
echo '<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl='. $code . '&choe=UTF-8">';
// Include file; generate.php
include "generate.php";
// New instance of class; BC
$upc = new BC(null, 4);
// Set barcode base64 to variable and display
$barcodeBase64 = $upc->build($code);
echo '<img src="data:image/png;base64,' . base64_encode($barcodeBase64) . '" />';
}
}
Furthermore your generate.php needed a little change in the function build:
public function build($code = null) {
$this->code = is_null($code) ? "00000000000" : $code;
$code = substr($code, 0, 11);
$code = str_pad($code, 11, "00000000000");
if(is_numeric($code)){//
$checksum = 0;
for($digit = 0; $digit < strlen($code); $digit++) {
if($digit%2 == 0) {//
$checksum += (int)$code[$digit] * 3;
}
else{//
$checksum += (int) $code[$digit];
}
}
$checkdigit = 10 - $checksum % 10;
$code .= $checkdigit;
$code_disp = $code;
$code = "*".substr($code, 0,6)."#".substr($code, 6,6)."*";
$this->width = $this-> barwidth*95 + $this->padding*2;
$this->barheight = $this->barwidth*95*0.75;
$this->height = $this->barwidth*95*0.75 + $this->padding*2;
$barcode = imagecreatetruecolor($this->width, $this->barheight);
$black = imagecolorallocate($barcode, 0, 0, 0);
$white = imagecolorallocate($barcode, 255, 255, 255);
imagefill($barcode, 0, 0, $black);
imagefilledrectangle($barcode, $this->border, $this->width - $this->border, -1, $this->barheight - $this->border - 1, $white);
$bar_pos = $this->padding;
for($count = 0; $count < 15; $count++) {
$character = $code[$count];
for($subcount = 0; $subcount < strlen($this->mapcode[$character]); $subcount++) {//
if($count < 7) {
$color = ($this->mapcode[$character][$subcount] == 0) ? $white : $black;
}
else{
$color = ($this->rightmap[$character][$subcount] == 0) ? $white : $black;
}
if(strlen($this->mapcode[$character]) == 7) {
$height_offset = $this->height * 0.05;
}
else {
$height_offset = 0;
}
imagefilledrectangle($barcode, $bar_pos, $this->padding, $bar_pos+$this->barwidth - 1, $this->barheight - $height_offset - $this->padding, $color);
$bar_pos += $this->barwidth;
}
}
ob_start();
imagepng($barcode);
$barcodeImage = ob_get_contents();
ob_clean();
return $barcodeImage;
}
}
I also see that you filled the image with black which normally is filled with white as the code is a black on white image. To change this simply replace:
imagefill($barcode, 0, 0, $black); > imagefill($barcode, 0, 0, $white);

captcha image is display

I have code which display captcha in my local machine. But when I put that code in server then captcha image not working. Please any body solve my problem. My local machine is ubuntu 12.04, and server machine is ubuntu 14.04. Below is my code.
demo.php
<?php session_start();
if(isset($_POST['Submit'])){
// code for check server side validation
if(empty($_SESSION['captcha_code'] ) || strcasecmp($_SESSION['captcha_code'], $_POST['captcha_code']) != 0){
$msg="<span style='color:red'>The Validation code does not match!</span>";// Captcha verification is incorrect.
}else{// Captcha verification is Correct. Final Code Execute here!
$msg="<span style='color:green'>The Validation code has been matched.</span>";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Secure Professional Captcha.</title>
<link href="./css/stylecaptcha.css" rel="stylesheet">
<script type='text/javascript'>
function refreshCaptcha(){
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</head>
<body>
<br>
<form action="" method="post" name="form1" id="form1" >
<table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="table">
<?php if(isset($msg)){?>
<tr>
<td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
</tr>
<?php } ?>
<tr>
<td align="right" valign="top"> Validation code:</td>
<td><img src="captcha.php?rand=<?php echo rand();?>" id='captchaimg'><br>
<label for='message'>Enter the code above here :</label>
<br>
<input id="captcha_code" name="captcha_code" type="text">
<br>
Cannot read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh.</td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" type="submit" onclick="return validate();" value="Submit" class="button1"></td>
</tr>
</table>
</form>
</body>
</html>
captcha.php
<?php
session_start();
include("./phptextClass.php");
/*create class object*/
$phptextObj = new phptextClass();
/*phptext function to genrate image with text*/
$phptextObj->phpcaptcha('#162453','#fff',120,40,10,25);
?>
phptextClass.php
<?php
/*phptext class, version 1.0
created by www.w3schools.in (Gautam kumar)
April 26, 2014
*/
class phptextClass
{
public function phptext($text,$textColor,$backgroundColor='',$fontSize,$imgWidth,$imgHeight,$dir,$fileName)
{
/* settings */
$font = './calibri.ttf';/*define font*/
$textColor=$this->hexToRGB($textColor);
$im = imagecreatetruecolor($imgWidth, $imgHeight);
$textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);
if($backgroundColor==''){/*select random color*/
$colorCode=array('#56aad8', '#61c4a8', '#d3ab92');
$backgroundColor = $this->hexToRGB($colorCode[rand(0, count($colorCode)-1)]);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
}else{/*select background color as provided*/
$backgroundColor = $this->hexToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
}
imagefill($im,0,0,$backgroundColor);
list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize);
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
if(imagejpeg($im,$dir.$fileName,90)){/*save image as JPG*/
return json_encode(array('status'=>TRUE,'image'=>$dir.$fileName));
imagedestroy($im);
}
}
public function phpcaptcha($textColor,$backgroundColor,$imgWidth,$imgHeight,$noiceLines=0,$noiceDots=0,$noiceColor='#000000')
{
/* Settings */
$text=$this->random();
$font = './font/monofont.ttf';/* font */
$textColor=$this->hexToRGB($textColor);
$fontSize = $imgHeight * 0.75;
$im = imagecreatetruecolor($imgWidth, $imgHeight);
$textColor = imagecolorallocate($im, $textColor['r'],$textColor['g'],$textColor['b']);
$backgroundColor = $this->hexToRGB($backgroundColor);
$backgroundColor = imagecolorallocate($im, $backgroundColor['r'],$backgroundColor['g'],$backgroundColor['b']);
/* generating lines randomly in background of image */
if($noiceLines>0){
$noiceColor=$this->hexToRGB($noiceColor);
$noiceColor = imagecolorallocate($im, $noiceColor['r'],$noiceColor['g'],$noiceColor['b']);
for( $i=0; $i<$noiceLines; $i++ ) {
imageline($im, mt_rand(0,$imgWidth), mt_rand(0,$imgHeight),
mt_rand(0,$imgWidth), mt_rand(0,$imgHeight), $noiceColor);
}}
if($noiceDots>0){/* generating the dots randomly in background */
for( $i=0; $i<$noiceDots; $i++ ) {
imagefilledellipse($im, mt_rand(0,$imgWidth),
mt_rand(0,$imgHeight), 3, 3, $textColor);
}}
imagefill($im,0,0,$backgroundColor);
list($x, $y) = $this->ImageTTFCenter($im, $text, $font, $fontSize);
imagettftext($im, $fontSize, 0, $x, $y, $textColor, $font, $text);
imagejpeg($im,NULL,90);/* Showing image */
header('Content-Type: image/jpeg');/* defining the image type to be shown in browser widow */
imagedestroy($im);/* Destroying image instance */
if(isset($_SESSION)){
$_SESSION['captcha_code'] = $text;/* set random text in session for captcha validation*/
}
}
/*for random string*/
protected function random($characters=6,$letters = '23456789bcdfghjkmnpqrstvwxyz'){
$str='';
for ($i=0; $i<$characters; $i++) {
$str .= substr($letters, mt_rand(0, strlen($letters)-1), 1);
}
return $str;
}
/*function to convert hex value to rgb array*/
protected function hexToRGB($colour)
{
if ( $colour[0] == '#' ) {
$colour = substr( $colour, 1 );
}
if ( strlen( $colour ) == 6 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
} elseif ( strlen( $colour ) == 3 ) {
list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
} else {
return false;
}
$r = hexdec( $r );
$g = hexdec( $g );
$b = hexdec( $b );
return array( 'r' => $r, 'g' => $g, 'b' => $b );
}
/*function to get center position on image*/
protected function ImageTTFCenter($image, $text, $font, $size, $angle = 8)
{
$xi = imagesx($image);
$yi = imagesy($image);
$box = imagettfbbox($size, $angle, $font, $text);
$xr = abs(max($box[2], $box[4]));
$yr = abs(max($box[5], $box[7]));
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
return array($x, $y);
}
}
?>

GET , will not receive my POST ? PHP

I have created a dynamic signature maker for my online game.
You can create the sig manually via
http://pernix-rsps.com/sig/pcard.php?user=usernamehere
I tried to make a userbox and submit , so that people does not have to visit
http://pernix-rsps.com/sig/pcard.php?user=USERNAME
and edit it, i want it to create the link for them upon entering username
my code for the username box
<center>
<form name="sig" id="sig" method="get" action="pcard.php">
<table border="0">
<tr><td colspan="2"><?php echo isset($_GET["user"])?$_GET["user"]:"";?> </td></tr>
<tr><td width="30">Username</td><td width="249"><input name="username" type="text" id="username" width="150px" placeholder="Username" /> </td></tr>
<tr><td></td><td><input name="btnsubmit" type="submit" id="btnsubmit" title="create sig" /></td></tr>
</table>
</form>
</center>
And then pcard.php
<?php
if (isset($_GET['user'])) {
$image_path = "img/saved_cards/".$_GET['user'].".png";
if (file_exists($image_path)) {
if (time() < filemtime($image_path) + 300) { // every 5 minutes ?
pullFromCache($image_path);
exit;
}
}
generate();
}
function pullFromCache($image_path) {
header("Content-type: image/png");
$image = imagecreatefrompng($image_path);
imagepng($image);
}
function generate() {
$DB_HOST = "localhost";
$DB_USER = "";
$DB_PASS = "";
$DB_NAME = "";
$user = clean($_GET['user']);
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die($con->error);
$res = $con->query("SELECT * FROM hs_users WHERE username='$user'");
if($res->num_rows > 0) {
header("Content-type: image/png");
getSig($res->fetch_assoc());
} else {
header("Content-type: image/png");
$image = imagecreatefrompng('./img/sigbg.png');
$color = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 3, 251, 10, 'Invalid User', $color);
imagepng($image);
}
}
function getSig($row) {
$image = imagecreatefrompng('./img/sigbg.png');
$color = imagecolorallocate($image, 255, 255, 255);
$yellow = imagecolorallocate($image, 255, 255, 0);
$total = getTotalLevel($row);
$combat = getCombatLevel($row);
imagestring($image, 5, 250, 10, ''.$row['username'].'', $yellow);
imagestring($image, 2, 250, 26, 'Exp: '.number_format($row['overall_xp']).'', $color);
imagestring($image, 2, 250, 39, 'Total: '.number_format($total).'', $color);
imagestring($image, 2, 250, 51, 'Pernix-Rsps.com ', $color);
$array = array("Attack", "Defence", "Strength", "hitpoints", "Range", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "pk", "Summoning", "Dungeoneering");
$baseX = 28;
$baseY = 4;
foreach ($array as $i => $value) {
imagestring($image, 2, $baseX, $baseY, ''.getRealLevel($row[''.strtolower($array[$i]).'_xp'], strtolower($array[$i])).'', $color);
$baseY += 15;
if ($baseY > 64) {
$baseY = 4;
$baseX += 45;
}
}
ImagePNG($image, "img/saved_cards/".$row['username'].".png");
imagepng($image);
}
function getTotalLevel($row) {
$total = 0;
$array = array("Attack", "Defence", "Strength", "Hitpoints", "Range", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "pk", "Summoning", "Dungeoneering");
foreach ($array as $i => $value) {
$skillName = strtolower($array[$i]);
$total += getRealLevel($row[$skillName.'_xp'], strtolower($skillName));
}
return $total;
}
function getLevel($exp) {
$points = 0;
$output = 0;
for ($lvl = 1; $lvl <= 99; $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return 99;
}
function getRealLevel($exp, $skill) {
$points = 0;
$output = 0;
$skillId = $skill == "dungeoneering" ? 1 : 0;
for ($lvl = 1; $lvl <= ($skillId == 1 ? 120 : 99); $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return ($skillId == 1 ? 120 : 99);
}
function getDungLevel($exp) {
$points = 0;
$output = 0;
for ($lvl = 1; $lvl <= 120; $lvl++) {
$points += floor($lvl + 300.0 * pow(2.0, $lvl / 7.0));
$output = (int) floor($points / 4);
if (($output - 1) >= $exp) {
return $lvl;
}
}
return 120;
}
function clean($string) {
return preg_replace('/[^A-Za-z0-9 \-]/', '', $string);
}
function getCombatLevel($row) {
$attack = getLevel($row['attack_xp']);
$defence = getLevel($row['defence_xp']);
$strength = getLevel($row['strength_xp']);
$hp = getLevel($row['hitpoints_xp']);
$prayer = getLevel($row['prayer_xp']);
$ranged = getLevel($row['range_xp']);
$magic = getLevel($row['magic_xp']);
$combatLevel = (int) (($defence + $hp + floor($prayer / 2)) * 0.25) + 1;
$melee = ($attack + $strength) * 0.325;
$ranger = floor($ranged * 1.5) * 0.325;
$mage = floor($magic * 1.5) * 0.325;
if ($melee >= $ranger && $melee >= $mage) {
$combatLevel += $melee;
} else if ($ranger >= $melee && $ranger >= $mage) {
$combatLevel += $ranger;
} else if ($mage >= $melee && $mage >= $ranger) {
$combatLevel += $mage;
}
return (int)$combatLevel;
}
?>
upon entering and submiting the username in the box, it just takes you to the pcard.php without image being made
any ideas
You are using the wrong fieldname in your PHP. In your form you use the fieldname username:
<input name="username" ... />
And in your PHP you try to get GET['user']. Change that in GET['username'] and everything should work (the getting the value part that is ;)).

Categories