I have a login script where a page (index.php) can request the user to login (protect.php) however all that I see on index.php is a blank white screen with no source and no error messages. I should at least be seeing login.php to ask the user to log in. This script worked for a few minuets than just decided to stop working
This exact script has worked before in many other web apps that I have created however this one does not work. After hours of debugging I am still unable to find a solution to this problem.
index.php:
<?php
$allow=array('0','1','2');
require("users/protect.php");
?>
<script>window.location="/setup.php";</script>
protect.php:
<?php
session_start();
// --------------------------------THE VARIABLES---------------------------------- //
#include ("config.php");
// ----------------------------------THE CODE ------------------------------------ //
function clearance ($user_value, $pass_value, $level_value, $userlevel_value, $table_value, $column1, $column2, $path) { // Function to see if user can login
$check = mysql_query ("SELECT $userlevel_value FROM $table_value WHERE email='$user_value' AND password='$pass_value'"); // Query to see if user exists
$verify = mysql_num_rows ($check);
$get = mysql_fetch_array ($check);
if (count ($level_value) != 0) { // If the allow array contains userlevels
if (in_array ($get[$userlevel_value], $level_value) && $verify > 0) { // Search allow to see if userlevels match
$_SESSION['username'] = $user_value; // Register sessions
$_SESSION['password'] = sha1 ($pass_value); // sha1 password for extra security
$_SESSION['userlevel'] = $get[$userlevel_value];
}
} else {
if ($verify == 0) { // If attempt fails then redirect to login page
$_SESSION = array();
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit;
}
if ($verify > 0) { // If attempt is good then register the user
$_SESSION['username'] = $user_value;
$_SESSION['password'] = sha1 ($pass_value);
}
}
}
function protect ($level_value, $password_value, $userlevel_value, $table_value, $column1, $path) { // Function to keep pages secure
if (!isset ($_SESSION['username'])) { // If session doesn't exist then get user to login
if (isset ($_POST['username']) && isset ($_POST['password'])) {
$error = "Sorry but your login details were incorrect";
}
$_SESSION = array();
#include ("login.php");
exit;
} else { // If user is logged in check to see if session is valid and that they have the required userlevel
$check = mysql_query ("SELECT $password_value, $userlevel_value FROM $table_value WHERE $column1='$_SESSION[username]'"); // Query to see if user exists
$verify = mysql_num_rows ($check);
$get = mysql_fetch_array ($check);
if ($verify == 0) {
$_SESSION = array();
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit;
}
if ($verify > 0 && count ($level_value) != 0) {
if (!in_array ($get[$userlevel_value], $level_value)) { // Check to see if the users userlevel allows them to view the page
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit; // Ensure no other data is sent
}
}
}
}
if (isset ($_POST['username']) && isset ($_POST['password'])) { // If user submits login information then validate it
clearance ($_POST['username'], $_POST['password'], $allow, $userlevel, $table, $username, $password, $path);
}
protect ($allow, $password, $userlevel, $table, $username, $path);
mysql_close ($link); // Close the database connection for security reasons
// -----------------------------------THE END ------------------------------------ //
?>
Related
I have generated a php file that has information stored in a database. To access this a person must use a login in page.
However, when you are using MAMP how can you prevent someone from accessing the file through writing the IP address and php file name e.g. 123.456.78.00:80/fileone.php. I want this fileone.php to be hidden and for them to only access it through a login page.
Thanks in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: ' . $page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Login check
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true) {
"Your script"
}
If you have a profile for your users, like a normal user = 0 and an admin = 1 you can do it like this
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true && $_SESSION['profile'] == 1) {
"Your script"
}
Set sessions
To set set the sessions to true you need this
if(isset($_POST['submit'])) {
$_SESSION['loggedIn'] = true;
// for set a profile
$_SESSION['profile'] = 1;
}
Maybe I didn't understand you good, but to be sure I will explain something:
You said attached checklogin.php, but you can't use that to deny access for non members. If they know that the file exists, they can type it in the URL and still read fileone.php. The first coding block need to be in your fileone.php.
Session time
Search in your php.ini for 'session.gc_maxlifetime'. There will be a number and that is the time in seconds.
I have a login system for a member/admin site. The login is working perfectly, but I want to verify the user and give error messages if it's not the correct user or password. So far, with what I have, it will not give any error messages although I'm not getting any errors either.
function error_message(){ $error = '';
$loginName = isset($_REQUEST['loginName']) ? $_REQUEST['loginName'] : "";
$password = isset($_REQUEST['password']) ? $_REQUEST['password'] : "";
{$results = connect($loginName);
$loginName === $results['email'];
$passwords = password_verify($password,$results['password']);
if(!$results) {$error = 'Username not found'; echo $error; header ('Location: home.php');} //if no records returned, set error to no username
else //if found {if ((isset($password)) !== (isset($passwords))) //check password, if matched log him in
{ $error = 'Password is wrong'; echo $error; header('Location: home.php');} //if not matched then set error message
}
}
if(isset($error)) {echo $error; }//if there is an error print it, this can be anywhere in the page
}
This is my connection and how it is logging in:
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email ='$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
Login:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/admin/home.php?err=1');
}
if ($loginName === $results['email'] && password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
}
header('Location: /tire/admin/home.php');
}
Wow, that's some nasty code we have here. Let's get started:
Let's first take a look in the connect function:
Gets the row where the email matches the loginName provided.
Return the array with the desired row.
That's correct.
Now let's take a look to the login function:
Retrieves the row where the email matches loginName.
If there is no row (email does not match any user), redirects to home.php of ¿ADMIN? with the variable $err = 1.
Recheck the email (what for?) and verify the password.
If password is correct, it checks permissions and redirects to the correspondent home.php.
Notice that if there is no matches for a permission, it redirects you to admin home.php.
Notice that if the password is incorrect, you do nothing.
I will improve this code:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/error.php?code=1');
}
if (password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
} else {
header('Location: /tire/error.php?code=2');
}
}
And then in error.php (or whatever place you would like to show the errors, it's just an example):
switch($_GET['code']){
case 1:
$error = "Email invalid";
break;
case 2:
$error = "Password invalid";
break;
}
print $error
That being said, I will strongly recommend you to read about exceptions and implement the logic based on that. It's far more clean than the code above, but I didn't want to change your code so drastically.
See: http://php.net/manual/en/language.exceptions.php
Please help me I want my program to choose a site if it has not yet username then it will proceed it to ch_uname.php. Then if the login credentials have already username then it will be preceded to index_profile.php. Thank you in advance.
if(mysql_num_rows($runcreds)> 0 ) //checking log in forms
{
if(mysql_num_rows($run_uname)>=1 ) //if username has already avalaible(proceed)
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('modules/index_profile.php','_self')</script>";
}
if(mysql_num_rows($run_uname)<1)//choouse username if has not yet username
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('forms/ch_uname.php','_self')</script>";
//modules/index_profile.php
}
}
else
{
echo "<script>alert('Admin details are incorrect!')</script>";
}
}
Here is a basic demonstration (using a PDO connection) of what I think you are looking for? I am assuming some stuff here because you don't give enough info before your code snippet:
session_start();
// I will use PDO because I cannot bring myself to use mysql_ in this demonstration
// Initiate connection (assigning credentials assumed)
$con = new PDO("mysql:host=$mysqlDB;dbname=$mysqlTable", $mysqlUser, $mysqlPass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
// Stop if empty
if(empty($username)) {
// You can echo or assign to a variable to echo down the page
echo 'Username cannot be empty';
return;
}
// Set up prepared statement
$query = $con->prepare("select Email_add,password from `users` where username = :username");
$query->execute(array(":username"=>$username));
// Loop through returned
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// If the loop comes up blank, assign false (0)
$result = (isset($result) && !empty($result))? $result:0;
// If username exists
if($result != 0) {
// I am assuming you have some form of super secure hash method for passwords...
$password = bcrypt($_POST['password']);
// If passwords match, create session
if($result[0]['password'] == $password) {
$_SESSION['Email_add'] = $result[0]['Email_add'];
// You probably don't need javascript to redirect
header('Location: modules/index_profile.php');
exit;
}
else {
// Password doesn't match
// You can echo or assign to a variable to echo down the page
echo 'Invalid Username/Password';
}
}
// This would mean the username doesn't exist
else {
header('Location: forms/ch_uname.php');
exit;
}
}
I created a log-in page and i used cookies for the auto-login option.
For some reason, when i'm trying to test it (going to the log-in page - for testing the redirecting)
its not working.
When i'm printing the $_COOKIE i see only the 'PHPSESSID'.
This is my code:
public function index(){
if (isset($_COOKIE[$_SESSION[SESSION_KEY.'id']]) && isset($_COOKIE[$_SESSION[SESSION_KEY.'password']]))
{
$login = $_COOKIE[$_SESSION[SESSION_KEY.'id']];
$password = 1;
}
else if(isset($_POST['login']) && isset($_POST['password']))
{
$password = $_POST['password'];
$login = $_POST['login'];
}
if(isset($login) && isset($password))
{
$query = "SELECT * FROM myDB WHERE id= '{$login}' AND Password = '{$password}'";
$result = $this->db->query($query)->result();
if(count($result) == 0 || count($result) > 1){
$this->load->view('admin/login');
}elseif(count($result) == 1){
$_SESSION[SESSION_KEY.'id'] = $result[0]->id;
$_SESSION[SESSION_KEY.'password'] = 1;
if (isset($_POST['remember']) && isset($_POST['remember']) == 1)
{
setcookie($_SESSION[SESSION_KEY.'id'], $login, time()+60*60*24*10, base_url());
setcookie($_SESSION[SESSION_KEY.'password'], $password, time()+60*60*24*10, base_url());
}
redirect('customers/customers_list');
}
}
else {
$this->load->view('admin/login');
return;
}
}
What could be the problem? where are all the cookies?
And yes, i have session_start();
Try to use the php set_cookie() function the first time the user logs in e.g
setcookie ("username" , $_POST ['username' mktime ()+( 84600 *30 ), "/")
Then get the username cookie if it exists, so you can use the stored value anywere you want e.g
if (isset($_COOKIE ['username' ])) {
//if the cookie exist allow user login e.g
$_SESSION['login']= 'true';
}
else {
//if a cookie doesn't exist
echo "Oops you have to log in!"
//then you display login form
}
Then on the other page you have something like
session_start();
if ($_SESSION['login']='true') {
//Then you display the page
}
else {
//redirect to login page
}
Okay this is definitley an easy question and a stupid one but since I have been developing on localhost i didn't even realise it was a problem. The header to redirect to members page in the loginscript is not working because it is positioned incorrectly. This did not cause a problem on wamp but is on the live server. The script is included in an html file for reasons too long to tell here. Nothing is echoed in the script until something goes wrong but then the script is stopped. Where should i put the redirect header?
Here is the login script:
<?php
// Connects to your Database
include ("database.php");
//Checks if there is a login cookie
if(isset($_SESSION['username']))
//if there is, it logs you in and directes you to the members page
{
echo '<div id="probwarn"><t1><b>You are already logged in! You do not need to do it again.</b></t1></div>';
}
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted
$flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload.
// makes sure they filled it in
if(!$_POST['username'] | !$_POST['pass']) {
echo('<div id="probwarn"><t1>You did not fill in a required field.</t1></div>');
$flag = $flag + 1;
}
// checks it against the database
$pass = htmlspecialchars(mysql_real_escape_string($_POST['pass']));
$username = htmlspecialchars(mysql_real_escape_string($_POST['username']));
$check = mysql_query("SELECT * FROM members WHERE username = '".$username."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
if($flag == 0) {
echo('<div id="probwarn"><t1>You must <b>register</b> first.</t1></div>') ;
}
$flag = $flag + 1;
}
$check = mysql_query("SELECT * FROM members WHERE username = '".$username."'")or die(mysql_error());
$pass = htmlspecialchars(mysql_real_escape_string($_POST['pass']));
$username = htmlspecialchars(mysql_real_escape_string($_POST['username']));
while($info = mysql_fetch_array( $check ))
{
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']) {
if($flag == 0) {
echo('<div id="probwarn"><t1>Incorrect password, please try again.</t1> </div>');
$flag ++;
} }
}
// if login is ok then we add a cookie
if($flag == 0) {
$pass = htmlspecialchars(mysql_real_escape_string($_POST['pass']));
$username = htmlspecialchars(mysql_real_escape_string($_POST['username']));
$_SESSION['username']=$username;
$_SESSION['password']=$pass;
//then redirect them to the members area
//THIS IS THE HEADER
header("Location: ../members.html");
}
}
else
// if they are not logged in
?>
LOGIN FORM IS USUALLY HERE
You forgot to exit after setting a Location header. Unless you know exactly what you're doing, you should ALWAYS put exit (or die()) after a Location header.
you can use header('Location: address') everywhere of your code, but it's better to use exit() function after header, if redirection not executed, other codes doesn't execute.