Simple PHP Login

First off let me say I’m a noob and I know this isn’t very secure but,
I have a very simple php login script…

$username = “admin”;
$password = “admin”;

if($_POST[‘username’] != $username || $_POST[‘password’] != $password)
echo “contact form”;
echo “html website”;

My issue is when the page refreshes or the user is sent to a different page (ie. to delete file or upload file) and php sends them back, they need to login again. How can I get around this. I’ve tried to learn sessions and cookies, but it doesn’t seem to work for me. Is there a way other than sessions and cookies? or am I just doing it wrong?

Thank you in advance for you help

without seeing all your code I can’t help you any more then with this:

$username = “admin”;
$password = “admin”;

//checks if there is an open session called ‘login’
if(isset($_SESSION[‘login’])) {

//redirect or an include goes here
//this is what happens if there is a login session

} else {

//your test to see if the username and password match if statement
if($_POST['username'] != $username || $_POST['password'] != $password) {
	echo "contact form";
} else {
	//a session called 'login' is started
	$_SESSION['login'] = "yes";
	echo "html website";


it at least shows you how sessions can be used. If this doesn’t help then please post some more code e.g. index.php

I will try this later, but for now, how long will this session last?

I would also need a logout.php page to kill the session if the user wants to right?

Thanks for your speedy reply!

yes, logout is pretty simple:

you can unset the specific session used to test if the user is logged in

<?php session_start(); //unset the session you want unset($_SESSION['login']); header("Refresh: 0; URL=index.php"); ?>


or you can destroy all session variables:

<?php session_start(); session_destroy(); header("Refresh: 0; URL=index.php"); ?>


as for how long a session will last, I think 24 minutes is default.

Sorry, but I have one last question.

How does $_SESSION[‘login’] know which variables to keep?

Does a session store all variables? Or how does it know to keep the username and password.

Thanks for all your help.

when you create a session you tell it what value to hold (if any)

in the example Maas did below the session holds the value of ‘yes’
[php]//a session called ‘login’ is started
$_SESSION[‘login’] = “yes”;[/php]

you could however use anything you like:
[php]$_SESSION[‘username’] = $username;
$_SESSION[‘firstname’] = ‘fred’;
$_SESSION[‘email’] = $row[‘email’];
you can even use arrays if you wish.

hope that helps

Alright I think I got it now. I need to save 2 session variables,
$_SESSION[‘username’] = $username;
$_SESSION[‘password’] = $password;

Thanks for your help guys. I’ll probably be back with other questions.

Worked like a charm :smiley:

Thanks guys!

Sponsor our Newsletter | Privacy Policy | Terms of Service