problem with form to send entry to mysql database in php - php

I have three files working on an login app to learn PHP.
This is the connection with DB
<?php
# Connecting database below
$connection = mysqli_connect('localhost','root','','loginapp');
if ($connection) {
# code...
echo "connected";
}
else{
echo "Errorr";
die("Database");
}?>
and here is the html code for the web view
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Welcome to My Form</h1>
<form class="" action="login_create.php" method="post">
<input type="text" name="name" placeholder="Enter your name here"><br>
<input type="password" name="password" placeholder="Enter Password" value=""><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
and here is the file where things are going wrong, its not checking the conditions of entries and not putting the data into database what's wrong going there? help please
sometimes it gives
error that "unknown 'sbumit' in the $_POST" and sometimes it don't
doesn't even show any error
but doesn't even do anything
<?php
include "db.php";
if (isset($_POST['submit'])) {
$username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
if (strlen($username) > 10 && strlen($username) < 3) {
echo "Must enter username & pass between 3 & 10";
echo "So that we can forward your request";
}
else {
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')";
$result = mysqli_query($connection,$query);
if(!$result)
{
die('Sorry Query faild'.mysqli_error());
}
}
}
else
{
echo "You haven't wrote anything, write it first";
}
}?>

Habib,
Some guidance for PHP :
$button = isset($_POST["submit"])?$_POST["submit"]:"";
What this line does is apply a value to the $button variable, the first check is that IF isset($var) THEN (indicated with the ? ) apply the value of $var to the $button variable.
The colon : then sets that if the boolean query (true/false) of the IF returns false, then apply the second value instead, in this case an empty string of "".
This is code minimalisation and you should be aware of it but there is little need to use it, especially while learning.
Feedback on your code:
mysqli_error($connection); Your error feedback for MySQLi should include the connection details, as shown here.
replace the $username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
because you want to check not if they're set but if they're not empty, currently they will be set as they're set to the values of $_POST even if they are null (potentially), so replace with:
if(!empty($username) && !empty($password)){
Also note that ! is the negative operator. so above is IF NOT EMPTY.
if (strlen($username) > 10 && strlen($username) < 3) { this is impossible to reach because you're setting if string is longer then 10 AND string is shorter than 3, this is clearly impossible. replace the && with || which is OR rather than AND .
Personally I think that isset($_POST['submit']) is not the best way, instead checking that if($_POST['submit'] == 'submit') confirms the submission of this form from this submit button (the value is the value set in your HTML form).
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')"; This works fine, BUT you really, really need to do some research into SQL injection attacks and SQL security. read How can I prevent SQL injection in PHP? as a start. This is very important to learn at the start of your PHP MySQL learning.
Also research into PDO database connectivity.
Also be aware that your script will not output anything when you have a successful saving of username/password to the database.
As a closer:
Fnally, set up error logging on your page, to give you useful feedback on errors and problems: error_reporting(E_ALL);
ini_set('display_errors', 1); at the very top of your page. Also see How do I get PHP errors to display?

Change your code as follow.
<?php
include "db.php";
$button = isset($_POST["submit"])?$_POST["submit"]:"";
$username = isset($_POST["name"])?$_POST["name"]:"";
$password = isset($_POST["password "])?$_POST["password "]:"";
/*Commetents*/
$button =isset($_POST["submit"])?$_POST["submit"]:"";
is similar to following code:
if(isset($_POST["submit"]))
{
$button = $_POST["submit"];
}
else
{
$button = $_POST["submit"];
}
You know in Php 5.4 , it will present error,if you do not set any value to variable . that is why we used it. If it doesn't get any value it will set it value "".
if($button == "submit") means when someone will press the button submit then $_POST['submit'] value will be submit which you define in the submit button value.
if($button == "submit")
{
if($username=="" or $password=="")
{
$error ="Username & Password can't be blank";
}
elseif(strlen($username)<3 or strlen($username) > 10 )
{
$error ="Must enter username & pass between 3 & 10";
}
else
{
$query = "INSERT INTO users (username,password) VALUES('$username','$password')";
mysqli_query($connection,$query) or die(mysqli_error());
}
}
echo $error;
Hope it will help you .

Related

PHP 8.0.7 password_verify terminates with error

I'm making a dummy login page for a school project, and I'm using a hardcoded login for testing.
However, when I execute the following page:
<!DOCTYPE html>
<html>
<body>
<?php
$email = $password = "";
$loginErr = $loginSuccess = "";
// Dummy login to replace the database
$correctEmail = htmlspecialchars("abc123#gmail.com");
$correctPassword =
"\$2y\$10\$Ul2c6wZYxmO9MCJEnySdT.VnoRz7gAFOGVrAEOAhTFBM/5mp81Xl2";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
echo gettype($password);
echo gettype($correctPassword);
echo password_verify($password, $correctPassword) or die("Something went wrong");
I get the following output:
stringstringSomething went wrong
I get this output regardless of whether I escape-code the dollar signs in the hash.
When I tried to fetch the exception:
try
{
echo password_verify($password, $correctPassword);
}
catch (Exception $e) { echo $e->getMessage();}
it didn't print anything.
php -l returned no syntax errors for either version of the code.
As stated in the title, I'm using PHP 8.0.7, which should support password_verify according to the function's manual page.
Do any of you know how I can get this function working?
EDIT/SOLUTION: I assumed the function wasn't returning because "echo verify_password($password, $correctPassword)" didn't echo a false value. I now know that I have to typecast false values to int if I want them to show up.
Second, I thought that if the hash was of htmlspecialchars([password here]), then using htmlspecialchars($_POST["password"]) would be fine. Removing htmlspecialchars from the equation entirely fixed the issue.
The problem originates from your use of htmlspecialchars(). htmlspecialchars() is used for encoding certain characters that have meaning in HTML before sending them to the browser. It has no place here.
So, working from your code I set this up on my development server:
<!DOCTYPE html>
<html lang="en-GB">
<body>
<?php
$email = $password = "";
$loginErr = $loginSuccess = "";
// Dummy login to replace the database
$correctEmail = "abc123#gmail.com";
$correctPassword =
'$2y$10$PxZQRBaAG81cH1BCJowrxu7RaNnlm1i.Ls0l95ohU9rvsqqZr3guG';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["email"];
$password = $_POST["password"];
echo gettype($password);
echo gettype($correctPassword);
echo password_verify($password, $correctPassword) or die("Something went wrong");
} else {
?>
<form method="POST">
<input name="email"><br>
<input name="password" type="password">
<input type="submit" name="submit">
</form>
<?php
}
I've added a basic form for testing and changed the correct password hash to a hash of 'password', and I've removed the references to htmlspecialchars().
It works fine.
If you're using htmlspecialchars() as an attempt to defend against SQL injection, you've chosen the wrong function.
The quick fix would be to change to using mysqli_real_escape_string(). However, this is not considered best practice, and you should look to refactor your code to use prepared statements when no sanitisation is required at all.

How to make a Multi Login User Using PHP?

<?php
ini_set('display_errors', '1');
require_once 'core/init.php';
if(logged_in() === TRUE) {
header('location: dashboard.php');
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "") {
echo "Username Field is Required <br />";
}
if($password == "") {
echo "Password Field is Required <br />";
}
if($username && $password) {
if(userExists($username) == TRUE) {
$login = login($username, $password);
if($login) {
$userdata = userdata($username);
$_SESSION['id'] = $userdata['id'];
header('location: dashboard.php');
exit();
} else {
echo "Incorrect username/password combination";
}
} else{
echo "Username does not exists";
}
}
} // /if
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles1.css">
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<title>Login</title>
</head>
<body class="container">
<div class = "login-box">
<img src = "image/person1.png" class = "avatar">
<h1 id = "login-header">Login</h1>
<form id=registration_form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="form_username" autocomplete="off" placeholder="Username" />
<span id="username_error"></span>
</div>
<br />
<div>
<label for="password">Password</label>
<input type="password" name="password" id="form_password" autocomplete="off" placeholder="Password" />
<span id="password_error"></span>
</div>
<br />
<div>
<input type="submit" name="btnLogin" value = "Login">
</div>
Not yet a member? Register
</form>
</body>
</html>
Can somebody help me regarding to my PHP. I'm very new in PHP. My website must have a multi-login user. But I try to do it and I failed. I don't received any error. But the problem is when I press the login button nothing happen. If the user_type is equal to admin I want to link it to adminPanel.php and if user_type is equal to user I want to link it to userPanel.php. Can somebody fix my code below. I really appreciate it.
function login($username, $password) {
global $connect;
$userdata = userdata($username);
if($userdata) {
$makePassword = makePassword($password, $userdata['salt']);
$sql = "SELECT * FROM tbl_user WHERE username = '$username' AND password = '$makePassword'";
$query = $connect->query($sql);
if($query->num_rows == 1) {
$logged_in_user = mysqli_fetch_assoc($query);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
header('location: adminPanel.php');
}else{
$_SESSION['user'] = $logged_in_user;
header('location: userPanel.php');
}
}
}
$connect->close();
// close the database connection
}
Forword
I feel generous tonight...
This may not fix your issue. As I said in the comments, there are many things that can be wrong. Without more information on what is happening, how you do things there is no way to tell.
These are things that are important (things to check)
how you submit the post (the form)
fields could be named wrong, form could be setup wrong etc.
the form action could simply be wrong
the form method could simply be wrong
how you handle that submission
variables could be sent to login() incorrectly, login($password,$username) instead of login($username,$password)
vairables could simply be translated wrong, for example you could have $_POST['user'] insead of $_POST['username']
you could be doing validation checks on input, which may or may not remove data, could be wrong.
how you handle starting the session
you can't use session until you start it
what if any output you have when handling the submission
output before header location will prevent the redirect
header location does not exit the current code scope, stuff after it can run so you should call exit after doing a redirect.
how you connect to the DB
you may have DB error
what if any errors you get, what error reporting do you have
you could have errors your not reporting for any of the above, and many things I didn't mention.
You probably shouldn't roll you own login system until you have a better handle on the security implications ( and other things).
Password/Security
The makePassword function is not included (in your code), but in any case you should use the built in (PHP5.4+) password function. It's much more secure and saves a lot of work:
function makePassword($plaintext){
return password_hash($plaintext, PASSWORD_DEFAULT);
}
This will return a 60 char long hash, but it's recommended to use VARCHAR(255).
It will look something like this in the DB:
//$2y = BCRYPT (default), $10 Cost or iterations (default), that's all I can remember.
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Then for login (MySqli):
//session_start(); //make sure this is called
function login($username, $password, \mysqli $connect) //use type hinting
{
//can fail because of syntax errors, missing privileges
$stmt = $connect->prepare('SELECT * FROM tbl_user WHERE username = ?') OR die($connect->error);
//can fail because of incorrect number of arguments, invalid types
$stmt->bind_param("s", $username) OR die($stmt->error);
//can fail for various reasons
$stmt->execute() OR die($stmt->error);
$result = $stmt->get_result();
if($result->num_rows == 1) {
$user = $result->fetch_assoc($query);
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error
}
}else{
//username error
}
}
Personally I only use PDO these days. It's been several years sense I used MySqli (so forgive me if I got anything wrong here).
For PDO, this is how I connect with it:
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'user';
$pass = 'pass';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
try{
$PDO = new PDO($dsn, $user, $pass, $options);
}catch(PDOException $e){
//only show end user error codes
die("Error[{$e->getCode()}] connection to DB");
}
The options turn on, Exception error reporting and set the default fetch mode to fetch associative array. With those settings the same thing as above can be done like this:
//session_start(); //make sure this is called
function login($username, $password, \PDO $Pdo) //use type hinting
{
try{
$stmt = $Pdo->prepare('SELECT * FROM tbl_user WHERE username = :username');
$stmt->execute([':username' => $username]);
if($stmt->rowCount()){
$user = $stmt->fetch();
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error, return an error, or throw an exception etc.
}
}else{
//username error
}
}catch(PDOException $e){
//only show end user error codes
die("Database Error[{$e->getCode()}]");
}
}
If you notice it takes around 5 calls to MySqi, and PDO takes only 3 calls. Besides that MySqi is dealing with 3 objects (mysqli, mysqli_stmt, mysqli_result), PDO deals with only 2 (PDO, PDOStatment). Error reporting is also much cleaner.
A few other notes.
use password_hash($plaintext, algo) to create hashes
use password_verify($plaintext, $hash) to check passwords (note plaintext)
use prepared statements
Do not lookup by password, it's not a secure way of verifing 2 hashes are the same (casing, encoding etc...)
use session_start() before using $_SESSION
Do not output anything (not even a single space) before using header
call exit; after using header as it doesn't exit the script it's called in, so it can run code beneath it and produce unexpected results
avoid using global it can be hard to debug your code, instead use dependency injection (pass in the DB connection)
use DRY principals (Dont Repeat Yourself)
And there is probably a bunch of stuff I am forgetting.
UPDATE
Based on the code you added, the part that handles the form submission can be done like this:
<?php
error_reporting(E_ALL); //unclear
ini_set('display_errors', '1');
require_once 'core/init.php';
if(true === logged_in()) { //put constant values on the left
header('location: dashboard.php');
}
if('POST' == $_SERVER['REQUEST_METHOD']){ //put constant values on the left
//ternary condition (shorthand if then)
$username = empty($_POST['username']) ? false : $_POST['username'];
$password = empty($_POST['password']) ? false : $_POST['password'];
//PHP7+ null coalescing can be used instead of above
//$username = $_POST['username'] ?? false;
if(!$username) {
echo "Username Field is Required <br />";
}
if(!$password) {
echo "Password Field is Required <br />";
}
if($username && $password) {
login($username, $password);
//don't forget the connection, if you use the functions without
//it as a global, (which I refuse to use). I once spent a week
//tracking down changes to a global variable in some code I was fixing, never again.
// global $connect;
// login($username, $password, $connect);
}
}
You don't need to do redirects after calling login it's already doing them. You don't need to check if the user exists because you are already checking when fetching there saved password. If you need to know that information there you can either throw exceptions (to much to cover) or you can have the login function return them. In the case that the login is successfule the code will exit before the errors can return.
Summery
My best guess, barring any errors (and assuming the session is started) is that this is happening
form submission, to self
call to login()
everything works, call to header('location: adminPanel.php'); (with no exit)
code returns to the form page (because no exit)
call to header('location: dashboard.php'); And exit();
But that is just a guess, because when yo say "when I press the login button nothing happen" that can mean many things.
One of these days I will put a tutorial for something like this on my website, but it will be more comprehensive.
Anyway, hope it helps you.

PHP - Checking the textbox in Login Forms

The file code is going to check if the field is empty then run the code. The main problem is that when the text box is filled, the "authentication" doesn't work anymore.
So basically, the system gonna check if the text box is filled (both for the Username and Password), when the text box is not filled out, an error will show up "Please fill all the fields" and it's not gonna let the user login if the text box isn't filled out. The problem now is when the text boxes is properly filled (or "filled"), the authentication system isn't working anymore.
More Information:
The authentication system is using SHA256 as the "encryptor" or the "hash code". When I don't enter the code for "checking the fields if empty", the code actually works, but when I put it on the file, everything seems messed up now.
The HTML form code:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
Remember me: <input type="checkbox" name="remember" /><br />
<input type="submit" name="submit" value="Login" />
Register
</form>
The PHP code:
<?php
$username = $_POST['username'];
$mainpass = $_POST['password'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username']) || empty($_POST['password'])) {
echo "Please fill all the fields!";
}
} else {
?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$mainpass = $_POST['password'];
$password = hash('sha256', $mainpass);
// processing remember me option and setting cookie with long expiry date
if (isset($_POST['remember'])) {
session_set_cookie_params('604800'); //one week (value in seconds)
session_regenerate_id(true);
}
$mysqli = new mysqli(localhost, root, "", loginsecure);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows != 1) {
echo "<p><b>Error:</b> Account doesn't exists! Register here!</p>";
} else {
// Authenticated, set session variables
$user = $result->fetch_array();
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// update status to online
$timestamp = time();
$sql = "UPDATE users SET status={$timestamp} WHERE id={$_SESSION['user_id']}";
$result = $mysqli->query($sql);
redirect_to("profile.php?id={$_SESSION['user_id']}");
// do stuffs
}
}
if (isset($_GET['msg'])) {
echo "<p style='color:red;'>" . $_GET['msg'] . "</p>";
}
}
?>
Problem is the if statements in the else clause will never be reached except when the method is GET.
Change the if statement and remove the first assignment of $username and $password:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username']) || empty($_POST['password'])) {
echo "Please fill all the fields!";
}
elseif (isset($_POST['submit'])) {
$username = $_POST['username'];
$mainpass = $_POST['password'];
// rest of your code...
what do you mean by messed up?
You should be able to do it by checking if POST username exists and if its not empty (repeat for password)
if any of these tests come back negative then output error and show the login form again.
if the tests pass continue with the processing as per normal

Some issue with login credentials in php

Below is my code for making a user login the page but when I tried to submit the form it does not check database and directly gives me the else output i.e invalid ID or password I am not getting any error reports too though error reporting is turned on I am not sure where am I going wrong here.
<?php
if(isset($_POST['loginsubmit'])=='Login')
{
$email=$_POST['emaillogin'];
$pass=$_POST['passlogin'];
$pass=md5($pass);
$email = stripslashes($email);
$pass = stripslashes($pass);
$email = mysql_real_escape_string($email);
$pass = mysql_real_escape_string($pass);
require_once "database.php";
$sql = "SELECT * FROM user_log WHERE email = '$email' and password='$pass'";
$loginresult=mysql_query($sql);
$row=mysql_fetch_array($loginresult);
$rowcnt=mysql_num_rows($loginresult);
if($rowcnt==1)
{
session_start();
$_SESSION['email']=$row['email'];
$_SESSION['mobile']=$row['mobile'];
$_SESSION['fname']=$row['fname'];
$_SESSION['lname']=$row['lname'];
echo " <script>
window.location = '../';
</script>";
}
else
{
echo " <script>
alert('Invalid Login ID or Password....');
window.location = '../';
</script>";
}
I've even tried to echo wheather I am getting email and password properly from form and yes I was getting but issue starts from below line I guess:
$sql = "SELECT * FROM user_log WHERE email = '$email' and password='$pass'";
EDIT:FORM ADDED BELOW
<form action="" method="POST">
<input type="email" id="email" placeholder="abc#xyz.com" name="emaillogin" required>
<input type='password' id='password' name='passlogin' placeholder='Password here' required>
<input type="submit" id="continuesubmitemail" name="loginsubmit" value="Login">
</form>
isset() is used to check variable is set or not
You can check your condition as
if(isset($_POST['loginsubmit']) && $_POST['loginsubmit']=='Login')
Also write session_start(); at the top of your page
Use while loop to get data
$rowcnt=mysql_num_rows($loginresult);
if($rowcnt==1)
{
while($row=mysql_fetch_array($loginresult))
{
$_SESSION['email']=$row['email'];
$_SESSION['mobile']=$row['mobile'];
$_SESSION['fname']=$row['fname'];
$_SESSION['lname']=$row['lname'];
}
echo " <script>
window.location = '../';
</script>";
}
And finally stop using mysql it is deprecated . You can use PDO or mysqli
how can you even get into that line? isset function returns boolean and it will be always false because you are doing it like:
if(isset($_POST['loginsubmit'])=='Login')
you should make it like:
if(isset($_POST['loginsubmit']) && $_POST['loginsubmit']=='Login')
isset() returns true or false so you have to write your if condition below..
if(isset($_POST['loginsubmit']) && $_POST['loginsubmit']=='Login')
Replace your condition
with
if($_POST['loginsubmit']=='Login')
use mysql_query($sql) OR DIE(mysql_error());
this will display your mysql error
ps , mysql is deprecated , use mysqli or pdo instead
Try this
$loginresult=mysql_query($sql) or die(mysql_error());
and check that are you getting any output

PHP/MySQL Database Issues

PHP/MySQL newbie question.
I have a database I've imported into my local phpmyadmin. However it seems I can't access it from my a php application. The connection string seems right and when I try to authenticate user credentials to access database information, no problems.
However authenticate everyone and knows when I put in fake credentials. Still it won't pull any other information from the database.
For instance, once a users login they should see something like, "Hello username", that kind of thing. At this point I see "Hello" without the username. Any ideas what i might be missing?
I noticed you are using the root user (though I'm not sure if this was added merely for posting purposes here.) Depending on what hosting environment you are using this may or may not be a problem - some shared hosts force you to assign a user for databases in MySQL.
From the looks of things your query should be executing and returning a number of rows at the least. Have your tried print_r on the results array? If so, can you post the output?
If you are successfully getting results from the database, I don't see anywhere in your posted code a conditional that echos out a success message. You may want to check isset() against the $_SESSION superglobal keys you assign ( recordID and firstName) and if true echo out a success message if you have not already done so.
Just a thought as well - I noticed you are using sprintf to format out your query - it may be a bit too robust for what you're trying to accomplish, but using PDO to get parameterized sql queries is a nice way to get that job done where available.
Introduction to PHP 5 PDO
ok sorry for all the back and forth guys. here's the issue. I've got a php app and mysql database connected (or at least i hope so...). there is a form in the header of my page for users to login. i CAN login but i can't seem to pull any information from the database. If i try to log in using bogus credentials i'm given an "incorrect login" message. However when i do login it can't seem to pull anything else from the database other than those credentials.
ok here's the code...
DATABASE CONNECTION:
<?php
session_start();
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_test = "localhost";
$database_test = "girlpower";
$username_test = "root";
$password_test = "password";
$test = mysql_pconnect($hostname_test, $username_test, $password_test) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_test, $test);
?>
HERE'S THE LOGIN CODE:
<?php
require_once("includes/db.php");
$userEmail = trim($_POST['userEmail']);
$password = trim($_POST['password']);
$userlogin = trim($_POST['userlogin']);
//print_r($_POST);
if ($userlogin != "" && $userEmail != "" && password != "" )
{
$sql = sprintf("Select * from girlpower where email = '%s' and pwd = '%s'", $userEmail, $password );
//echo $sql;
$res = mysql_query($sql);
if( mysql_num_rows( $res ) == 0 )
{
//TODO:
//redirect..
header("Location: " . $_SERVER['HTTP_REFERER'] . "?fail=1" );
}
else
{
$row = mysql_fetch_assoc( $res );
$_SESSION['recordId'] = $row['recordId'];
$_SESSION['firstName'] = $row['firstName'];
//echo "success...";
header("Location: " . $_SERVER['HTTP_REFERER'] );
//print_r($_SERVER);
}
//print($_SESSION);
}
else
{
header("Location: " . $_SERVER['HTTP_REFERER'] . "?fail=1" );
}
HERE'S WHERE HEADER CODE (THIS IS WHERE THE FORM LIVES):
<?php
$fail = false;
if( $_GET['fail'] != "")
{
$fail = true;
}
if( $_SESSION['recordId'] != "" )
{
//get the 1st name
$firstName = $_SESSION['firstName'];
}
?>
<div id="header">
< SHOULD BE LINK "index.php"></a>
<div id="ulogin">
<fieldset id="userlogin">
<?php if( $firstName == ""){ ?>
<form name="loginForm" action="dologin.php" method="post" >
<label for="logemail">Members Login: Email</label> <input type="text"
name="userEmail" id="logemail" size="15" />
<label for="logpwd">Password</label> <input type="password" name="password"
id="logpwd" size="15" />
<input type="submit" name="userlogin" id="login" value="Login" />
<?php if ($fail == true ) {?>
<span class="error">Incorrect Login</span>
<?php }?>
</form>
</fieldset>
<?php
}
else{
?>
<div id="welcome">Welcome <?= htmlentities( $firstName ) ?> | <SHOULD BE LINK ="seemsgs.php?receiver_id="<?= $_SESSION["recordId"]?> > See Messages</> |<SHOULD BE LINK ="member.php">Update Profile</> | <SHOULD BE LINK ="dologout.php">Logout</a> </div><?php }?>
</div>

Categories