Displaying generated PNG in PHP? - 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);

Related

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'

Retrieving data from the session

How to retrieve data in .htm page using twig.
public function onRun()
{
$captchaImagePath = '/Applications/MAMP/htdocs/install-master/storage/app/uploads/captcha/';
Log::info($captchaImagePath);
$captchaImageUrl = '/Applications/MAMP/htdocs/install-master/storage/app/uploads/captcha/';
$captchaFontPath = '/Applications/MAMP/htdocs/install-master/storage/app/uploads/fonts/verdana.ttf';
$val = array(
'word_length' => 5,
'word' => '',
'img_path' => $captchaImagePath,
'img_url' => $captchaImageUrl,
'font_path' => $captchaFontPath,
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$img_path=$captchaImagePath;
$img_url=$captchaImageUrl;
$font_path=$captchaFontPath;
$captcha = $this->create_captcha($val,$img_path,$img_url,$font_path);
$url = Request::url();
if (ends_with($url, ['.html', '.htm']))
{
$url = str_replace(['.html', '.htm'], '', $url);
return Redirect::to($url, 301)->with($captcha);
}
Log::info($url);
Log::info($captcha);
}
the function in same file public function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
// Log::info($data);
// Log::info($img_path);
// Log::info($img_url);
// Log::info($font_path);
if(!isset($data['word_length']))
{
$length=5;
}
else
{
$length=$data['word_length'];
}
//Log::info($length);
$defaults = array('word' => '', 'word_length' => $length,'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
// Log::info($defaults);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
// Log::info( $$key);
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
// Log::info($img_path); Log::info($img_url);
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! is_dir($img_path))
{
return FALSE;
}
if ( ! is_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
//$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < $word_length; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 232, 244, 252);
$text_color = imagecolorallocate ($im, 57, 136, 190);
$grid_color = imagecolorallocate($im, 220, 239, 253);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
}
now how to use captcha which is image + word created through above function in
default.htm
<span id="captcha">
<img src="{{captcha.image}}" width="150" height="30" style="border:0;" alt=" " /> </span>
the file created by above function saves in given path bt how to show that image when form appears...................................................................................................................................................
First you need to correct your syntex, to flash session while redirecting you need to use
with('name', 'value')
so you need to use
if (ends_with($url, ['.html', '.htm']))
{
$url = str_replace(['.html', '.htm'], '', $url);
return Redirect::to($url, 301)->with('captcha', $captcha); // <- correct this
// $this->create_captcha() must return string value
// here $captch seems object/image so you should not pass objects in session
}
instead I guess you need to pass some random value
$someRandomValue = 'blabla';
$val = array(
'word_length' => 5,
'word' => '', // <----------------- something here [$someRandomValue]
'img_path' => $captchaImagePath,
'img_url' => $captchaImageUrl,
'font_path' => $captchaFontPath,
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
and then pass it like
with('captcha', $someRandomValue)
and now in other place you can get it by
$captchaValue = session::get('captcha')
so this $captchaValue will be same as $someRandomValue
in short in last you need user input as text/string and compare with $captchaValue (this will be from session) to validate it
if any doubt please comment.

Keep PNG transparency when extracting images from SWF with PHP

I am trying to extract images from SWF. The following code works, but when extracting png images, the background becomes opaque. Any help would be great; this is what I have:
class SWFextractImages {
private $swf;
private $jpegTables;
private $shipID;
public function doExtractImages($shipID, $b) {
$this->shipID = $shipID;
$this->swf = new SWF($b);
$this->jpegTables = '';
foreach ($this->swf->tags as $tag) {
if($tag['type']==6){
if($this->defineBits($tag)){
continue;
}
}
}
}
private function defineBits($tag) {
$ret = $this->swf->parseTag($tag);
$imageData = $ret['imageData'];
if (strlen($this->jpegTables) > 0) {
$imageData = substr($this->jpegTables, 0, -2) . substr($imageData, 2);
}
if($ret['characterId']==5){
$filename = sprintf('images/'.$this->shipID.'.jpg', $ret['characterId']);
file_put_contents($filename, $imageData);
return true;
}
}
}
Not sure if this will help, but this extracts other data from SWF file too. Here's the source code.
The function defineBits is only for jpg images
For png try this:
private function defineBitsLossless($tag) {
$ret = $this->swf->parseTag($tag);
$bitmapFormat = $ret['bitmapFormat'];
$bitmapWidth = $ret['bitmapWidth'];
$bitmapHeight = $ret['bitmapHeight'];
$pixelData = $ret['pixelData'];
$img = imageCreateTrueColor($bitmapWidth, $bitmapHeight);
if ($bitmapFormat == 3) {
$colorTable = $ret['colorTable'];
// Construct the colormap
$colors = array();
$i = 0;
$len = strlen($colorTable);
while ($i < $len) {
$red = ord($colorTable[$i++]);
$green = ord($colorTable[$i++]);
$blue = ord($colorTable[$i++]);
$colors[] = imageColorAllocate($img, $red, $green, $blue);
}
$bytesPerRow = $this->alignTo4bytes($bitmapWidth * 1); // 1 byte per sample
// Construct the image
for ($row = 0; $row < $bitmapHeight; $row++) {
$off = $bytesPerRow * $row;
for ($col = 0; $col < $bitmapWidth; $col++) {
$idx = ord($pixelData[$off++]);
imageSetPixel($img, $col, $row, $colors[$idx]);
}
}
} else if ($bitmapFormat == 4) {
$bytesPerRow = $this->alignTo4bytes($bitmapWidth * 2); // 2 bytes per sample
// Construct the image
for ($row = 0; $row < $bitmapHeight; $row++) {
$off = $bytesPerRow * $row;
for ($col = 0; $col < $bitmapWidth; $col++) {
$lo = ord($pixelData[$off++]);
$hi = ord($pixelData[$off++]);
$rgb = $lo + $hi * 256;
$red = ($rgb >> 10) & 0x1f; // 5 bits
$green = ($rgb >> 5) & 0x1f; // 5 bits
$blue = ($rgb) & 0x1f; // 5 bits
$color = imageColorAllocate($img, $red, $green, $blue);
imageSetPixel($img, $col, $row, $color);
}
}
} else if ($bitmapFormat == 5) {
$bytesPerRow = $this->alignTo4bytes($bitmapWidth * 4); // 4 bytes per sample
// Construct the image
for ($row = 0; $row < $bitmapHeight; $row++) {
$off = $bytesPerRow * $row;
for ($col = 0; $col < $bitmapWidth; $col++) {
$off++; // Reserved
$red = ord($pixelData[$off++]);
$green = ord($pixelData[$off++]);
$blue = ord($pixelData[$off++]);
$color = imageColorAllocate($img, $red, $green, $blue);
imageSetPixel($img, $col, $row, $color);
}
}
}
imagePNG($img, sprintf('images/img_%d.png', $ret['characterId']));
imageDestroy($img);
}
You can read more, understand more and use more from here

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

Single Digit Captcha Match, 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.

Categories