Cookie set but not show on another page php - php

I have a login page when I login, process page sets a cookie and I want to use this cookie to auto login the next time. Cookie is set on browser and I can see it but when I want to use it on login page cookie is empty (browser still has it and I can see it)
Browser : mozilla
Directories :
index.php (login page) --> in root /
include-function --> /functions/include-function.php
form-process.php --> /functions/form-process.php
I turned on output buffering of php.ini
Notice : this post edited after answers
This is my login page:
<?php
require("./functions/include-function.php");
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./style/form.css">
<script type="text/javascript"src="./js/form.js">
</script>
<title></title>
</head>
<body>
<div class="wrapper">
<div class="container">
<h1>Welcome</h1>
<form class="form" method="get" action="./functions/form-process.php">
<input type="text" placeholder="Username" name="username">
<input type="text" placeholder="Username" name="username" value="<?php print_r($_COOKIE); ?>">
<input type="password" placeholder="Password" name="password">
<button type="submit" id="login-button" name="submit" value="submit">Login</button>
</form>
</div>
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
This is my process page:
<?php require("./include-function.php"); ?>
<?php
if (isset($_GET['submit'])) {
$username = $_GET['username'];
$pass = $_GET['password'];
$message = validation_form($_GET);
$value = 45;
$cookieName = "us";
if ($username == "vahid#gmail.com" && $pass == "123456" && empty($message)) {
$expired = time() + (60 * 60 * 24 * 1);
setcookie($cookieName,$value,$expired);
// redirect_to("http://www.youtube.com/");
print_r($_COOKIE);
}else{
redirect_to("../index.php");
}
}
?>
and this is my function file:
<?php
function redirect_to($location){
header("Location:". $location);
exit;
}
function validation_form($value=[]){
$message = [];
// Field must not Empty
// trim() so empty space not count
$username =trim($value['username']);
$password =trim($value['password']);
if (!isset($username) || $username==="" || empty($username)
|| !isset($password) || $password==="" || empty($password)) {
$message['validation'].="Username and Password must not empty";
}
// Length Check
$max = 20;
$min = 3;
if (strlen($username) > $max || strlen($password) > $max) {
$message['validation'].= "Password Or Username Must not more than 20 character";
}
if (strlen($username) < $min || strlen($password) < $min) {
$message['validation'].= "Password Or Username Must not less than 3 character";
}
// Type Check
if (!is_string($password)) {
$message['validation'].= "Password Must be Number";
}
//Preg_match
if (!preg_match("/#/",$username)) {
$message['validation'].= "Your username is your email ";
}
return $message;
}
?>

So if I understand correctly you want make a login page in wich when you enter username and password value, next time you refresh the page you are already logged in? or you want to make form sticky and maintain the value inserted before?
BTW if login script isn't in the same folder of the action form script you don't see the cookie in login script because by default the browser send the cookie only at page in folder or subfolder of the script that set the cookie, the action form script in this case.
So first of all set $path = "/" and put it as setcookie argument,
for tell to browser : "send the cookie at every script in the domain or subdomain"
Another point is, as other already told you in the comments, that setcookie modify the header, and all header changes must be done before any output, and in your case you output a whitespace before setting the cookie.
If you need to output something before, you can use the output buffer's functions, whit wich you can buffering all output before the header and send it only after the header is set. see more on https://www.php.net/manual/en/book.outcontrol.php.
Tough i think you make this page for "try'n", don't implement a login like this in real case of use.
Because you are passing username and password in http request that are in readable format.
Use php session and hashed field in a database for store client data in efficient and more safe way,
and to allow user access page more easily, make a sticky form, injecting in field value the value in stored variable, not printing the entire array that storing them.
Hope this may help!

Related

PHP Session Issue when trying to create a login and register system

I am currently in the process of developing a browser based game in php to test myself, and unfortunately I am having trouble with sessions. The pages seem to all just go blank if i set session include in the header, but then it doesn't redirect to membersarea.php when a user logs in using the form (form works i think). I may be doing all this wrong
header.php
<?php
include 'inc/conf.php';
?>
<!DOCTYPE html>
<head>
<title>Mineshaft Online | Free to play Browser MMORPG</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<?php
if(isset($_SESSION['username'])) {
?>
<div class="navigation">
<ul>
<li>Dashboard</li>
<li>Mineshaft</li>
<li>Smeltery</li>
<li>Blacksmith</li>
<li>Settings</li>
<li>Logout</li>
</ul>
</div>
<?php
} else {
?>
<div class="navigation">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
</ul>
</div>
<?php
}
?>
<div class="main-content">
and here is the login.php
<?php
include 'inc/conf.php';
include 'header.php';
if(isset($_POST['submit'])){
// Escape special characters in a string
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// If username and password are not empty
if ($username != "" && $password != ""){
// Query database to find user with matching username and password
$query = "select count(*) as cntUser from users where username='".$username."' and password='".$password."'";
$result = mysqli_query($conn, $query); // Store query result
$row = mysqli_fetch_array($result); // Fetch row as associative array
$count = $row['cntUser']; // Get number of rows
if($count > 0){
$_SESSION['username'] = $username;
header('location: membersarea.php');
} else {
echo "Error! Invalid username and password.";
}
}
}
?>
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text" class="textbox" id="username" name="username" placeholder="Username" />
</div>
<div>
<input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="submit" value="Submit" name="submit" id="submit" />
</div>
</div>
</form>
Here is the 'inc/session.php' file
<?php
session_start();
if(!isset($_SESSION["username"])) {
header("Location: login.php");
exit();
}
?>
It sounds like the inc/session.php file isn't included at any point in your project. If you want to use sessions, all the scripts using them must start with the session_start() function, and that, before you start to write any html in your page.
That being said, I'm tempted to assume that you've made a little mistake, writing 'inc/session.php' instead of 'inc/config.php' file, which is indeed loaded in your scripts.
I see two things that you should check:
In your 'login.php' file, you include the 'inc/config.php' as well as the 'header.php' file (which already includes 'inc/config.php'). That might be a problem, because you will then start your sessions two times.
In your 'inc/config.php' file (again, assuming that this is the 'inc/session.php' that you wrote), you start the sessions, and immediately say "if the session 'username' doesn't exist, then we redirect to login.php", which would be a problem if you don't have your 'username' session created before... this would do a redirection loop and your web browser should stop and display a message explaining so.
Other than that, make sure that your server has the sessions activated, you could write a simple script (with nothing else in the file, to keep it simple) like this:
<?php session_start(); $_SESSION['test'] = 'it works!'; ?>
Run the script once, then change the same file to:
<?php session_start(); if(isset($_SESSION['test'])) { echo $_SESSION['test']; } else { echo 'The SESSION test has not been set'; } ?>
And see what your script say.

How to prevent user from bypassing php authentication

We call it html1 for simplicity.
When a user goes to html1, there's a login2.php login page to enable access to client.php which is the hidden page.
It then goes to checklogin.php...if the password and user name matches...it then goes to the hidden client.php page...if not..it goes back to homepage.
The user has to login to be able to view the contents of hidden client.php page.
However the user can access client.php by typing in ..../client.php on the address bar...therefore bypassing the auth page and rendering it useless. I can just type servername/client.php...and it still shows me the contents of client.php...but I want client.php...to be private!
How do I prevent this from happening?
thanks.
first login page...
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<table>
<form method="post" action="checklogin2.php">
<div id="name">User Id: <input type="text" name="****"></div>
<div id="password">Password: <input type="password" name="*******"></div>
<div class="button"><input type="submit" value="Login"></div>
</form>
</table>
</body>
</html>
then it goes to....
checklogin2.php
<?php
$*** = $_POST['****'];
$***** = $_POST['***'];
if($uid == '****' and $***** == '*****')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
else
{
header("location:index.html");
}
?>
Then it goes to...
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
header("location:client.php");
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
In the beginning of your every page you have to check if user is authorized.
On checklogin.php if user entered correct login and password, just set something like
$_SESSION['authorized'] = TRUE;
...and on other pages just check if user is authorized:
if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === TRUE) {
// Alright, let's show all the hidden functionality!
echo "Psst! Hey! Wanna buy some weed?";
} else {
// User is not authorized!
header('Location: login.php');
exit();
}
Note that you don't have to mess with cookies, session IDs etc. - just add session_start() before everything and freely use $_SESSION var.
This is the main pro of sessions (and $_SESSION variable in particular): you can remember some data among different pages on same website.
All pages has to check if the user is authed. I would recommend using objects, and always inherit a class that checks this for you. It's not fun to have the same code everywhere, doing the same thing.
if($_SERVER["PHP_SELF"] == '/yourpagefolder/yourpage.php' && !isset($_SESSION['login_user'])){
header('location: login.php');
}

Code for a simple singin page using php

I am new to programming. I need a simple login page code for PHP which displays an error message in the same page for incorrect login details and redirected to the account page incase of correct login details. The code should remember the activity and redirect to the account page of the user if he has closed the page without login out. Any help would be deeply appreciated.
Log in page
<html>
<head>
<title>Login</title>
</head>
<h3>Login Page</h3>
<form action="trylog.php" method = "post"><!--action redirects to trylog.php -->
<label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br /><!--username label defined -->
<label for="password">Password:</label> <input type="password" id="password" name="password"><br /><br /><!--password label defined -->
<button type = "submit">Login</button><!--submit button defined -->
</form>
</html>
Account page
<html>
<title>Login</title>
<body>
<?php
session_start(); //resumes previous session based on indentifiers from POST attribute in login.php
$usr = "admin"; //usr keyword defined
$psw = "password"; //psw keyword defined
$username = '$_POST[username]';
$password = '$_POST[password]';
//$usr == $username && $psw == $password
if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password"))
//checking for correctness of username and password
{
echo "password accepted";
$_SESSION['login']=true;
//successful login confirmation
echo "<br><a href='http://localhost/login/login.php'>Logout</a>";
}
else
{
echo "incorrect login";
//incorrect login message
}
session_destroy(); //destroys session
?>
</body>
</html>
Thanks
Navaneeth
session_start has to be before output, so move that before <html> etc. (output is a space before <?php too. <?php has to be the first sequence in your code.
what you meant by $psw and $usr variables? You have them in form, delete them.
When you work with variables, don´t use quotes - you can use double-quotes marks, not single. Better is to use no quote marks: $username = $_POST['username'];. On the other hand, the key should be in quote marks, elsewhere you work with undefined constant username - if constant doesn´t exists, PHP work with the same string.
Condition on line 12 will never be true because you test there a SESSION which hasn´t been set before. You set this session on your line 16, but only if this session already exists (line 12). It´s logical nonsense :-)
Why you create variables $username and $password when you doesn´t work with them?
Before you work with $_POST, lines 9 and 10, you must check if the form was sent, so if (isset($_POST['username'])) {}.

Easy way to password-protect php page

I have a page I want to password-protect. I've tried doing HTTP authentication, but for some reason it doesn't work on my hosting. Any other quick (and easy) way to do this? Thanks!
Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.
Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.
They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.
If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin"
&& $pass == "admin")
{
include("secure.html");
}
else
{
if(isset($_POST))
{?>
<form method="POST" action="secure.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?}
}
?>
This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.
First prepare your password salts file:
hash_generate.php:
<?php
$user = "Username"; // please replace with your user
$pass = "Password"; // please replace with your passwd
// two ; was missing
$useroptions = ['cost' => 8,];
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions);
$pwoptions = ['cost' => 8,];
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);
echo $userhash;
echo "<br />";
echo $passhash;
?>
Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"
.htaccess
deny from all
Now no one can peek into the hash. Next up is your index.php:
index.php:
<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
$user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
$pass = $_POST['pass'];
}
$useroptions = ['cost' => 8,]; // all up to you
$pwoptions = ['cost' => 8,]; // all up to you
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions); // hash entered pw
$hasheduser = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass = file_get_contents("stuff/pass.txt"); // and our stored password
if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {
// the password verify is how we actually login here
// the $userhash and $passhash are the hashed user-entered credentials
// password verify now compares our stored user and pw with entered user and pw
include "pass-protected.php";
} else {
// if it was invalid it'll just display the form, if there was never a $_POST
// then it'll also display the form. that's why I set $user to "" instead of a $_POST
// this is the right place for comments, not inside html
?>
<form method="POST" action="index.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php
}
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";
if (isset($_COOKIE['PrivatePageLogin'])) {
if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>
<!-- LOGGED IN CONTENT HERE -->
<?php
exit;
} else {
echo "Bad Cookie.";
exit;
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['user'] != $username) {
echo "Sorry, that username does not match.";
exit;
} else if ($_POST['keypass'] != $password) {
echo "Sorry, that password does not match.";
exit;
} else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
header("Location: $_SERVER[PHP_SELF]");
} else {
echo "Sorry, you could not be logged in at this time.";
}
}
?>
And the login form on the page...
(On the same page, right below the above^ posted code)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
Here's a very simple way. Create two files:
protect-this.php
<?php
/* Your password */
$password = 'MYPASS';
if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
// Password not set or incorrect. Send to login.php.
header('Location: login.php');
exit;
}
?>
login.php:
<?php
/* Your password */
$password = 'MYPASS';
/* Redirects here after login */
$redirect_after_login = 'index.php';
/* Will not ask password again for */
$remember_password = strtotime('+30 days'); // 30 days
if (isset($_POST['password']) && $_POST['password'] == $password) {
setcookie("password", $password, $remember_password);
header('Location: ' . $redirect_after_login);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Password protected</title>
</head>
<body>
<div style="text-align:center;margin-top:50px;">
You must enter the password to view this content.
<form method="POST">
<input type="text" name="password">
</form>
</div>
</body>
</html>
Then require protect-this.php on the TOP of the files you want to protect:
// Password protect this content
require_once('protect-this.php');
Example result:
After filling the correct password, user is taken to index.php. The password is stored for 30 days.
PS: It's not focused to be secure, but to be pratical. A hacker can brute-force this. Use it to keep normal users away. Don't use it to protect sensitive information.
Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.
If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd
Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.
If you want to use sessions the following is the best way to go:
# admin.php
session_start();
if(!$_SESSION["AUTH"])
require_once "login.php";
# Do stuff, we are logged in..
# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
$_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.
if($_SESSION["AUTH"])
require_once "admin.php";
This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.
I would simply look for a $_GET variable and redirect the user if it's not correct.
<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
header('Location: http://www.staggeringbeauty.com/');
}
?>
Now, if this page is located at say: http://example.com/secrets/files.php
You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)
A simple way to protect a file with no requirement for a separate login page - just add this to the top of the page:
Change secretuser and secretpassword to your user/password.
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!($user == "secretuser" && $pass == "secretpassword"))
{
echo '<html><body><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
Username: <input type="text" name="user"></input><br/>
Password: <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Login"></input>
</form></body></html>';
exit();
}
This helped me a lot and save me much time, its easy to use, and work well, i've even take the risque of change it and it still works.
Fairly good if you dont want to lost to much time on doing it :)
http://www.zubrag.com/scripts/password-protect.php
</html>
<head>
<title>Nick Benvenuti</title>
<link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
<link rel="stylesheet" href="CSS/main.css">
<link rel="stylesheet" href="CSS/normalize.css">
<script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
<script type="text/javascript">
function tester() {
window.location.href="admin.php";
}
function phpshower() {
document.getElementById("phplogger").classList.toggle('shower');
document.getElementById("phplogger").classList.remove('hider');
}
function phphider() {
document.getElementById("phplogger").classList.toggle('hider');
document.getElementById("phplogger").classList.remove('shower');
}
</script>
<?php
//if "login" variable is filled out, send email
if (isset($_REQUEST['login'])) {
//Login info
$passbox = $_REQUEST['login'];
$password = 'blahblahyoudontneedtoknowmypassword';
//Login
if($passbox == $password) {
//Login response
echo "<script text/javascript> phphider(); </script>";
}
}
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
<form method="post">
Password: <input name="login" type="text" /><br />
<input type="submit" value="Login" id="submit-button" />
</form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>
Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.
/*PHP CONTENT STARTS HERE*/
.hider {
visibility:hidden;
display:none;
}
.shower {
visibility:visible;
}
#phplogger {
background-color:#333;
color:blue;
position:absolute;
height:100%;
width:100%;
margin:0;
top:0;
bottom:0;
}
/*PHP CONTENT ENDS HERE*/
This stores the password in history after login!
You can specify a password in your php code so only users that have the secret url can access:
mywebsite.com/private.php?pass=secret
in your login-protected file:
<?php
if(isset($_GET["pass"]) && $_GET["pass"]=="secret"){
//put your code here
}
else{
echo "you're not allowed to access this page";
}
?>

Cookies are Not Being Set Properly in PHP Script

Im very new in php and try to use cookie but it is not woking in my site, can anyone guide me please , what is going wrong in my code:
<?php
session_start();
?>
<script>
function Redirect(url)
{
location.href = url;
}
</script>
<?php
define('_VALID_ACCESS', true);
include_once "includes/connect.php";
include_once "includes/login.php";
if(empty($_POST['loginname']) || empty($_POST['password']))
{
$msg = "User or password is empty";
}
else
{
if(login($_POST['loginname'], $_POST['password']) == true)
{
$usern = $_POST['loginname'];
session_register('loginname');
$loginname = $usern;
sleep(1);
if(activestatus($_POST['loginname'], $_POST['password']) == true)
{
$usern = $_POST['loginname'];
session_register('loginname');
$loginname = $usern;
sleep(1);
$hour = time() + 3600;
setcookie("ID_my_site", $_POST['loginname'], $hour);
setcookie("Key_my_site", $_POST['password'], $hour);
$test = $_COOKIE["ID_my_site"];
$msg = "<script> Redirect ('home.html?testname=".$test."')</script>";
//header("Location: home.html");
}
else
{
$msg = "<script> Redirect ('valid.php?testname=".$usern."')</script>";
}
}
else
{
$msg = "<font color=red>User or Password is wrong</font>";
}
}
echo '<div id="divTarget">' . $msg . '</div>';
?>
<link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection">
<link rel="stylesheet" href="css/blueprint/print.css" type="text/css" media="print">
<link rel="stylesheet" href="css/blueprint/ie.css" type="text/css" media="screen, projection">
<body>
<div class="container" id="login_container">
<form id="login" action="action.php" method="post" name="loginform" >
<fieldset id="login_screen" style="width:350px">
<label id="login_label" for="login">User Login </label>
<br><br>
<label for="login">Email Address</label>
<input type="text" name="loginname" id="loginname" value="email#coolmates.com">
<p id="space"><label for="password">Password</label>
<input type="password" id="password" name="password" value="********" ></p>
<input type="checkbox">Keep me signed in until i signout
<p id="test"><input type="submit" value="Submit"></p>
<a href="forgetpassword.html">Forgot
your password</a> |<span id="free">Not a member?</span>Sign up<blink><span id="free">Free</span></blink>
</p>
</fieldset>
</form> </div>
</body>
Turn on display_errors and set your error_reporting to E_ALL and you should see an error message about 'headers already sent' - you have to call setcookie() BEFORE ANY HTML IS SENT. From php.net/setcookie:
setcookie() defines a cookie to be
sent along with the rest of the HTTP
headers. Like other headers, cookies
must be sent before any output from
your script (this is a protocol
restriction). This requires that you
place calls to this function prior to
any output, including and
tags as well as any whitespace.
In the code block that you posted this bit:
<script>
function Redirect(url)
{
location.href = url;
}
</script>
Is being output directly to the browser well before you ever attempt to set the cookies.
Your two possibilities would be to use output buffering so that you output everything at the very end or to switch to a method where all of your processing code is executed first in one script and there you set $_SESSION and cookie values and then include a second script at the tail end of the first that contains the code to be output to the browser.
Try this (specifying the root of your site) :
setcookie("ID_my_site", $_POST['loginname'], $hour,'/');
or try this (adding quotes to your loginname) :
setcookie("ID_my_site", "$_POST['loginname']", $hour,'/');
1st you don't need session_register, you can just do.
Since session_register is the preferred method since 4.1.0 and deprecated as of PHP 5.3
$_SESSION["loginname"] = $_POST["loginname"]
2nd if you are going to use sessions, your flow could be better, since this does not work.
$_SESSION["foo"] = 1;
header("Location: stuff.php");
Then you can't view the session data in stuff.php. You could either send the user to the main page, and do the authentication there, and if it passes then you just continue on with the loading of the main page, and if it doesn't, then you send the user back to the login page like this.
if($_SESSION["authenticated"] == 0)
{
header("Location: login.php");
die();
}
Also you should not be storing a password is cookie data -- this is a big security No-No!!!
If you want to do something like that set a unique - random - identifier that changes when they login and use that instead (you should still MD5 it)

Categories