Set cookies in PHP. Urgent, need help!


Dear all,

I’m developing an online reservation system, I’m facing problem to display username (after they were logged-in), here is my coding:

I’ve the following form, for user to input:

Username: Password:

File: authuser.php

//check for required fields
if (!$myusername || !$mypassword) {
header(“Location: ./test2.html”);

//setup names of database and table to use
//$db_name = “sptt”;
$table_name = “pendaftaran”;
//connect to server and select database
$connection = mysql_connect("$host", “$user”, “$password”)
or die(mysql_error());
$db = mysql_select_db($database, $connection) or die(mysql_error());

//build and issue query
$sql = “SELECT * FROM $table_name WHERE
username = ‘$myusername’ AND
password = ‘$mypassword’”;

$result = mysql_query($sql) or die (mysql_error());

//get the number of rows in the result set
$num = mysql_numrows($result);

//print a message and set a cookie if authorized,
//or redirect elsewhere if unauthorized
if ($num != 0) {
$cookie_name = “auth”;
$cookie_value = “ok”;
$cookie_expire = “0”;
$cookie_domain = “”;
$cookie_username = “$myusername”;
$cookie_password = “$mypassword”;
setcookie($cookie_name, $cookie_value, $cookie_expire,
“/” , $cookie_domain, 0);
setcookie($cookie_username, $cookie_password);

 $display_block = "
 <p><strong>Welcome $myusername:</strong></p>
 <li><a href="secretA.php">secret page A</a>

} else {
header(“Location: ./test2.html”);

Secret Area <?php echo "$display_block"; ?> [/code]

File: secretA.php


if($_COOKIE[auth] == “ok”) {

Secret Page A <?php echo "Welcome $user!"; ?> [/code]

What I want is, after user logged-in, their name will display in page secretA.php. If they didn’t logged in, the message will be ‘Welcome Guest’. I think maybe is something wrong in secretA.php. Please help, urgently need your help. Thank you, regards.


First of all: the word ‘urgent’ usually moves the issue down to the bottom of the ‘things-to-do’ list of those who can help. See also How to ask a smart question.

As for your problem: I’d suggest you read up on the syntax of setcookie(), and superglobal variables (or try the Cookies section in the PHP manual).