I hope you are doing great,
I'm making this website with login accounts apparently, I have registered my users in a local database and in a server database. My HTML/PHP code doesn't show any errors when I run it.I have checked my DB connection. it's correct. The website allows me to sign in with any user and password. It doesn't seem to validate my entered data properly. Although I checked my SQL command.
I wonder if you could help me with this guys. You are the best! :)
thanks in advance, Cheers
here is a useful piece of my code:
My header - Header.php:
<html>
<?php
/* static $called = FALSE;
if (!$called)
{*/
session_start();
/*$called = true;
}*/
include_once 'debugging.php';
?>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div >
<dt id="navbar1" class ="navbar">
Home
Upload Videos
</dt>
</div>
<?php
if (isset($_SESSION['logged'])) {
echo '<div class="right navbar" id = "navbar2">
Log out
<p class = "right">/</p>
Edit Account
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square"
height="42" width="42" class = "right"/>
</div>';
} else {
echo '<div class="right navbar" id = "navbar2">
Login
<p class = "right">/</p>
Sign Up
</div>';
}
?>
Progress - Feedback:
Ok guys, I tried what you told me to do. It started to make me sign in automatically. Probably the session['logged'] variable declaration is considered to be true. I set it to be true only if the user login from the login page. but it is not functioning in that way.
Here is my login page code:
<?php
include_once 'Header.php';
?>
<div id="container">
<br>
<?php
/*
if($_DEBUG)
{
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
}
$page_title = 'Login';/* */
//in this page we do things slightly differently - the code for validation
and displaying messages is done
//before we display the form
echo '<div id = "div_1"><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="index.php" method="post">
<label>UserName<br>
<span class="small">enter your username</span>
</label>
<input type="text" name="UserName" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="TRUE">
</form>
</div>
</div>';
if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not
copied multiple times
require_once('LoginFunctions.php');
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the
values in the array to $check and $data
list($check, $data) = checkLogin($_POST['UserName'],
$_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time()+ 900 ) ; //cookie
expires after 15 mins
setcookie('LName', $data['LName'], time() + 900 ) ;
//
//use session variables instead of cookies
//these variables should now be available to all pages in the
application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['UserName'] = $data['UserName'];
//to enable $_SESSION array to be populated we always need to call
start_session() - this is done in header.php
//print_r is will print out the contents of an array
print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in
Loginfunctions.php to give absolute path for required page
$_SESSION['logged'] = TRUE;
//this version of the header function is used to redirect to
another page
header("Location: $url");//since we have entered correct login
details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
//echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br
/>';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
<?php
include 'Footer.php';
?>
See the notes section of the session_start documentation. Revise your code as follows:
<?php
// Start the session before ANY output.
// Start the session always - there's little / no value to only starting sometimes.
session_start(); ?>
<html>
<?php
/* static $called = FALSE;
if (!$called)
{*/
/*$called = true;
}*/
include_once 'debugging.php';
?>
<head>
session_start must run before any output is sent to the browser. Additionally, there's no value in having it in an if statement, so keep it simple and put it where it runs consistently before any output.
Related
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.
I am trying out a php sample code given here: https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php
This gives a log in form, where you can register username password and then log in with a registered user. A welcome page is only visible after you have logged in, and the welcome page shows the specific username of the currently logged in account.
I am trying to modify the welcome.php given in the above link, to add a data entry form that will save some personal data like name and age to a mariadb database. Here is my version of the welcome.php file:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$uname=htmlspecialchars($_SESSION["username"]);
$name = "";
$age = 0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
// */
// /*
$tempvar = trim($_POST["name"]);
// $tempvar='sdsd';
var_dump($tempvar);
if($tempvar == "")
echo $tempvar.' found';
// */
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
</p>
<p>Enter your data here:</p>
<!-- <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> -->
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="save" value="submit">
<!-- <input type="submit" class="btn btn-primary" value="submit"> -->
</form>
</body>
</html>
If I understand this correctly clicking the submit button should generate a post message which should be captured by the php script at the beginning of the file. This much is happening, but I cannot display the content of the text box given by <input type="text" name="name">. The var_dump($tempvar); in the php code at the beginning comes up with String(0) "". I have tried moving the php code to a separate file (as given here in insert.php) instead of attempting to process the post message in the same file, but I am getting the same result. I am not getting any errors.
How do I access the contents of the text box in the post message handler? I am testing this in XAMPP on Windows 10.
Did the example with the login work correctly? This would prove that POSTing data works.
Which version of PHP are you using? There was a feature called register_globals up to 5.4.0 which allowed accessing POST data via named variables. Since you are setting $name = "" this could overwrite your data. I would take it out at that position anyway (use an else clause if necessary). If you have register_globals active either update PHP or turn it off to avoid confusion.
The next step to debug the issue is to print the whole array of $_POST like mentioned here but more pretty
if($_SERVER["REQUEST_METHOD"] == "POST"){
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
This will show you what values were actually POSTed.
Same can be done with the $_SERVER array like this
echo '<pre>';
print_r($_SERVER);
echo '</pre>';
die();
$uname=htmlspecialchars($_SESSION["username"]);
The die() command will halt execution so you need to remove it when you want the script to continue.
Your code works fine for me. I ran it in my system, it shows the submitted name with the var_dump i.e. string(18) "Md Shabbir Hossain".
There are some flaws that I would fix.
Initial user get to Welcome.php.
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$uname=htmlspecialchars($_SESSION["username"]); //username is not defined or it does not exists yet.
$name = "";
$age = 0;
if($_SERVER["REQUEST_METHOD"] == "POST"){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
// */
// /*
$tempvar = trim($_POST["name"]);
// $tempvar='sdsd';
var_dump($tempvar);
if($tempvar == "")
echo $tempvar.' found';
// */
}
I would do this:
<?php
// Initialize the session
session_start();
//Check if the user already logged.
if(!isset($_SESSION["loggedin"])){
//Redirect
header("location: login.php");
exit;
}
// Check if post to login is submitted
if(isset($_POST['save'])){
// /*
echo '<script language="javascript">';
echo 'alert("submit button clicked")';
echo '</script>';
$uname = '';
//Check if Username is submitted
if(isset($_POST['username'])){
$_SESSION["username"] = $_POST['username'];
$uname=htmlspecialchars($_SESSION["username"]);
}
$name = "";
$age = 0;
//For test
var_dump($_POST[]);
}
I'm having a problem with my school project. I've asked both my teacher and classmates for help but none of them doesn't know what to do.
I've made a browser based game, and obviously it needs to have users. And this is where the problem is.
When i log in and proceed to the authenticate page, it extracts info from POST just fine, but when i insert the info into SESSION in authenticate and then go to the homepage index, it refuses to get the SESSION information and i just get an error.
NOTE, design2.php doesnt have anything to do with the log in process.
Here's the code:
Login.php
<?php
include_once'design2.php';
?>
<div id="center">
<form method="POST" action="authenticate.php">
User Name <input id="input" type="text" name="player" size="21">
Password <input id="input" type="password" name="password" size="21">
<br>
<input type="submit" value="Login" name="submit">
<br><br>Not Registered? <a id='underlinelink' href='register.php'>Register</a>
Authenticate.php
<?php
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
{
$player=$_POST['player'];
$password=$_POST['password'];
$player=strip_tags($player);
$password=strip_tags($password);
$password=md5($password);
$query = "select name, password from players where name='$player' and password='$password'";
$result = mysql_query($query) or die("Could not query players");
$result2 = mysql_fetch_array($result);
if ($result2)
{
$_SESSION['player'] = $player;
echo "<big>Logged in successfully<br>";
echo "<A id='underlinelink' href='index.php'>Continue</a></big>";
}
else
{
echo "<big>Wrong username or password.<A id='underlinelink' href='login.php'>Try Again</a></big>";
}
}
?>
</div>
Design.php (This is on every single webpage on my site)
<?php
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
if(isset($_SESSION['player']))
$player = $_SESSION['player'];
else
echo "could not logg in, <a href='login.php'>Go back</a>";
exit;
$playerinfo="SELECT * from players where name='$player'";
$playerinfo2=mysql_query($playerinfo) or die("could not get player stats!");
$playerinfo3=mysql_fetch_array($playerinfo2);
?>
Please help, i really need to get this done before its due.
You need to create or resume the session before you write into it. So in your Authenticate.php where you do $_SESSION['player'] = $player;, create a session first exactly as you do it in your other files. Something like that
Authenticate.php
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
// Rest of your code
// ...
if ($result2)
{
$_SESSION['player'] = $player;
// and so on...
Also, as #DamienLegros noted in his answer, you should always have the session_start() statement as early as possible in your code, i.e. as one of the first statements, so you make sure no output has been made before it's started. Otherwise you'll start getting errors stating that headers has already been sent.
Your session_start() must be BEFORE any output
<?php
session_start();
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
...
...
...
note: add session_start(); at the top of your Authenticate.php page
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 months ago.
I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).
I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.
That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).
So how do I redirect the user from one page to the next?
What options do I have? Also, what is the best practice in these instances?
EDIT: Here's my entire login.php page:
<?php
session_start();
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Sprout</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'>
</head>
<body>
<div class='box'>
<form action='login.php' method='post'>
Name<br /> <input type='text' name='username' class='form'/><br />
Password<br /> <input type='password' name='password' class='form'/>
<input type='submit' value='Login' class='button' />
</form>
</div>
</body>
</html>";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
$dbname = "database";
mysql_select_db($dbname);
$query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query) or die ("Failed Query of " . $query);
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
}
?>
You could use a function similar to:
function redirect($url) {
header('Location: '.$url);
die();
}
Worth noting, you should them with a die() or exit() function to prevent further code execution.
Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.
You can conditionally redirect to some page within a php file....
if (ConditionToRedirect){
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php");
exit();
}
else{
// do something
}
That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?
This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).
Another option (not a good one though!) would be outputting JavaScript to redirect:
<script type="text/javascript">location.href = 'newurl';</script>
header won't work for all
Use below simple code
<?php
echo "<script> location.href='new_url'; </script>";
exit;
?>
Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.
Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:
if(isset($_POST['mySubmit'])) {
// the form was submitted
// ...
// perform your logic
// redirect if login was successful
header('Location: /somewhere');
}
// output your stuff here
You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.
The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.
If the login is valid you'll redirect using the "header" function.
Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.
<?php
ob_start();
if (FORMPOST) {
if (POSTED_DATA_VALID) {
header("Location: https://www.yoursite.com/profile/");
ob_end_flush();
exit;
}
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>
firstly create index.php page and just copy paste below code :-
<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
<legend>
<icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
</legend>
<div class="control-group">
<label class="control-label" for="inputPassword">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
<input class="input" type="text" name="username" id="username" placeholder="Username" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-password icon-cream"></icon>
</span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
</div>
</div>
</div>
<div class="control-group signin">
<div class="controls ">
<input type="submit" class="btn btn-block" value="Submit" />
<div class="clearfix">
<span class="icon-forgot"></span>forgot password
</div>
</div>
</div>
</form>
/*------------------after that ----------------------*/
create a login_check.php and just copy paste this below code :-
<?php
session_start();
include('conn.php');
<?php
/* Redirect browser */
header("location:index.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
if(count($_POST)>0)
{
$result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["user_id"] = $row[user_id];
$_SESSION["username"] = $row[username];
$session_register["user_id"] = $row[user_id];
$session_register["username"] = $row[username];
}
else
{
$_SESSION['msg']="Invalid Username or Password";
header("location:index.php");
}
}
if(isset($_SESSION["user_id"]))
{
header("Location:dashboard.php");
}
?>
/*-----------------------after that ----------------------*/
create a dashboard.php and copy paste this code in starting of dashboard.php
<?php
session_start();
include('conn.php');
include('check_session.php');
?>
/*-----------------------after that-----------------*/
create a check_session.php which check your session and copy paste this code :-
<?php
if($_SESSION["user_name"])
{
?>
Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to Logout.
<?php
}
else
{
header("location:index.php");
}
?>
if you have any query so let me know on my mail id farjicompany#gmail.com
Although not secure, (no offense or anything), just stick the header function after you set the session variable
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
header('Location: /profile.php');
On click BUTTON action
if(isset($_POST['save_btn']))
{
//write some of your code here, if necessary
echo'<script> window.location="B.php"; </script> ';
}
----------
<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>';
$gourl='http://stackoverflow.com';
echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';
exit;
?>
----------
Just like you used echo to print a webpage. You could use also do the same with redirecting.
print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>
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)