Checking if a session is active - php

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.

$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 :)

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

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?

Related

PHP SESSION variable troubles

I'm sorry to trouble you, I have tried my best to solve this but I am not sure where I am going wrong and I was wondering if someone out there would be willing to help!
Basically, I am having some issues with $_SESSION variables; I would like for each occasion that a visitor came to the page that they would be shown a different content message.. The below code, when first landing on a page will seem to skip the first "content1", and will display "content2" instead, then "content3" after another revisit. I've put in an unset call, which eventually sends it there, am I not using _SESSIONS correctly?
I'm not sure how the session variable was assigned to 1, for it to land correctly in the if===1 statement without it first returning the original "content1"
if (empty($_SESSION)) {
session_start();
}
if (!isset($_SESSION['content'])) {
$content = "content1";
$_SESSION['content'] = 1;
return $content;
}
elseif ($_SESSION['content'] === 1) {
$content = "content2";
$_SESSION['content'] = 2;
return $content;
}
elseif($_SESSION['content'] === 2) {
$content = "content3";
unset($_SESSION['content']);
return $content;
}
Apologies for babbling or whether this was a simple fix / misunderstanding on my part. It's caused quite a headache!
Many thanks.
-edit-
This is a function that is called from within the same class, it has not gone through a loop anywhere either..
You are only calling session_start(); if the session has not been created.
What about the other times, when it's 1, or 2?
Call session_start(); regardless of your if (empty($_SESSION)) { statement
You should always use the session_start() function. If a session exists, it will continue it, otherwise it will create a new session.
Your code can then be simplified to the following:
// Start/Resume session
session_start();
// Get content
function display_message()
{
if ( ! isset($_SESSION['content']))
{
$_SESSION['content'] = 1;
}
if ($_SESSION['content'] == 1)
{
++$_SESSION['content']; // Increment session value
return 'Content #1';
}
elseif ($_SESSION['content'] == 2)
{
++$_SESSION['content']; // Increment session value
return 'Content #2';
}
elseif ($_SESSION['content'] == 3)
{
unset($_SESSION['content']); // Remove session value
return 'Content #3';
}
}
// Display content
echo display_message();
However, if someone visits your page a fourth time, they will be shown the first message again (because the session value is no longer tracking what they've been shown).
Perhaps this sort of functionality might be handled better with by using a cookie to track this information?

Check result of PHP include

I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.

An Include inside an if statement in Joomla-PHP

Im adding php inside an article using DirectPHP plugin.
My goal is to create a script that will include a file with text when the user has member = true; and when not to not show anything.
I have added this piece of code in a module in the top next to the logo:
<?php
if ($user =JFactory::getUser()->guest)
{
$member = false;
echo "Welcome guest, sign up and read nice quotes";
}
else
{
$member = true;
$user =& JFactory::getUser();
echo "Welcome " . $user->username;
}
?>
I have set member = true; now that the person has signed in. If he isnt signed in its on false.
Then inside the article I have:
<?php
if ($member == false)
{
$file = file_get_contents ('quotes/quotes.html');
echo $file;
}
?>
<hr id="system-readmore" />
<?php
if ($member == true)
{
include_once JPATH_SITE.'/quotes/random.php';
echo ShowQuotes();
}
?>
I cant find the problem making this not run. The quotes are shown for both $member = false; and $member = true; Are includes always being parsed despite the if statement? Same goes for file_get_contents? I tried to see if the $member declaration from the header is being kept within the parsing and wrote:
<?php
if ($member = true)
{
echo "Logged in";
}
?>
and it worked good so the problem is within the include_once and file_get_contents, I tried to pinpoint it as much as I can.
Thanks in advance for your help!
This is probably your issue:
if ($member = true)
{
echo "Logged in";
}
This is always assigning the value of true to $member.
Also here:
if ($user =JFactory::getUser()->guest)
You might have the same assignment problem (not sure if you intended to set $user and do a conditional at one here.
I might suggest getting in the habit of writing condditionals like this:
if (true === $member) { ... }
By inverting the order of the items, if you ever accidentally type = instead of == or ===, then you will get an error, instead of having the code silently perform unexpectedly.
You seem to have a scope issue here: you are declaring $member in a module, but $member won't be available to the article: and php will evaluate ($something == false) to always succeed if $something is undefined, if you want to check if a variable is really false you need to use ($something===false). Read more here: http://www.php.net/manual/en/language.types.boolean.php
That being said, since there is no real overhead to JFactory::getUser()->guest, just use that as well in you article!
btw, enable notices in your php configuration (either on screen or to a log file) and make sure you read that as you develop, it will tell you whatever is wrong, developing without seeing the errors is a guessing game, you can only bang your head against the wall so many times... you eventually need to switch on the light :-)

What is the proper way to test CodeIgniter session variable?

Take the following code snippet. What is the best way to test to make sure the session variable isn't empty?
<?php if ($this->session->userdata('userID')) {
$loggedIn = 1;
}
else {
$loggedIn = 0;
} ?>
If later in my script, I call the following, the first prints properly, but on the second I receive Message: Undefined variable: loggedIn
<?php echo $this->session->userdata('userID'));
echo $loggedIn; ?>
I've tried using !empty and isset, but both have been unsuccessful. I also tried doing the if/then statement backwards using if (!($this->session->userdata('userID')), but no dice. Any thoughts?
Try doing the following instead:
<?php
$loggedIn = 0;
if ($this->session->userdata('userID') !== FALSE) {
$loggedIn = 1;
}
?>
If the error continues, you'll need to post more code in case you're calling that variable in another scope.
If your aim is to see whether or not the session variable 'userID' is set, then the following should work:
$this->session->userdata('userID') !== false
Why don't you create a boolean field in your session called is_logged_in and then check like:
if(false !== $this->session->userdata('is_logged_in'))
if($this->session->userdata('is_logged_in')) {
//then condition
}
This is the proper way to test!

cookie won't set

This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.

Categories