WeatheRay WeatheRay - 1 year ago 45
HTML Question

Can't set PHP Cookie but copied working code

I have just started building my own website. I'm new to websites in general.

For a few weeks, I have been working on a site for a friend. When I copied the code (and changed some paths and links) to use the framework on my site, it somehow broke the cookie functionality.

I have seen other statements that cookies have to be created at the start of a page, but I am not sure how to do that, in this case. I have a landing page with a call to the content page. The content page calls the verification page which takes care of logging in and cookie. Or, that's how it worked before I copied the site.

I have learned that if I browse to just the login page, not the landing page, it will create a cookie, thereby giving credence to creating the cookie first. It fixes other things, and does not appear as intended, but it works.
If I create the cookie at the top of the landing page, it does get created, but I can't edit it later on, so this doesnt help me.

I found the login code from the internet, complete with cookie creation.
Credit: http://www.zubrag.com/scripts/

<html>
<link rel="icon" type="image/png" sizes="32x32" href="assets/favicon-
32x32.png">
<head>
<title>
Name
</title>
<style>
#centerpct {
height:300px;
margin-top: 50px;
}
td.big {
line-height: 2;
color:black;
}
a.one:link {color:#29282a;}
a.one:visited {color:#29282a;}
a.one:hover {color:#a06e4e;}
</style>
<script language="javascript" type="text/javascript"
src="get_document.js"></script>
</head>
<body style="background-color:#29282a;color:white;">
<div id="centerpct">
<center>
<a href="www.example.com">
<img src="assets/welcome.jpg" height="250px" width="450px">
</a>
</center>
</div>
<hr size=2px; width=75%;>
<center>
<br>
Welcome.
<br />
<br />
<div style="background-color:white;color:orange;padding: 20px
20px;width:500px; border-style: solid; border-width:5px;border-
color:#a06e4e;">
<center>
<?php
//The below line is required to keep OVERLORD in scope
$USE_OVERLORD = 0;
include("minion.php");
?>
</center>
</div>
<br />
</center>
</body>
<footer>
<center><div style="background-color:white;color:orange;padding: 20px
20px;width:500px; border-style: solid; border-width:5px;border-
color:#a06e4e;">
Click <a class="one"; href="www.example.com/justify.php?logout=1"
>HERE</a> to log out.
</div></center>
</footer>
</html>

START MINION PAGE
<?php include("justify.php"); ?>
<script language="javascript" type="text/javascript" src="get_document.js">
</script>
<form name="frmDocument" method="post" action="get_document.php">
<input type="hidden" name="document_name" value="">
<center>Documents</center>
<hr size=2px; width=100%;>
<table>
<tr>
<td class="big">
</td>
</tr>
<tr>
<td class="big">
<a href="#" onClick="GetDocument('test.doc')">test</a>
</td>
</tr>

</table>
</form>
<?php
if($USE_OVERLORD){
?><hr size=2px; width=100%;>
<center>Other Documents (increased access level)</center>
<hr size=2px; width=100%;>
<tr>
<td class="big">
No documents exist at this time.
</td>
</tr>
<?php }
unset($USE_OVERLORD); ?>

<?php


// Add login/password pairs below, like described above
// NOTE: all rows except last must have comma "," at the end of line
// Also denotes as overlord or minion
include("users.php");

// request login? true - show login and password boxes, false - password box
only
define('USE_USERNAME', true);

// User will be redirected to this page after logout
define('LOGOUT_URL', 'example.com');

// time out after NN minutes of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 5);

// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);

##################################################################
# SETTINGS END
##################################################################


///////////////////////////////////////////////////////
// do not change code below
///////////////////////////////////////////////////////

// show usage example
// the ?help is important
if(isset($_GET['help'])) {
die('Include following code into every page you would like to protect, at
the very beginning (first line):<br>&lt;?php include("' .
str_replace('\\','\\\\',__FILE__) . '"); ?&gt;');
}

// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 60);

// logout?
if(isset($_GET['logout'])) {
setcookie("verify", '', $timeout); // clear password;
header('Location: ' . LOGOUT_URL);
exit();
}

if(!function_exists('showLoginPasswordProtect')) {

// show login form
function showLoginPasswordProtect($error_msg) {
?>
<html>
<head>
<title>Please enter password to access this page</title>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</head>
<body>
<style>
input { border: 1px solid black; }
</style>
<div style="width:500px; margin-left:auto; margin-right:auto; text-
align:center">
<form method="post">
<h3>Please enter password to access this page</h3>
<font color="red"><?php echo $error_msg; ?></font><br />
<?php if (USE_USERNAME) echo 'Login:<br /><input type="input"
name="access_login" /><br />Password:<br />'; ?>
<input type="password" name="access_password" /><p></p><input
type="submit" name="Submit" value="Submit" />
</form>
<br />
</div>
</body>
</html>

<?php
// stop at this point
die();
}
}

// user provided password
if (isset($_POST['access_password'])) {

$login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
$pass = $_POST['access_password'];
if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
|| (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) ||
$LOGIN_INFORMATION[$login] != $pass ) )
) {
showLoginPasswordProtect("Incorrect password.");
}
else {
// set cookie if password was validated
setcookie("verify", md5($login.'%'.$pass), $timeout);


//Check if user is supervisor. If so, make a note of it for later.
if (array_key_exists($_POST['access_login'],$LOGIN_OVERLORD)) {
$USE_OVERLORD = 1;}

// Some programs (like Form1 Bilder) check $_POST array to see if
parameters passed
// So need to clear password protector variables
unset($_POST['access_login']);
unset($_POST['access_password']);
unset($_POST['Submit']);
}

}

else {

// check if password cookie is set
if (!isset($_COOKIE['verify'])) {
showLoginPasswordProtect("");
}

// check if cookie is good
$found = false;
foreach($LOGIN_INFORMATION as $key=>$val) {
$lp = (USE_USERNAME ? $key : '') .'%'.$val;
if ($_COOKIE['verify'] == md5($lp)) {
$found = true;
// prolong timeout
if (TIMEOUT_CHECK_ACTIVITY) {
setcookie("verify", md5($lp), $timeout);
}
break;
}
}
if (!$found) {
showLoginPasswordProtect("");
}
}
?>


If I have done something else glaringly wrong, please let me know.

Thank you for the time,
WeatheRay

Answer Source

A typical php file

$ cat htdocs/le.cookie.php
<html>
<head>
<?php

ob_start();

echo 'WOT????' . PHP_EOL;

setcookie('tasty', 'cookie');



echo ob_get_clean();

here is what the output looks like for the browser

$ curl -D- http://sol.lan/le.cookie.php
HTTP/1.1 200 OK
Date: Thu, 27 Jul 2017 15:33:57 GMT
Server: Apache
X-Powered-By: PHP/5.6.30-pl0-gentoo
Set-Cookie: tasty=cookie
Cache-Control: max-age=0, must-revalidate
Expires: Thu, 27 Jul 2017 15:33:57 GMT
Content-Length: 22
Content-Type: text/html; charset=UTF-8

<html>
<head>
WOT????

You can not set the cookie after the script has begun producing output. This is because cookies are set in the HTTP response headers. They come before the HTTP response body.


Here is what you can not do:

<html>
<body>

Hello World
<?php setcookie(...)

Output has already started with <html>.

<?php echo 'foobar'; setcookie(...)

Output started with echo


Here is what you can do:

<?php
ob_start()
?>
<html>
<body>
Hai to yoloz
<?php echo '<p>wot??</p>';

setcookie(...);
echo ob_get_clean();

?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download