jason.claude Posted May 14, 2007 Share Posted May 14, 2007 Just wanted to ask about an issue dealing with cookies, basically My local Apache server using php 5.2 on Mixrosoft windows XP has problems with keeping the cookies. I have set the variables in php.ini according to the manual and have created a script that i know works since it behaves like it should my on my web host however when i visit my script on my local host the cookie is written to the destination folder, but the moment I visit another page the file cannot seem to read the cookie or it is deleted. I was thinking of either asking someone to email me a copy of a working php.ini that can handle cookies( most probably the quickest way for me to figure out what is wrong) or someone work out the proble from the info given. Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted May 14, 2007 Share Posted May 14, 2007 There is nothing in the php.ini that can control cookies. All cookies are handled by the client (web browser, eg IE, FF, Opera etc). Make sure you are setting the cookie correctly in your scripts. The following should do: setcookie("myPHPCookie", "Hello this is a cookie set by PHP", time()+3600); That will set cookie called myPHPCookie with the value "Hello this is a cookie set by PHP" and the cookie will expire after an hour. It is important you set the time parameter (the third parameter of the setcookie function) to a date in the future and not a time from the past. Then when you go to grab the cookie you use $_COOOKIE['cookie_name'] variable, obviously you change cookie_name with your cookie, so for the above example you'll use $_COOKIE['myPHPCookie'] When you set a cookie make sure you are not trying to access the cookie at the same time you set it. Quote Link to comment Share on other sites More sharing options...
jason.claude Posted May 17, 2007 Author Share Posted May 17, 2007 then why does my script work perfectly on my web host, but not on my localhost, that is why I assumed it had something to do with my php settings, another question if the above one has no solution, does Apache handle anything to do with cookies. *my php code to set the cookies is right. ** I also changed my Browsers security settings to see if that was changing the scripts behaviour. Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted May 17, 2007 Share Posted May 17, 2007 Does disabling your firewall help? Perhaps your firewall may be blocking the cookies on localhost. Also could you post a snippet of code of how you set cookies in your script? Quote Link to comment Share on other sites More sharing options...
jason.claude Posted May 18, 2007 Author Share Posted May 18, 2007 already had added localhost and port 25 to the exception list so that should not be the problem... anyway realised that the problem is not the cookies but the session below is my php.ini settings for sessions [session] ; Handler used to store/retrieve data. session.save_handler = files ; Argument passed to save_handler. In the case of files, this is the path ; where data files are stored. Note: Windows users have to change this ; variable in order to use PHP's session functions. ; ; As of PHP 4.0.1, you can define the path as: ; ; session.save_path = "N;/path" ; ; where N is an integer. Instead of storing all the session files in ; /path, what this will do is use subdirectories N-levels deep, and ; store the session data in those directories. This is useful if you ; or your OS have problems with lots of files in one directory, and is ; a more efficient layout for servers that handle lots of sessions. ; ; NOTE 1: PHP will not create this directory structure automatically. ; You can use the script in the ext/session dir for that purpose. ; NOTE 2: See the section on garbage collection below if you choose to ; use subdirectories for session storage ; ; The file storage module creates files using mode 600 by default. ; You can change that by using ; ; session.save_path = "N;MODE;/path" ; ; where MODE is the octal representation of the mode. Note that this ; does not overwrite the process's umask. ;session.save_path = "/tmp" session.save_path = "E:/php/session/" ; Whether to use cookies. session.use_cookies = 1 ;session.cookie_secure = ; This option enables administrators to make their users invulnerable to ; attacks which involve passing session ids in URLs; defaults to 0. ; session.use_only_cookies = 0 ; Name of the session (used as cookie name). session.name = PHPSESSID ; Initialize session on request startup. session.auto_start = 0 ; Lifetime in seconds of cookie or, if 0, until browser is restarted. session.cookie_lifetime = 0 ; The path for which the cookie is valid. session.cookie_path = "C:\Documents and Settings\Sean\Cookies" ;session.cookie_path = "/" ; The domain for which the cookie is valid. session.cookie_domain = ; Whether or not to add the httpOnly flag to the cookie, which makes it inaccessible to browser scripting languages such as JavaScript. session.cookie_httponly = ; Handler used to serialize data. php is the standard serializer of PHP. session.serialize_handler = php ; Define the probability that the 'garbage collection' process is started ; on every session initialization. ; The probability is calculated by using gc_probability/gc_divisor, ; e.g. 1/100 means there is a 1% chance that the GC process starts ; on each request. session.gc_probability = 1 session.gc_divisor = 1000 ; After this number of seconds, stored data will be seen as 'garbage' and ; cleaned up by the garbage collection process. session.gc_maxlifetime = 1440 ; NOTE: If you are using the subdirectory option for storing session files ; (see session.save_path above), then garbage collection does *not* ; happen automatically. You will need to do your own garbage ; collection through a shell script, cron entry, or some other method. ; For example, the following script would is the equivalent of ; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes): ; cd /path/to/sessions; find -cmin +24 | xargs rm ; PHP 4.2 and less have an undocumented feature/bug that allows you to ; to initialize a session variable in the global scope, albeit register_globals ; is disabled. PHP 4.3 and later will warn you, if this feature is used. ; You can disable the feature and the warning separately. At this time, ; the warning is only displayed, if bug_compat_42 is enabled. session.bug_compat_42 = 0 session.bug_compat_warn = 1 ; Check HTTP Referer to invalidate externally stored URLs containing ids. ; HTTP_REFERER has to contain this substring for the session to be ; considered as valid. session.referer_check = ; How many bytes to read from the file. session.entropy_length = 0 ; Specified here to create the session id. session.entropy_file = ;session.entropy_length = 16 ;session.entropy_file = /dev/urandom ; Set to {nocache,private,public,} to determine HTTP caching aspects ; or leave this empty to avoid sending anti-caching headers. session.cache_limiter = nocache ; Document expires after n minutes. session.cache_expire = 180 ; trans sid support is disabled by default. ; Use of trans sid may risk your users security. ; Use this option with caution. ; - User may send URL contains active session ID ; to other person via. email/irc/etc. ; - URL that contains active session ID may be stored ; in publically accessible computer. ; - User may access your site with the same session ID ; always using URL stored in browser's history or bookmarks. session.use_trans_sid = 0 ; Select a hash function ; 0: MD5 (128 bits) ; 1: SHA-1 (160 bits) session.hash_function = 0 ; Define how many bits are stored in each character when converting ; the binary hash data to something readable. ; ; 4 bits: 0-9, a-f ; 5 bits: 0-9, a-v ; 6 bits: 0-9, a-z, A-Z, "-", "," session.hash_bits_per_character = 5 ; The URL rewriter will look for URLs in a defined set of HTML tags. ; form/fieldset are special; if you include them here, the rewriter will ; add a hidden <input> field with the info which is otherwise appended ; to URLs. If you want XHTML conformity, remove the form entry. ; Note that all valid entries require a "=", even if no value follows. url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry" this is my actual code for the cookies <?php function fetchSocket() { global $vData, $dData, $_MIME; if ($conn = @fsockopen("tcp://{$this->parsed['host']}", $this->parsed['port'], $erstr, $errno, 5)) { $status = socket_get_status($conn); if (!$status['blocked']) socket_set_blocking($conn, true); socket_set_timeout($conn, 5); $cookiereq = ""; if ($vData['sp.cookies'] == "true") foreach ($this->cookies as $cooky) if (is_object($cooky)) $cookiereq .= $cooky->makeCookie($this->parsed['host'], $this->parsed['path']); $acceptreq = implode(", ", $this->accept); $lastmodreq = ($this->lastmod) ? "If-Modified-Since: ".date("r", $this->lastmod)."\r\n" : ""; $this->parsed['full'] = str_replace(array("&", " "), array("&", "%20"), $this->parsed['full']); fwrite($conn, "{$this->request} {$this->parsed['full']} HTTP/1.0\r\nHost: {$this->parsed['hostport']}\r\nUser-Agent: {$dData['userAgent']}\r\n{$lastmodreq}{$cookiereq}Accept: {$acceptreq}, */*;q=0.1\r\nAccept-Encoding: gzip\r\n".(($this->referer) ? "Referer: {$this->referer}\r\n": "")."\r\n"); while (!feof($conn) && !$this->status) { $data = fgets($conn, 1024); $this->dataleng += strlen($data); $this->headers[] = $data; $status = socket_get_status($conn); if ($status['timed_out']) $this->status = 2; if (preg_match("/^Docit: Search/", $data)) $this->status = 3; if (preg_match("/^HTTP\/1\.\d ([1-5]\d\d)/i", $data, $code)) { $this->httpcode = (string)$code[1]; if ($this->httpcode{0} != "2" && $this->httpcode{0} != "3") $this->status = 4; if ($this->lastmod && $this->httpcode == "304") $this->status = 1; } if ($vData['sp.cookies'] == "true") { if (preg_match("/^Set-Cookie:\s*([^\r\n]*?)[\r\n]/i", $data, $cooky)) { $cooky =& new Cookie($cooky[1], $this->parsed['host'], $this->parsed['path']); if ($cooky->valid) { reset($this->cookies); while (list($key, $value) = each($this->cookies)) if ($cooky->name == $value->name && $cooky->domain == $value->domain && $cooky->path == $value->path) unset($this->cookies[$key]); if (!$cooky->expired) $this->cookies[] = $cooky; } } } if (preg_match("/^Location:\s*([^\r\n]*?)[\r\n]/i", $data, $location)) { $this->status = 3; if (isset($location[1])) $this->redirect = $location[1]; } if (preg_match("/^Content-Encoding:\s?gzip/", $data)) $this->gzip = true; if (preg_match("/^Content-Type:\s*([^;\r\n]+?)[\s;\r\n]/i", $data, $mime)) { $this->mimetype = $mime[1]; if (in_array($this->mimetype, $this->accept)) { if (preg_match("/charset=\s*([^;\r\n]+?)[\s;\r\n]/i", $data, $charset)) $this->charset = strtoupper($charset[1]); } else { $this->accepted = false; $this->status = 3; } } if (preg_match("/^\r?\n$/", $data)) { if ($this->mimetype && !$this->status) { if (($this->ctype = $_MIME->get_ctype($this->mimetype)) && $_MIME->ctype[$this->ctype]->tofile) { if ($this->into && $_MIME->ctype[$this->ctype]->ready) { if ($pout = @fopen($this->into, "w")) { while (!feof($conn)) { $this->dataleng += strlen($data = fgets($conn, 1024)); fwrite($pout, $data); } $this->intostat = true; fclose($pout); } } } else while (!feof($conn)) $this->body .= fgets($conn, 1024); $this->dataleng += strlen($this->body); $this->body = trim($this->body); } break; } } fclose($conn); } else { $this->status = 6; $this->errstr = "$errno ~ $erstr"; } } } class Cookie { var $name = ""; var $value = ""; var $comment = ""; var $domain = ""; var $maxAge = -1; var $path = ""; var $secure = false; var $version = 1; var $acceptTime; var $valid = true; var $expired = true; //* function Cookie($cookytext, $host, $path) { $host = strtolower($host); $ahost = explode(".", $host); if (count($ahost) > 2) unset($ahost[0]); $this->domain = ".".join(".", $ahost); $this->path = (($slh = strrpos($path, "/")) > 0) ? substr($path, 0, $slh - 1) : $path; $this->acceptTime = time(); $cooky = explode(";", $cookytext); for ($x = 0; $x < count($cooky); $x++) { $cook = explode("=", $cooky[$x], 2); if (isset($cook[1])) $cook[1] = trim(trim($cook[1]), "\""); if ($x == 0) { $this->name = $cook[0]; $this->value = $cook[1]; } else { switch (strtolower($cook[0])) { case "comment": $this->comment = $cook[1]; break; case "domain": $cook[1] = strtolower($cook[1]); if ($cook[1]{0} != "." || $cook[1]{strlen($cook[1]) - 1} == "." || !preg_match("/[^.]\.[^.]/", $cook[1]) || strpos($host, $cook[1]) !== false) { $this->domain = $cook[1]; } else $this->valid = false; break; case "max-age": if ($stamp = strtotime($cook[1])) $this->maxAge = $stamp; if ($this->maxAge < $this->acceptTime) $this->expired = true; break; case "path": if (strpos(strtolower($path), strtolower($cook[1])) === 0) { $this->path = $cook[1]; } else $this->valid = false; break; case "secure": $this->secure = true; break; case "version": $this->version = (int)$cook[1]; break; } } } } function makeCookie($pagehost, $pagepath) { if (preg_match("/".preg_quote($this->domain, "/")."$/", $pagehost)) if (strpos($pagepath, $this->path) === 0) if ($this->maxAge > time() || $this->maxAge == -1) return "Cookie: \$Version=\"{$this->version}\"; {$this->name}=\"{$this->value}\"; \$Path=\"{$this->path}\"\r\n"; return ""; } } ?> I tried a session example from the php manual as below and all that shows is the number 0. <?php session_start(); // Use $HTTP_SESSION_VARS with PHP 4.0.6 or less if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } else { $_SESSION['count']++; } echo $session['count']; ?> refreshed the page while in the session directory and noticed that a new session was created every time I refreshed the page, not sure if that helps... thanks for the help so far Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted May 18, 2007 Share Posted May 18, 2007 Looking at the code you provided for testing sessions. The last line is incorrect: echo $session['count']; It should be this: echo $_SESSION['count']; $session (as you have it) and $_session is not the same as $_SESSION. PHP see's these as completely different variables. Quote Link to comment Share on other sites More sharing options...
jason.claude Posted May 19, 2007 Author Share Posted May 19, 2007 thanks, for that, but my actual code is still not working. The session is still being recreated each time, not keeping the same session, any way I am goint to try php.net to look for any bugs or fixes. I will post here if I find anything. thanks for the help Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted May 19, 2007 Share Posted May 19, 2007 I just looked through your post above which quoted your session configuration in the php.ini. I noticed this: session.cookie_path = "C:\Documents and Settings\Sean\Cookies" Remove that and leave it as the default value which was "/" Save the php.ini and restart Apache. Now retry the session test code you tried earlier. Setting session.cookie_path to "C:\Documents and Settings\Sean\Cookies" will cause your cookie to be invalid and will not work and thus PHP keeps creating a new session file when you refresh the page. Quote Link to comment Share on other sites More sharing options...
jason.claude Posted May 21, 2007 Author Share Posted May 21, 2007 Thanks that worked... ;D, How do mod the topic so that it is resolved. Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted May 21, 2007 Share Posted May 21, 2007 You can click the Topic Solved link, which is just above the Quick Reply box to mark your topic as solved. I have marked it solved it for you. Glad I sorted your cookie problem out. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.