Hi Everyone, Hoping someone here can help me fix this problem I have of setting a cookie variable from a databse $id = $row["id"]; variable.

This seems to work fine when using session data, but I am trying to use cookies and I am a bit stuck. . .

here is the code I have been trying with, you will see where I am setting the cookies, but I need to make the cookie variable = $row ["id"]

if ($_POST['sms'] != "") {

	include_once "../includes/config.php";
	// Be sure to filter this data to deter SQL injection, filter before querying database
	$sms = $_POST['sms'];
	 //strip slashes
	$sms = stripslashes($sms);
	 //stripping tags
	$sms = strip_tags($sms);

	$sql = mysql_query("SELECT id FROM minibays WHERE creff='$sms'");
    $numRows = mysql_num_rows($sql);

	if ($sms = "") {
		$msg_to_user = '<br /><br /><h4><font color="#484848">Please enter your secure sms code</font></h4>';
	} else if ($numRows > 0) {
		/*
		Start sessions											
		*/
			$id = $row["id"];
        	//$_SESSION['SESS_MEMBER_ID'] = $id;		   
		   	setcookie("id", "id", time()+86400);
			setcookie("id"," ' . $id . '", time()+86400);
			setcookie("id"," ' . $id", time()+86400);
			setcookie("id"," " . $id . "", time()+86400);
							
			$securecode = $row["securecode"];
			//$_SESSION['SESS_SECURE_CODE'] = $securecode;
			setcookie("securecode"," ' . $securecode . '", time()+86400);
			
			$creff = $row["creff"];
			//$_SESSION['SESS_CREFF'] = $creff;
			setcookie("creff","$creff", time()+86400);
			//$creff = $row["creff"];
			//$_SESSION['SESS_CREFF'] = $creff;
			
		/*
		Login and go to members area											
		*/	
		//header("location: members.php?$_SESSION[id]");
		//header("Location: members.php?id=".$id."");
		header("Location: members.php?id=$id");
		
		exit ();
	} else {

Any help would be great thanks :)

Dani AI

Generated

Short summary and fixes (ties to replies from and ):

You have a few independent issues stopping the cookie from getting the row id. correctly spotted that you were passing a literal string instead of the variable. Two other blockers: the code never fetches the query row (so $row is undefined), and the blank-check uses the assignment operator (so it always makes $sms empty). Also note that the mysql_* API is outdated — use mysqli or PDO and prepared statements to avoid injection.

What to do, in plain steps:

  • Validate and trim the posted sms, then run a prepared query and fetch one row.
  • Check the row exists, cast the id to an integer or string, then call setcookie before sending any output.
  • Use a cookie path of / (as mentioned) and set httponly/secure/samesite flags when appropriate.
  • Prefer storing a server-side session or a random token mapped to the user id rather than placing a raw id in a cookie.

Example (modern, minimal pattern using PDO and secure cookie options):

$stmt = $pdo->prepare('SELECT id, securecode, creff FROM minibays WHERE creff = :c LIMIT 1');
$stmt->execute([':c' => $sms]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
    setcookie(
        'id',
        (string)$row['id'],
        [
            'expires' => time() + 86400,
            'path' => '/',
            'httponly' => true,
            'secure' => true,
            'samesite' => 'Lax'
        ]
    );
    header('Location: members.php?id=' . urlencode($row['id']));
    exit;
}

Quick troubleshooting tips:

  • Cookies set by PHP won’t appear in $_COOKIE until the next request (the Set-Cookie header is sent to the browser).
  • If you get “headers already sent” errors, move cookie/header calls before any output or enable output buffering.
  • Check the browser devtools Network/Storage tabs to confirm the Set-Cookie header and cookie attributes.

Recommended Answers

All 2 Replies

Check line 23: setcookie("id", "id", time()+86400); the second argument, the value, is "id" while it should be $id: setcookie("id", $id, time()+86400);

Heres how i set cookies

setcookie("token", $token, $expire, "/");

The last variable "/" is the path the cookie is available in, which had me confused for awhile when i first got into cookies.

If you set a cookie in a directory called setup, that cookie is only available in that directory and wont exist on http://example.com/ setting the path to '/' makes the cookie available on the whole domain

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.