Hi there What's the best way to create a login page? I want to add the basic 'username' and 'password' field and a 'submit' button to my web page. * login page - once I someone logs in then they can view the closed off web page. Many thanks in advance CHEERS
When you want to secure a page in PHP all you need to do is use sessions. A basic protection without using a database would be this code: Login.php <?php ob_start(); session_start(); # Set login username $username = 'Username Here'; # Set login password $password = 'Password here'; # Set protected area url $protected = 'Protected area page'; # Do not edit below if(!isset($_SESSION['logged_in'])) { // Display the HTML login form if(!isset($_POST['login'])) { ?> <form action="" name="login" method="post"> <p>Username: <input type="text" name="username"/></p> <p>Password: <input type="password" name="password"/></p> <p><input type="submit" name="login" value="Login"/></p> </form> <?php }else{ if($_POST['username']!=$username||$_POST['password']!=$password) { echo '<p>Wrong password</p>'; echo '<p><a href="login.php">Continue.</a></p>'; }else{ # Set session $_SESSION['logged_in']=1; # Redirect to protected area header('Location:'.$protected); } } }else{ echo '<p>You are already logged in, <a href="login.php?b=logout">logout</a>.</p>'; } # Logout if($_GET['b']=='logout') { session_destroy(); header('Location:login.php'); } ?> PHP: I just wrote this in the quick reply, haven't tested it but all you need to do is copy this code and paste it into a file and save it as login.php When you want to secure a page add this code to the very top of the document. ob_start(); session_start(); if(!isset($_SESSION['logged_in'])) { header('Location:login.php'); } PHP: Hope this helps you to get what you need, there's a great deal of room for improvement in this but it should get you started. Thanks, Glen
Hey Huggy, I tried for hours and still couldn't get it right (frustrating!!). Will keep searching until I find a solution. Thanks
Hey Huggy, I forgot to mention that I was using it inside a CMS. But its OK now, I found a module that works, well only half of it . Thanks for the help though
you can just insert this line above each php page.. <?php $username = 'username'; $password = 'password'; if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || (($_SERVER['PHP_AUTH_USER'] != $username) && ($_SERVER['PHP_AUTH_PW'] != $password))) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; } ?> PHP: from there you can customize it..