I'm trying to stay on the same page after submitting a form button.
Depending on the button the user clicks, I want to display certain information on that same page the button was clicked.
For some reason it keeps redirecting me back to my "ask_login.php" page after I click on the button.
I've read around and some people recommend using AJAX or JQuery but I don't really understand much about it. I'd be appreciated if I could get some help. Thanks.
loggedin.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
?>
<form method="POST" action="">
<input type="submit" name="details" value="Details">
</form>
<form method="POST" action="">
<input type="submit" name="optionB" value="option B">
</form>
<form method="POST" action="">
<input type="submit" name="optionC" value="option C">
</form>
<form action="#">. no action means 'submit to current url', the pound sign mean 'the current document' and should not navigate. though i'm not sure forms semantically allow this.
I would recommend posting the form data over ajax though. Its not hard to do, Jquery offers the most used ajax function and you basically loop though each input in a form and push the value into a uri-encoded string and post that via an ajax call.
I think this following code is not correct...
if($username && $password)
Try this
if(!empty($username) && !empty($password))
i think it shout be
<?php
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
?>
<form method="POST" action="">
<input type="submit" name="details" value="Details">
</form>
<form method="POST" action="">
<input type="submit" name="optionB" value="option B">
</form>
<form method="POST" action="">
<input type="submit" name="optionC" value="option C">
</form>
you can use jquery to process the form
$.post( "test.php", $( "#testform" ).serialize(),function(e){alert(e);} );
test.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
?>
http://api.jquery.com/jquery.post/
beware, no input validation!
read this page
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Related
I apologize for the wall of text but I've been banging my head against the wall around this problem for awhile so I'm gonna try to provide as much information as possible.
I'm not quite sure if the problem I'm getting has to do with user sessions (I'm new to PHP), but that's what it seems to me.
I ask a user to enter his login information (id and password) to enter the system in ask_login.php:
<div class="login_box">
<h1>Login</h1>
<form method="POST" action="login.php">
<p><input type="text" name="username" placeholder="UserID"></p>
<p><input type="password" name="password" placeholder="Password"></p>
<input type="submit" name="submit" value="Login"></p>
</form>
</div>
If the login details (id and password) are found in the database the user gets logged in to his user portal (login.php) where he can check his details, exams dates, etc..
My problem is whenever I login, if I click for example on the details button to check the user details, it redirects me to my ask_login.php page asking for my login details again saying that I didn't enter any ID/Password details.
I've tried removing the code where it checks if the login forms were submitted blank, and it eventually started working and I was able to click the 'Details' button or any other button, without getting redirected to ask_login.php.
But now when I click on the 'Details' button my "Welcome, username" line doesn't show the username, which makes me think that it has something to do with php sessions. Furthermore, any query that I make won't show the result.
Here's my login.php code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$conn_error = 'Could not connect.';
$mysql_db = '------';
if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
die($conn_error);
}
$query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($query);
if($numrows!== 0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['id'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
#$_SESSION['id'] = $username;
}
else {
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Wrong username/password!");
}
}
else {
echo "<script>alert('User doesn't exist.');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("That user doesn't exist!");
}
}
else if(empty($username) || empty($password)) {
echo "<script>alert('You didn't enter an ID/Password');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Please enter an ID and password!");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Logged in | FCUL</title>
<link rel="stylesheet" href="css/stylesheet_loggedin.css" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="shortcut icon" href="img/vitor-20130904-favicon.ico"/>
</head>
<body>
<div id="header">
<br/>
<img src="/img/fcul_cent_logo_001.png" width="510" height="70"/>
</div>
<div id="loggedinas">
<br/>
Welcome,
<?php
$result = mysql_query("SELECT nome FROM users WHERE id='$username'");
while($row = mysql_fetch_assoc($result)) {
echo $row["nome"];
}
?>
( <?php echo $username; ?> )
<br/>
<div id="logout">
<font size="2"><u>[Logout]</u></font></a>
</div>
<hr/>
</div>
<?php
//FETCH USER'S BI
if(isset($_POST['username'] )) {
$ID = $_REQUEST['username'];
$query = "SELECT bi FROM users WHERE id='$ID'";
//if query is successful
if($query_run = mysql_query($query)) {
//if it returns 0 rows
if(mysql_num_rows($query_run)==NULL) {
echo "<script>alert('Unexpected Error 004');</script>";
echo "<script language='javascript'>window.location = 'index.php';</script>";
}
while($query_row = mysql_fetch_assoc($query_run)) {
$bi = $query_row['bi'];
//echo $bi;
}
}
}
?>
<br/>
<center>
<div id="buttons">
<form method="POST" action="login.php">
<input type="submit" name="details" value="details">
</form>
<?php
//**print user's BI if he clicks on 'Details' button**
if($_POST['detalhes']){
echo '<div id="content">' . $bi . '</div>';
}
?>
</div>
</center>
</body>
</html>
you cannot access session on first time you insert it in $_SESSION['id'] = $username variable.
you can only access it on the second run of session_start();
try this.
1. make login.php
2. make welcome.php
try to separate the module where login.php will only process for checking
the login process then if this condition success then
<?
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
$_SESSION['id'] = $username;
header("location: welcome.php");
}
?>
in welcome.php
<?
session_start();
// this is for the checking if user is loged in
if (!$_SESSION['id']) {
header("location: ask_login.php");
exit;
}
?>
You are not checking if the user is already logged, so, after receiving your post from ask_login.php, when you click anything in your page $username and $userpassword will be null.
Just wrap all your code after session_start with
if($_SESSION['id'] === false)
{
//Your code
$username = $_POST['username'];
$password = $_POST['password'];
if($username &&...
}
wrap your code with this
if ($_SESSION['id']){
//your login checking here
};
e.g
if ($_SESSION['id']){
if($username && $password) {
$conn_error = 'Could not connect.';
$mysql_db = '------';
if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
die($conn_error);
}
$query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($query);
if($numrows!== 0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['id'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
#$_SESSION['id'] = $username;
}
else {
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Wrong username/password!");
}
}
else {
echo "<script>alert('User doesn't exist.');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("That user doesn't exist!");
}
}
else if(empty($username) || empty($password)) {
echo "<script>alert('You didn't enter an ID/Password');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Please enter an ID and password!");
}
}
?>
I am making a lo-gin page, where you should use a user_name and a password in order to lo-gin. before logging in, you need to register an account with your name.
This is my code for logging in to the page:
<?php
// if already logged in
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
if(isset($_POST['logout'])) {
session_destroy();
echo 'Logged Out!';
showloginform();
}
else {
print("<p>Dear $_SESSION[username]</p>");
print "<p>only a logged in user can see this</p>";
}
}
//not logged in:
else {
//have login request:
if(isset($_POST['username']) && isset($_POST['password'])) {
include 'opendb.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT Name, password FROM Restaurant_table WHERE Name = '$username' AND password = '$password'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
//found username/password combination:
if (mysql_num_rows($result) == 1) {
$_SESSION['logged'] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo 'logged in';
//exit;
}
else {
echo 'Sorry, wrong user_id or password.';
}
}
//have no login request:
else {
showloginform();
}
}
function showloginform() {
echo "\r\n please enter your login information to proceed with our site <br/><br/>";
echo '<form action="start.html" method="post">';
echo '<div class="input-group">';
echo '<input type="text" placeholder="User ID" name="username" class="input-transparent" id="email" />';
echo '<input type="password" placeholder="password" name="password" class="input-transparent"/>';
echo '</div>';
echo '<button id="login-submit" type="submit" class="login-button">Manager Login</button>';
echo '</form>';
}
function checkpass() {
include 'opendb';
$sql = "select * from Restaurant_table where Name='$_POST[username]' and password='$_POST[password]'";
$result = mysql_query($sql,$conn) or die(mysql_error());
return mysql_num_rows($result);
}
?>
but it seems like it doesnt work, First of all it doesnt give me any error when i log-in with use wrong info it just moves to the next page. It is suppose to give me an error or omething, I am not sure what is going wrong.
You are using action as start.html page for your <form>. Because of that it is redirecting to start.html rather than start.php. Change this
echo '<form action="start.html" method="post">';
to
echo '<form action="start.php" method="post">';
OR quote by Prisoner
echo '<form action="" method="post">';
Yes first you have to post the values in a php page not html page.
echo '<form action="<?php echo $_SERVER[\'PHP_SELF\']?>" method="post">';
Second mistake is
if (mysql_num_rows($result) == 1) {
instead of this it should be.
if (mysql_num_rows($result)> 0) {
I'm kinda' beginner and I've coded my own PHP login from Zero, but I still got some errors, here's the code:
<?php
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ($username = $result['username']) {
if ($password = $result['password']){
header('Location: admin.php');
} else {
echo "PASSWORD IS INCORRECT";
}
} else {
echo "USERNAME IS INCORRECT";
}
?>
So if you can fix this or got an easier way from PHP login from please tell me. :)
A few things...
Don't use mysql functions
You need to use == to compare strings, not =
You need to actually fetch the results of your query
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result); /* add this */
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
if(isset($_POST['usernameInput']) && isset($_POST['passwordInput'])){
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
}
else{
echo 'some error ...';
}
if($username == $row ['username'] && $password == $row ['password']){
header('Location: admin.php');
}
else{
echo ' username or password is wrong';
}
?>
I have to point out that you are sending the same form over and over without first checking the post. And when you send the form, you will not be able to send the header to redirect, because html is started and headers are sent already.
Mysql functions are deprecated, please use mysqli interface.
Among other several bugs like assignment = instead of is equal ==
Try it this way:
If no post exists send the form else check and if ok redirect or not ok. resend the form
<?php
if($_POST){
include 'connection.php';
$query = " SELECT * FROM admin";
$r = mysql_query($query) or die(mysql_error());
// get an associated array from query result resource.
$result = mysql_fetch_assoc($r);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ( ($username == $result['username'])
&& ($password == $result['password'])){
header('Location: admin.php');
exit(0);
} else {
echo "PASSWORD IS INCORRECT";
}
}
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
?>
I'm currently using a modified version of a login script I found online.
Can anybody suggest some ways of modularizing the code into functions?
Here is the code for the login page:
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password=md5($password);
$sql="SELECT * FROM client_login WHERE Username='$username' and Password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
$client_ref = $row['Client_ref'];
$user_level = $row['user_level'];
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['user_level'] = $user_level;
$_SESSION['client_ref'] = $client_ref;
$_SESSION['user'] = $username;
if ($user_level == '1') {
header('Location: admin.php');
} else {
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>
Ideally, I'd like a function for the user account search and the session setting. I previously tried to copy snippets of this code into a separate php functions file, but it didn't seem to work.
What do you think about this? :)
The function
<?php
function checkLogin($username, $password) {
global $bd;
$returnArray=array();
$username=mysqli_real_escape_string($bd, $username);
$password=md5($password);
$getUser=mysqli_query($bd, "SELECT `Client_ref`,`user_level` FROM client_login WHERE Username='$username' and Password='$password'");
$arrayUser=mysqli_fetch_array($getUser);
if(mysqli_num_rows($getUser) == 0)
{
$returnArray['error']='true';
$returnArray['errormsg']='User not found in the database.';
return $returnArray;
}
$returnArray['Client_ref']=$row['Client_ref'];
$returnArray['user_level']=$row['user_level'];
return $returnArray;
}
?>
Rest of the code
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=$_POST['username'];
$password=$_POST['password'];
$loginArray=checkLogin($username, $password);
if(!isset($loginArray['error']))
{
$_SESSION['user_level'] = $loginArray['Client_ref'];
$_SESSION['client_ref'] = $loginArray['user_level'];
$_SESSION['user'] = $username;
if($loginArray['user_level'] == '1')
{
header('Location: admin.php');
}
else
{
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
echo "The detailed error message is: ".$returnArray['errormsg'];
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>
I am learning how to use "setcookie", however, I couldn't get following line to work,
I have pasted all my codes here, if someone could give me a hand please?
Have no idea the reason.
Many thanks.
else{ die ("hahahahahahahahahahahahahaha"); }
HTML code
<form method="POST" action="">
<div class="error"><?php echo $error;?></div>
<p></p>
<label>Username: </label><br>
<input type="text" name="username"><br>
<label>Password: </label><br>
<input type="password" name="password"><br>
<input type="checkbox" name="rememberme"> Remember me<br>
<input type="submit" name="submit" value="Login">
PHP CODE
<?
if(isset($_POST['submit'])){
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = isset($_POST['rememberme']);
echo $rememberme;
if($username&&$password){
$login = mysql_query("SELECT * FROM form WHERE username='$username'");
while ($row = mysql_fetch_assoc($login))
{
$db_password = $row['password'];
if (md5($password)== $db_password)
{
$logstatus = TRUE;
}
else{
$logstatus = FALSE;
}
if ($logstatus == TRUE)
{
if ($rememberme == "1")
setcookie("username", $username, time()+600);
else if ($rememberme == "")
$_SESSION['username'] = $username;
echo " I am here";
}
else{
die ("hahahahahahahahahahahahahaha"); //unable to get here
}
}
}
else{
echo "enter username / password";
}
}
?>
Try this code, I haven't tested it but is should works :)
session_start();//dont forget this :P
if(isset($_POST['submit'])){
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = isset($_POST['rememberme']);
echo $rememberme;
if($username&&$password){
$login = mysql_query("SELECT * FROM form WHERE username='$username' AND password='".md5($password)."'");
if (mysql_num_rows($login))//if this returns 1 you are logged in
{
if ($rememberme == "1")
setcookie("username", $username, time()+600);
else
$_SESSION['username'] = $username;
echo " I am here";
}else{
die ("Incorrect Username/Password"); //unable to get here
}
}
}
else{
echo "enter username / password";
}
}
The while loop is causing the issue, simply remove it.
Well I didn't tested the code but trying following might help.
Add line:
$logstatus = TRUE;
before while.
Justification:
Scope of variable finishes as soon as block finishes. defining logstatus outside while will make sure its scope do not end where it is required.