I am very new to php programming. I have written a sign up html file where the user enters his email and password. If the user has already registered, I am redirecting to sign-in screen and if the user is new use, I am persisting in the database. Now if the user enters wrong password, he will again be redirected to sign-in screen but this time I want to show a message on the screen, that the password entered is incorrect. The sign in screen should not display the message when the user navigates directly to the sign in screen.
The code snippet is shown below:
<?php
define('DB_HOST', 'hostname');
define('DB_NAME', 'db_name');
define('DB_USER','username');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() {
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (email,pass) VALUES ('$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) {
header('Location: reg-success.html');
}
}
function SignUp() {
if(!empty($_POST['email'])){
$emailQuery = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]'");
if($row = mysql_fetch_array($emailQuery)) {
$query = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]' AND pass = '$_POST[password]'");
if($row = mysql_fetch_array($query)) {
echo 'validated user. screen that is accessible to a registered user';
}else{
echo 'Redirect to the sign in screen with error message';
}
}else{
NewUser();
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>
Please let me know how to get this implementation using php
Here are a couple of classes that may help you prevent injection hacks plus get you going on how to do what you are trying to do in general. If you create classes for your tasks, it will be easier to re-use what your code elsewhere. I personally like the PDO method to connect and grab info from a DB (you will want to look up "binding" to help further prevent injection attacks), but this will help get the basics down. This is all very rough and you would want to expand out to create some error reporting and more usable features.
<?php
error_reporting(E_ALL);
// Create a simple DB engine
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Your user controller class
class UserControl
{
public $_error;
protected $db;
// Save the database connection object for use in this class
public function __construct($db)
{
$this->_error = array();
$this->db = $db;
}
// Add user to DB
protected function Add()
{
$email = htmlentities($_POST['email'],ENT_QUOTES);
// Provided you have a php version that supports better encryption methods, use that
// but you should do at least a very basic password encryption.
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine writer method to write your sql
$this->db->Write("INSERT INTO WebsiteUsers (`email`,`pass`) VALUES ('$email','$password')");
}
// Fetch user from DB
protected function Fetch($_email = '')
{
$_email = htmlentities($_email,ENT_QUOTES);
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine fetcher method to check your db
$_user = $this->db->Fetch("SELECT * FROM WebsiteUsers WHERE email = '$_email' and password = '$password'");
// Return true if not 0
return ($_user !== 0)? 1:0;
}
// Simple fetch user or set user method
public function execute()
{
// Check that email is a valid format
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Save the true/false to error reporting
$this->_error['user']['in_db'] = $this->Fetch($_POST['email']);
// Asign short variable
$_check = $this->_error['user']['in_db'];
if($_check !== 1) {
// Add user if not in system
$this->Add();
// You'll want to expand your add feature to include error reporting
// This is just returning that it made it to this point
$this->_error['user']['add_db'] = 1;
}
else {
// Run some sort of login script
}
// Good email address
$this->_error['email']['validate'] = 1;
}
else
// Bad email address
$this->_error['email']['validate'] = 0;
}
}
// $_POST['submit'] = true;
// $_POST['email'] = 'jenkybad<script>email';
// $_POST['password'] = 'mypassword';
if(isset($_POST['submit'])) {
// Set up a db connection
$db = new DBEngine('hostname','dbname','dbuser','dbpass');
// Create instance of your user control
$_user = new UserControl($db);
// Execute instance
$_user->execute();
// Check for basic erroring
print_r($_user->_error);
} ?>
Related
I want to get and echo a users permission level.
I have a function where the users email is passed, the function then needs to get the users permission level and return it, so it can be echoed on another page.
I imagine the function will look though the database for the passed email, it then finds the users permission and returns with that.
In the 'User.class.php'
public static function permGetter($email)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':permission'=>$permission]);
$user = $stmt->fetchObject('User');
if($user !== false)
{
return $permission;
}
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
In the 'permRequest.php'
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email))
{
echo 'Permission ' + (int) $permission;
}
}
else
{
//I use level 5 as a debug so i can see when it fails
echo 'Permission 5';
}
}
?>
Database
Here's an example on what my database looks like.
Edit 1
Okay messing about, I think i got closer to the solution.
First, #Lawrence Cherone, thanks for pointing out my mistake in my execute.
Okay I have changed my code in
User.class.php
public static function permGetter($email, $permission)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email');
$stmt->execute([':email'=>$email]);
$row = $stmt->fetch(PDO::FETCH_NUM);
$permission = $row['permission'];
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
I have made small changes to
permRequest.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
$permission = '';
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email, $permission))
{
echo 'Permission ', $permission;
}
}
}
?>
But now i get an error. The error is this Notice: Undefined index: permission in /classes/User.class.php on line 56
So, I read up on it and it seemed like it should be emptied first, so I empty it in permRequest.php that's why I'm passing it too, but I still get this error after i emptied it?
However if i change
$row = $stmt->fetch(PDO::FETCH_NUM);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);
/* OR */
$row = $stmt->fetch(PDO::FETCH_BOTH);
I get no error but it simply says my email or password is incorrect, which it isn't I have double and triple checked it.
So I'm confused to which PDO::FETCH_ I should use. I have read this (Click here) and I would say that both ASSOC, BOTH and NUM would fit the purpose.
So why is one giving an error while the two other's simply fails the login?
Edit 2
Found the solution and i have written it as a Answer. Can't accept it for the next two days however.
I moved everything out of the User.class.php and moved it into permRequest.php. This solved my problem for some reason. So my code looks like this now
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once("../includes/init.php");
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
if(Auth::getInstance()->login($email, $pass))
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sub = $row['permission'];
echo 'Permission ', $sub;
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
}
And I don't use the User.class.php for this function.
So my guess is something went wrong when returning $sub when it was in User.class.php
I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify
So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>
I am trying to write a simple function that checks if a username exists in the db and if so to call another function to generate a new username. My code seems to fall over though:
Username Function:-
$user1=create_username($fname, $company);
function create_username($surname, $company){
//$name_method=str_replace(" ", "", $surname);
$name_method=$surname.$forename;
$company_name_method=str_replace(" ", "", $company);
if(strlen($name_method)<=5)
{
$addition=rand(11,99);
$first=$addition.$name_method;
}
else
{
$first=substr($name_method,0,5);
}
if(strlen($company_name_method)<=5)
{
$addition2=rand(11,99);
$second=$addition2.$company_name_method;
}
else
{
$second=substr($company_name_method,0,5);
}
$middle=rand(100,1000);
$username=$first.$middle.$second;
return($username);
}
Check Username Function:
check_user($user1, $dbc, $fname, $company);
function check_user($user1, $dbc, $surname, $company){
$check_username="SELECT username FROM is_user_db WHERE username='$user1'";
$resultx=mysqli_query($dbc, $check_username) or die("Could not check username");
$num_rows=mysqli_num_rows($resultx);
if($num_rows>0)
{
$user1=create_username($fname, $company);
check_user($user1, $dbc, $fname, $company);
}
else
{
return($user1);
}
}
It just seems to return the original username.
You probably need to re-factor your code a little. Write out the steps on paper; that helps me. So far, I can see:
You want to check a username is unique on form submission
If it's not, generate a new username
So, check the username when your form is POSTed:
<?php
if (isset($_POST['submit'])) {
if (username_unique($_POST['username'])) {
// carry on processing form
}
else {
$suggested_username = suggest_username($_POST['username']);
// display form, with new suggested username?
}
}
And then write your functions:
<?php
// following on from code from above
function check_username($username) {
// get database connection (I use PDO)
$sql = "SELECT COUNT(*) AS count FROM users_tbl WHERE username = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($username));
$row = $stmt->fetchObject();
return ($row->count > 0); // if 'count' is more than 0, username already exists
}
function suggest_username($username) {
// take username, and add some random letters and numbers on the end
return $username . uniqid();
}
Hopefully this will help. Obviously it'll need some modification to work in your set-up, but this is the general flow you'll need.
Trying to add some extra elements to my session variables for filesystem directory work, and I noticed that I can't add some. Here's what I have:
<?php
#login.php
// This page processes the login form submission.
// Upon successful login, the user is redirected.
// Two included files are necessary.
// Check if the form has been submitted:
if(isset($_POST['submitted']))
{
// For processing the login:
require_once ('login_functions.php');
// Need the database connection:
require_once ('../mysqli_connect.php');
// Check the login:
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if ($check) //OK!
{
// set the session data:
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['company_name'] = $data['company_name'];
$_SESSION['email'] = $data['email'];
// Store the HTTP_USER_AGENT:
$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
//Redirect:
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit(); // Quit the script.
}
else // Unsuccessful!
{
// Assign $data to $errors for error reporting
// in the login_functions.php file.
$errors = $data;
}
mysqli_close($dbc); // Close the database connection
} //End of the main submit conditional
//Create the page:
include('login_page_inc.php');
?>
here are the login functions:
<?php #login_functions.php
//This page defines two functions used by the login/logout process.
/*This function determines and returns an absolute URL.
* It takes one argument: the page that concludes the URL.
* The argument defaults to index.php
*/
function absolute_url ($page = 'about.php')
{
//Start defining the URL...
//URL is http:// plus the host name plus the current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Remove any trailing slashes:
$url = rtrim($url, '/\\');
// Add the page:
$url .= '/' . $page;
// Return the URL:
return $url;
}//End of absolute_url() function.
/*This function validates the form data (email address and password).
* If both are present, the database is queried.
* The function requires a database connection
* The function returns an array of information, including:
* - a TRUE/FALSE variable indicating success
* - an array of either errors or the database result
*/
function check_login($dbc, $email = '', $pass = '')
{
$errors = array(); // Initialize error array.
// Validate the email address:
if (empty($email))
{
$errors[] = 'You forgot to enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
// Validate the password:
if (empty($pass))
{
$errors[] = 'You forgot to enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if(empty($errors)) //If everything's OK.
{
// Retrieve the user_id and first_name for that email/password combo
$q = "SELECT user_id, first_name, email FROM
user WHERE email='$e' AND pass=SHA1('$p')";
$r = #mysqli_query ($dbc, $q); // Run the query.
//Check the result:
if (mysqli_num_rows($r)==1)
{
//Fetch the record:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Return true and the record:
return array (true, $row);
}
else //Not a match for writer, check the publisher table
{
$q = "SELECT pub_id, company_name, cemail FROM
pub WHERE cemail='$e' AND password=SHA1('$p')";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)==1)
{
//Fetch the record:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Return true and the record:
return array (true, $row);
}
else
{
echo '<p>Invalid Credentials</p>';
}
}
} // End of empty($errors) IF.
// Return false and the errors:
return array(false, $errors);
} // End of check_login() function.
?>
Note: $_SESSION['first_name'] and $_SESSION['company_name'] have always worked correctly, however adding email and user_id is not working. Thanks in advance.
email and user_id will never work for the publisher: as the login function returns "pub_id" and "cemail". To fix this, you could change the SQL to:
$q = "SELECT pub_id as user_id, company_name, cemail AS email FROM
pub WHERE cemail='$e' AND password=SHA1('$p')";