tags:

views:

40

answers:

3

I am building a captcha class. I need to store the generated code in a PHP session. This is my code so far:

<?php

class captcha
{
    private $rndStr;
    private $length;

    function generateCode($length = 5)
    {
        $this->length = $length;
        $this->rndStr = md5(time() . rand(1, 1000));
        $this->rndStr = substr($rndStr, 0, $this->length);

        if(session_id() != '')
        {
            return "session active";
        } else {
            return "no session active";
        }
    }
}

?>

And using this code to check:

<?php

include('captcha.class.php');
session_start();

$obj = new captcha();
echo $obj->generateCode();

?>

But it doesn't output anything to the page, not even a PHP error. Does someone know why this is? And is there a better way I can check if I've started a session using session_start()?

Thanks.

A: 
$this->rndStr = substr($rndStr, 0, $this->length); 
        return $rndStr;  //You return before the if statement is processed
        if(session_id() != '') 
        { 
            return "session active"; 
        } else { 
            return "no session active"; 
        } 

Answer in commented code above

Edit: And you changed your question and removed the return line, not nice for people bothering to answer :)

Jonas B
A: 

i was testing your class, seems ok here, got session active on page, maybe you want to try this line :

include(dirname(__FILE__).'/captcha.class.php');
Puaka
A: 

You do have an error, so I suggest checking your error reporting level and display errors setting - lots of short tutorials on how to do that.

Notice: Undefined variable: rndStr in /home/eric/localhost/test.php on line 12

Of course this is because you wrote $rndStr instead of $this->rndStr.

When I ran your code, aside from the error, I saw the expected output.

session active

Are you able to successfully output to the browser in other scripts?

erisco