Page 1 of 1

Cookies will not set

Posted: Sat Jun 19, 2004 2:19 am
by javman
I have the following code which will not work
<?php
echo "Hello World";
$string_name = "highspeed";
$string_value ="test";
$expiry_info = time() +40000;
setcookie($string_name, $string_value, $expiry_info);
?> the hello world works but it will not set a cookie.
If I use Cold Fusion the cookie sets right away.
Why will the php cookie not set?

Thanks very much for any help as this is my first PHP code.

Posted: Sat Jun 19, 2004 2:24 am
by feyd
try moving the echo line after setcookie()..

Posted: Sat Jun 19, 2004 9:34 am
by javman
That worked --!!thanks
However I am still confused. When i used the code alone without any html it works now. But when I use the php code in a PLAIN html page named
faith.php it will not set a cookie. This is confusing. And frustrating.

Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PHP Trial</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?php 
$string_name = "highspeed"; 
$string_value ="test"; 
$expiry_info = time() +40000; 
setcookie($string_name, $string_value, $expiry_info); 
echo "Hello World";
?> 
</body>
</html>
feyd|use

Code: Select all

tags when posting code please.[/color]

Posted: Sat Jun 19, 2004 11:42 am
by feyd
you are printing information, in this case HTML prior to the cookie getting set. Read the tutorial (in the Tutorials section) about header errors..

Posted: Sat Jun 19, 2004 11:53 am
by Joe
Header errors are very irratating especially when you are new to PHP. Try this:

Code: Select all

<?php
$string_name = "highspeed";
$string_value ="test";
$expiry_info = time() +40000;
setcookie($string_name, $string_value, $expiry_info);
echo "Hello World";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PHP Trial</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
HTML CODE HERE. NOT THE COOKIE SET. IT WOULD RESULT IN A HEADER ERROR AS  THERE IS OUTPUT BEEN GIVEN!
</body>
</html>
Take feyd's suggestion and goto the tutorials section!


All the best



Joe 8)

Posted: Sat Jun 19, 2004 7:05 pm
by javman
Many thanks
Actually that is what I did to get it working. but I did not know why it would not work . Your comments have been very helpful.

Posted: Sat Jun 19, 2004 8:29 pm
by tim
ob_start();

:wink:

Posted: Sat Jun 19, 2004 8:33 pm
by feyd
...is a crutch.