Forum Moderators: coopster

Message Too Old, No Replies

If cookie dosen't exist, set cookie

Is this how I do it?

         

Jeremy_H

5:49 pm on Mar 15, 2006 (gmt 0)

10+ Year Member



Hi, I'm trying to set a cookie if the user dosn't already have one.

Would this be the right code to do so?

$user=$HTTP_COOKIE_VARS["user"];
if($user==""){setcookie("user",$username,time()+604800);}

Thanks

StupidScript

5:52 pm on Mar 15, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Pretty good! or maybe:

if(!$user){setcookie("user",$username,time()+604800);}

Jeremy_H

11:47 pm on Mar 16, 2006 (gmt 0)

10+ Year Member



Thanks SS, I really like the alteration you made.

Quick question though. Now I'm finding myself setting a variable with a value a little more complicated.

I set a variable in PHP equal to what I want the cookie to be, and then I have the statement setting the cookie by the name of that new variable I created.

I wanted to be able to reduce my code, so I can just set the cookie directly, without having to make a variable, but my code keeps breaking. Here's what it looks like:

$rand=rand(100,999)."-".substr(ereg_replace("[^0-9]","",$REMOTE_ADDR),-8).substr(time(),-4);
if(!$HTTP_COOKIE_VARS["test"]){setcookie("test",$rand,time()+604800);}

And here's what I'm trying to make it look like:

if(!$HTTP_COOKIE_VARS["test"]){setcookie("test",rand(100,999)."-".substr(ereg_replace("[^0-9]","",$REMOTE_ADDR),-8).substr(time(),-4),time()+604800);}

If anybody has some tips why it's breaking, I would greatly appreciate it. Thanks

Mr_Fern

6:40 am on Mar 17, 2006 (gmt 0)

10+ Year Member



$HTTP_COOKIE_VARS is deprecated, it's better to use $_COOKIE instead. Plus it's a super global, so no need to "global $HTTP_COOKIE_VARS;" inside functions.

Also, regarding scripty's method, that relies on register_globals in the ini file being set to 1, which is considered a security risk, and has been defaulted to 0 in recent versions of PHP.

Best bet is
if (!isset($_COOKIE['user']) ) { setcookie('user',$username,time()+604800); }

Although the {} isn't really needed since it's just one statement after the if.

Mr_Fern

6:45 am on Mar 17, 2006 (gmt 0)

10+ Year Member



I'd like to offer a tip regarding the ereg. Since all you're trying to do is remove the periods from the IP, it would be better to use str_replace('.','',$REMOTE_ADDR) instead, Eregs are CPU intensive, and str_replace does the job, so it's better to use.

I can't call it on the code breaking, but, I think it might be better to do the variable method. It's easier to read your code later that way.

Jeremy_H

3:31 am on Mar 18, 2006 (gmt 0)

10+ Year Member



Mr_Fern,

You gave me some really good tips on how to avoid depreciated code and how to use less CPU intensive code.

Thanks