Jump to content

CAPTCHA PHP Session Error


Go to solution Solved by tryingtolearn,

Recommended Posts

SO I have been developing a log in system and wanted to make my own simple CAPTCHA. I found one on the internet and ported the code across to get started and see how someone had made it. The issue I am having is that the dynamically generated image that I have created it seems is one step ahead of the session variable (the string is generated and then saved into session - then generates the image). But when i echo back the session it is always one step behind the actual image... Anyway here is my code and ask away please :)

<?php

	require('includes/util.inc.php');

	$form = '
		<form action="register.php" method="post">
			<p>username <input type="text" name="username" id="usrinp"></p>
			<p>email <input type="text" name="email" id="emainp"></p>
			<p>password <input type="password" name="password1" id="psw1inp"></p>
			<p>re-enter password <input type="password" name="password2" id="psw2inp"></p>
			<p><img src="captcha.php"/></p>
			<p>captcha <input type="text" name="captcha" id="capinp"></p>
			<p><input type="submit" value="Register" id="subinp"></p>
		</form>
	';

	if(isset($_SESSION['captcha'])) {
		echo $_SESSION['captcha'];
	}

	if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['username']) && !empty($_POST['email'])) {
		if($_POST['captcha'] == $_SESSION['captcha']) {

			$username = $_POST['username'];
			$email = $_POST['email'];
			$password = SHA1($_POST['password1']);
			$password = SHA1($_POST['password2']);

			$q = 'SELECT username FROM users WHERE username = :username';
			$stmt = $pdo->prepare($q);
			$stmt->bindParam(':username', $username);
			$stmt->execute();

				if($stmt->rowCount() > 0) {
					echo "<pre>This username has already been taken</pre>";
				} else {
					$qi = 'INSERT INTO users ( username, password, email ) VALUES ( :username, SHA1(:password), :email )';
				    $query = $pdo->prepare($qi);
				    $result = $query->execute( array( ':username'=>$username, ':password'=>$password, ':email'=>$email ) );

				    if($result) {
				    	header("location:login.php");
						exit;
				    } else {
				      echo '<pre>Error, please try again</pre>';
				    }
				}

		}

	}

	$pageTitle = 'Register';
	include('includes/header.inc.php');
	include('pages/register.html');

?>

<?php

    require('includes/util.inc.php');

    $string = '';
    for ($i = 0; $i < 5; $i++) {
        $string .= chr(rand(97, 122));
    }
    
    $_SESSION['captcha'] = $string;

    $font_path = 'includes/fonts/';

    $captcha_image = imagecreatetruecolor(150, 60);

    $text_color = imagecolorallocate($captcha_image, 0, 0, 0);
    $bg_color = imagecolorallocate($captcha_image, 255, 255, 255);

    imagefilledrectangle($captcha_image, 0, 0, 399, 99, $bg_color);
    imagettftext($captcha_image, 30, 0, 10, 40, $text_color, $font_path . "dashdot.ttf", $_SESSION['captcha']);

    header("Content-type: image/png");
    imagepng($captcha_image);

?>
<?php 

	session_start();

	function class_loader($class) {
		require 'classes/' . $class . '.class' . '.php';
	}

	spl_autoload_register('class_loader');

	$user = (isset($_SESSION['user'])) ? $_SESSION['user'] : null;
	$cat = (isset($_SESSION['cat'])) ? $_SESSION['cat'] : null;

	try {
		$pdo = new PDO('mysql:dbname=phpcat; host=localhost', 'root', '');
	} catch (PDOException $e) {
		$pageTitle = 'Error!';
		include('header.inc.php');
		include('../pages/error.html');
		exit();
	}
Link to comment
https://forums.phpfreaks.com/topic/292201-captcha-php-session-error/
Share on other sites

 

 

the dynamically generated image that I have created it seems is one step ahead of the session variable (the string is generated and then saved into session - then generates the image). But when i echo back the session it is always one step behind the actual image

Not exactly sure I understand what the problem is from this.

 

Do you mean it doesn't display in the form??

Image displays. Let me run through what it would do. So page loaded with random string of 12345 lets say saved to session. The image will display 54321. I refresh the page and then the value of session will be 54321 and the session another random value. The random value seems to always be one step ahead and I have no idea why.

Sorry let me re word that - I confused myself it seems..

 

Image displays. Let me run through what it would do. So page loaded with random string of 12345 saved to $_SESSION. The image will display 54321. I refresh the page and then the value of $_SESSION will be 54321 and the image another random value. This random value on the image will then be the $_SESSION value next time i refresh.

  • Solution

Not sure if I still understand what you mean, Im guessing you want the image and the echoed session to be the same.. if so,

Try moving 

$string = '';
    for ($i = 0; $i < 5; $i++) {
        $string .= chr(rand(97, 122));
    }
    
    $_SESSION['captcha'] = $string;

from your captcha creation page and put it above your form.. 

  • Like 1

the reason you cannot echo the $_SESSION variable when your form is being displayed, and get the correct value, is because the code generating the value in the $_SESSION variable and producing the image is a separate http request from the browser that occurs long (in terms of computer processing) after the php code for your form has ended.

 

why do you want to echo it, on lines 17-19 of your code, which is outside of the form processing code? you can echo it inside your form processing code, which runs on the http request after the form and the image have been displayed.

All I wanted was to have the code similar to the original where all the CAPTCHA was in one file and was called. I was echoing it to illustrate that the values of the $_SESSION were incorrect. This is also the true value of the session as even when putting the image version in it doesn't work (the image and session are not the same).

it's not different sessions. per my reply, you are echoing it in the wrong place in your code -

 

 

why do you want to echo it, on lines 17-19 of your code, which is outside of the form processing code? you can echo it inside your form processing code, which runs on the http request after the form and the image have been displayed.

  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.