views:

118

answers:

2

I know how to read cookies using CGI and Ruby but the problem is, if I try to read cookies.value[0] when it does not exists, it breaks my program. So I need to check if the cookie is there to read first. I can't find this answer anywhere on the internet.

Please help, thank you, Henry.

+1  A: 

The Ruby CGI doc says:

HTTP Cookies are automatically parsed from the request. They are available from the cookies() accessor, which returns a hash from cookie name to CGI::Cookie object.

If that's the case, then the cookies are simply stored in a regular hash. You can use the regular Hash API to check for the presence of the target cookie, including Hash.key?():

if cgi.cookies().key?("mycookie")
  p "Cookie value is #{cgi.cookies()["mycookie"].value}"
else
  p "Cookie does not exist."
end
Craig Walker
Would it be possible to show me a snippet of code to check if a cookie called 'mycookie' exists? I know in PHP you can use something like if(isset[cookiename])Thanks for the answer
Henry
I actually was writing one up while you left that comment :-)
Craig Walker
FYI: I wrote this example up freehand; I haven't actually ran it. It should be close enough to get you going, but be on the lookout for (minor) errors.
Craig Walker
A: 

Hey Craig, for some reason It won't let me comment again so I have to leave an answer to my own question, I think it's because I've booted in to Ubuntu to test the code. It works great by the way! thank you so much.

I'm using a piece of code so when someone logs in, my ruby creates a cookie and then if the cookie exists, my website doesnt show a log in form, but a welcome 'username' instead.

I have this problem, which is, it detects the cookie fine if all the files are in the CGI bin which is where the cookie is created, but if I try to detect my cookie from another folder, it just doesn't ever seem to register it is there. Do you know why? I have a feeling it is something to do with the cookie path :(

Henry
Yup, cookie path and/or domain sound likely. You should probably post another question (with sample code) to handle that issue.
Craig Walker
Ok, all wrapped up thanks to your first code. It was the path. Thanks again, at least I can go to bed knowing I have learnt something today!
Henry