Create a cookie with cookielib

John J. Lee jjl at pobox.com
Sat Feb 10 07:31:09 EST 2007


I'm going to post this if it kills me (this was my first response in
this thread, my normal newsfeed has gone bad so can't post
reliably...)

Alessandro Fachin <Alessandro.Fachin at gmail.com> writes:

> Hi, i am trying to forge a new cookie by own with cookielib. But i don't
> still have success. This a simply code:
> 
> import cookielib, urllib, urllib2
> login = 'Ia am a cookie!'
> cookiejar = cookielib.CookieJar()
> urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
> values = {'user':login}
> data = urllib.urlencode(values)
> request = urllib2.Request("http://localhost/cookie.php", data)
> url = urlOpener.open(request)
> print url.info()
> page = url.read(500000)
> print page
> print cookiejar
> 
> the output of this is:
> 
> Date: Sat, 03 Feb 2007 10:20:05 GMT
> Server: Apache
> X-Powered-By: PHP/5.1.6
> Set-Cookie: user=Alex+Porter; expires=Sat, 03-Feb-2007 11:20:05 GMT
> Content-Length: 11
> Connection: close
> Content-Type: text/html; charset=UTF-8
> 
> Array
> (
> )
> <cookielib.CookieJar[<Cookie user=Alex+Porter for localhost.local/>]>

So the server has sent you a cookie back, and cookielib accepted it.

Success!

What your PHP program prints out is information about cookies that
were received *from* the browser (or from your script, in this case).
It does not print information about cookies that it is sending *to*
the browser.  Your PHP program is not a time machine, so it can't
print out information about a cookie that was *not there* in the
request you sent.  And the cookie was not there in the request you
sent because the server hadn't sent the cookie yet!

Send a second request (either in the same run of your program, or by
saving and loading the cookies), and you should see a cookie sent back
to the server (and then printed out by your PHP script in the response
you get back).  Web sites and web applcations sometimes use a trick
like a using a redirect or "Refresh" to get the browser to send a
second request, so that they get the cookie they set sent back to the
server again, without the user needing to perform any second action.

Also note that saving and loading cookies with cookielib will by
default drop "session cookies", unless you explicitly ask otherwise.


John




More information about the Python-list mailing list