$_COOKIE['cookiefoo'], try to get a cookie - php

I'm newbie with webapps and PHP.
I'm trying to get a cookie that it's not created yet, I mean, when I try to load a page that looks for a non-existent cookie I get an error, I tried to get rid of this with a try/catch but not success. This this the code I'm trying:
try{
$cookie = $_COOKIE['cookiefoo'];
if($cookie){
//many stuffs here
}
else
throw new Exception("there is not a cookie");
}
catch(Exception $e){
}
How can I achieve this, any ideas, it would be appreciated it.

Use isset to prevent an any warnings or notices from happening if the key is non-existent:
if(isset($_COOKIE['cookiefoo']) && !empty($_COOKIE['cookiefoo'])) {
// exists, has a value
$cookie = $_COOKIE['cookiefoo'];
}
The same can be done with array_key_exists, though I think isset is more concise:
if(array_key_exists('cookiefoo', $_COOKIE) && !empty($_COOKIE['cookiefoo'])) {
// exists, has a value
$cookie = $_COOKIE['cookiefoo'];
}

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?

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

Returning Boolean Value PHP MongoDB

I am trying to implement error proofing to a log in script. But, I cannot get it to work? I have no idea what is going on, or why it doesn't work like I expect it to. I have tried everything, please advise.
This is the method I am calling:
public function i_exist($this_username)
{
//$host_array = null;
//$host_array = $this->collection->findOne(array("Username" => $this_username));
//if ($host_array['Username'] = $this_username)
//{
return true;
//}
//return false;
}
This is how I am calling it:
if (!empty($_POST['Username']))
{
$host = new Host();
$event = new Event();
if ($host->i_exist($_POST['Username']))
{
header("Location: http://www.drink-social.com/error.php?login=duplicate");
}
It is supposed to check the database and see if that username is already in use. But it never directs to the error page? I have even tried commenting everything out and returning true, and returning 1. Nothing?
Any advice?
When you call header(); you will also need to call exit(); otherwise the script continues running.

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.

Checking if a session is active

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?

Categories