Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Should be on the top if you will be using the session variables below
- session_start();
- if(!isset($_SESSION['logged_in']) || empty($_SESSION['logged_in']))
- {
- // If user is not authenticated redirect to authentication page
- if (!$_SESSION['logged_in'])
- header("Location: localhost/login.htm");
- }
- // Now we check if the form information are sent, if not why bother connecting to the database in the first place
- if (isset($_POST['username']) && isset($_POST['password']))
- {
- if (!empty($_POST['username']) && !empty($_POST['password'])
- {
- // Trim removes the white spaces from the beginning and end | mysql_real_escape_string Saves your ass from injections
- $varUsername = mysql_real_escape_string(trim($_POST['username']));
- $varPassword = md5(mysql_real_escape_string(trim($_POST['username'])));
- // ^^ The best practice would be to put create a function that will clean your $_POST data
- /*
- * Database connection variables go here: | Although usually it's better to have an other script outside that will make the connections
- * Just incase you want to move from development to online publishing you wouldn't have to write these variables and change them in each
- * and every page of your script!
- */
- $dbHost = "localhost";
- $dbUser = "webuser";
- $dbPass = "";
- $dbDatabase = "mydatabase";
- $db = mysql_connect($dbHost, $dbUser, $dbPass) or die("Error connecting to database.");
- mysql_select_db($dbDatabase, $db) or die("Coudln't select the databse.");
- // It's usually a good practice to store your sql statements in a variable
- $m_query = "SELECT userName, userPass FROM users WHERE userName='$varUsername' AND userPass='$varPassword'";
- $result = mysql_query($m_query, $db);
- // Making sure the query was processed correctly and returned an identifier
- if ($result)
- {
- if ($mysql_num_rows($result) > 0)
- {
- while($row = mysql_fetch_assoc($result)
- {
- // Set the session variables
- $_SESSION['username'] = $row['user'];
- $_SESSION['logged_in'] = true;
- }
- // Successful login code will go here...
- echo 'Success!';
- }
- else
- {
- echo 'Invalid username and Password!';
- }
- }
- }
- }
- else
- {
- echo 'Authentication error: Invalid username\password';
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement