the header(location: agentverification.php) does not work when uploaded to godaddy server while it works on localhost server. I've try to edit my codes but the result is still the same. if any of you could help me, I'd appreciate it and thanks in advance.
agentlogin.php
<form method = "post" action = "agentverification.php" >
<table>
<input type="text" name="ID" size=20 ><br></td></tr>
<tr>
<td>Password <font color=red>*</font></td>
<td><input type="password" name="pass" size=20><br></td></tr>
</table>
<input type = "hidden" name = "login">
<input type = "submit" name = "login" value = "submit" id="pop">
agentverification.php
<?php
session_start();
$link = mysqli_connect('localhost', 'root', '','db5') or die(mysqli_error());
if(isset($_POST['login']))
{
extract($_REQUEST);
$id = $_POST['ID'];
$pass = $_POST['pass'];
$query= "SELECT * FROM agentReg WHERE AgentID = '$id'";
$record = mysqli_query ($link,$query);
$check=FALSE;
while($row=mysqli_fetch_array($record))
{
if($id === $row['AgentID']&& $pass === $row['password'] )
{
$check=TRUE;
}
}
if($check == TRUE)
{
$_SESSION['AgentID'] = $id;
$_SESSION['password'] = $pass;
header("Location: agentpage.php");
}
else
{ ?> <script>
alert ("Wrong combination of ID and Password. Please try again.");
</script> <?php
session_destroy();
header("location: agentlogin.php");
}
}?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
agentReg database structure
CREATE TABLE agentReg
(AgentID varchar (100) primary key,
password varchar (100));
You cannot use header('Location: ...'); after you've printed an output.
In your last else you should only include session_destroy(); and for instance header('Location: agentlogin.php?error=idpassword');. The error message should be in agentlogin.php.
Use
window.location.href = 'http://www.google.com'; //Will take you to Google.
Related
I'm trying to make a simple Ajax call for a Bootstrap login modal. The main HTML code of the login Modal looks like this:
<form method="post" id="loginForm">
<div id="loginMessage"></div>
<div class="modal-footer">
<button type="button" class="btn btn-success mr-auto" data-target="#signupModal" data-toggle="modal" data-dismiss="modal">Register</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input class="btn" name="login" type="submit" id="inputButton" value="Login">
</div>
</form>
In case the whole HTML code for the modal would help : https://jsfiddle.net/aslah/hykxLqd5/2/
The jQuery code looks like this:
$('#loginForm').submit(function(event){
//prevent default php processing
event.preventDefault();
//collect user inputs:
var datatopost = $(this).serializeArray();
//send the user data to login.php using AJAX
$.ajax({
url: "login.php",
type : "POST",
data : datatopost,
success : function(data){
if(data == 'success'){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
},
error : function(){
$('#loginMessage').html('<div class="alert alert-danger">There was an error with the AJAX call. Please, try again later!</div>');
}
});
});
This is my login.php code :
<?php
//starting the session
session_start();
//connecting to database
include('connection.php');
//check user inputs
// DEFINE ERROR MESSAGES //
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';
// $email = $_POST["loginEmail"]
// $password = $_POST["loginPassword"]
if(empty($_POST["loginEmail"])){
$error .= $missingEmail;
}else{
$email = filter_var($_POST["loginEmail"], FILTER_SANITIZE_EMAIL);
}
if(empty($_POST["loginPassword"])){
$error .= $missingPassword;
}else{
$password = filter_var($_POST["loginPassword"], FILTER_SANITIZE_STRING);
}
//If there are any ERRORS
if($error){
$resultMessage = '<div class="alert alert-danger">'. $error .'</div>' ;
echo $resultMessage ;
}else{
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
// $password = md5($password); no secure
$password = hash('sha256', $password);
//check if the user is registered by matching EMAIL & PASSWORD
$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password' AND activation='activated' ";
$result = mysqli_query($link, $sql);
//if any errors while running the query
if(!$result){
echo '<div class="alert alert-danger"> Error running the query!</div>';
exit;
}
//if login failed print ERROR
$count = mysqli_num_rows($result);
if($count !== 1){
echo '<div class="alert alert-danger">Wrong username or password</div>';
}else{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
//if remember me is not checked
if(empty($_POST['rememberme'])){
echo "success";
}else{
// if rememberme is checked
}
}
}
?>
On submit of the the Login button I want to redirect the user to the mainpage.php. I tried all the different fixes I found here but nothing worked. I can't figure out what I'm doing wrong. Any help is highly appreciated.
This is what I get when I submit the form
Aslah P Hussain
I have tested your code. The first thing that caught my attention is Notice about the undefined variable $error. Possibly you have defined it in include('connection.php'); but if not, this can cause problems with PHP output that you are expecting.
Additionally, if you are 100% sure that the console returns the message success - you can change your check in JavaScript to:
if(data.indexOf('success') >= 0){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
Possibly not the best solution to the problem, but at least will show you that redirect is working
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
So I'm working on an assignment for my class in which I am supposed to take a username and password and check it against a list contained in a table on a database I am connecting too.
Problem is when I am clicking the submit button nothing is happening I think this is likely to be some sort of error in syntax. Since I am new to PHP there is a good possibility it is something obvious, but not so much to me.
I have my database data stored in two PHP arrays (one for each field). I then converted the arrays to json which I will use in my JavaScript function that will be checked against the user inputted data.
I am including a form, a PHP script, and a JavaScript script in one document could this cause the issue?
Here is my code and thank you for any help!
<html>
<body>
<?php
/*config is included in order to protect my login info*/
require('config.php');
Echo "Project 4";
/*SQL connection*/
$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
/*Checking Connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM p4Data";
$data2 = mysqli_query($conn, $sql);
/*Display Data*/
echo "<table border = 1 style='float:left'>
<tr>
<th>Username</th>
<th>Password</th>
</tr>";
//Array Declarations
$usernameArr = [];
$passwordArr = [];
while($records = mysqli_fetch_array($data2)){
array_push($usernameArr,$records["username"]);
array_push($passwordArr,$records["password"]);
}
echo "</table>";
//JSON Conversion
$usernameJson = json_encode($usernameArr);
$passwordJson = json_encode($passwordArr);
mysqli_close($conn);
?>
<!-- JAVA SECTION -->
<script type="text/javascript">
var obj = JSON.parse('<?= $usernameJson; ?>');
var obj2 = JSON.parse('<?= $passwordJson; ?>');
function verifUser(){
var usernameData = document.getElementById("username").value;
var passwordData = document.getElementById("password").value;
for (i = 0; i < 30; i++){
if(usernameData == obj[i]){
alert("Username verfied at " + i);
indexLocated = i;
break;
}
}
}
</script>
<form name='form-main'>
Username: <input type="text" id="username"><br>
Password: <input type="password" id="password"><br>
<input type="button" value="Login >>" id="submitButton"
onclick="verifUser()">
</form>
</body>
</html>
You can use post method to get the value of user input like this
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="login">
</form>
and use this php code to get value when form is submitted
if(isset($_POST['submit'])){
$username_input = $_POST['username'];
$password_input = $_POST['password'];
}
Then make a query to sql where username = $username and password = $password. Like below
$sql query = " SELECT * FROM TABLE WHERE username = $username and password = $password";
And use
$num_rows = mysqli_num_rows($sql_query);
Now do a check of $num_rows = 1 that means input username and password is valid else echo Not valid
if($num_rows = 1){
**some code **
}else{
echo "Invalid information provided";
};
I was looking for a way to submit data through a button so that the data will be saved or updated in database, without reloading. Now updating and inserting of data works. But I have used dataString a javaScript variable. I thought through this dataString variable post data are passed. But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
How post method gets the data from my ajax call here.
<html>
<title>Registration</title>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
$dbname = "registration_project";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<div style="width:350px">
<div style="float:left;width:40%">
Id:<br/><br/>
First Name:<br/><br/>
Last Name:<br/><br/>
Age:<br/><br/>
</div>
<div style="float:left;width:60%">
<form action="" method="post">
<input type="number" id="id_id" name="id" value=<?php
if (isset($_POST['id']))
echo $_POST['id'];
?>><br /><br />
<input type="text" id="id_fname" name="fname" value=<?php
if (isset($_POST['fname']))
echo $_POST['fname'];
?>><br /><br />
<input type="text" id="id_lname" name="lname" value=<?php
if (isset($_POST['lname']))
echo $_POST['lname'];
?>><br /><br />
<input type="number" id="id_age" name="age" value=<?php
if (isset($_POST['age']))
echo $_POST['age'];
?>><br /><br />
<input type="submit" id="id_submit" name="submit">
</form>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
</body>
</html>
<?php
if (isset($_POST['id']))
echo $_POST['id'] . "<br/><br/>";
if (isset($_POST['fname']))
echo $_POST['fname'] . "<br/><br/>";
if (isset($_POST['lname']))
echo $_POST['lname'] . "<br/><br/>";
if (isset($_POST['age']))
echo $_POST['age'] . "<br/><br/>";
?>
<?php
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "select max(id) from registration";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row["max(id)"];
}
} else {
echo "0 results";
}
if ($id==$_POST['id']) {
$id = $_POST['id'];
$sql = "update registration set firstName='$fname', lastName='$lname', age=$age where id=$id";
mysqli_query($conn, $sql);
} else {
$id=$_POST['id'];
$sql = "Insert into registration(id,firstName,lastName,age) values($id,'$fname','$lname',$age)";
mysqli_query($conn, $sql);
}
}
mysqli_close($conn);
?>
<script>
$("#id_submit").click(function(e) {
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
</script>
Your click handler doesn't have e.preventDefault() in it. So after the AJAX call is sent, the form is also submitted normally. So even if you don't fill in dataString, the database will be updated from the form.
To make it only use AJAX, you should call e.preventDefault(). You also need to submit a value for the submit parameter, because the PHP code uses if(isset($_POST['submit'])) to know if it should process the form parameters.
$("#id_submit").click(function(e) {
e.preventDefault();
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "submit=submit&id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
In your case, values aren't getting passed. More over, the way you're trying to do ( ?id=...&fname=... etc) would be for passing it with $_GET.
You have to make something similar to :
$.ajax({
type:'POST',
data: { id : $("#id_id").val(),
fname : $("#id_fname").val(),
lname : $("#id_lname").val(),
age : $("#id_age").val()
},
url:'Registration.php',
success:function(data) {
// code
}
});
But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
Answer
When you remove var dataString all the fields having name attribute are automatically submitted along with form
I'm working on a login page by user level to separate the admin and user. but it didnt seems to work. it doesnt redirect and leave a blank page. I've tried remove the javascript part, but it doesnt change anything either.
index.php
<form class="login" action="login.php" method="post">
Username:<input type="text" name="username" id="username"/>
Password:<input type="password" name="password" id="password"/>
<input type="submit" value="login"/>
</form>
login.php
<?php
session_start();
include('config.php');
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = mysql_query("SELECT * FROM admin WHERE username='$username' AND password='$password'");
$result = mysql_fetch_array($sql);
$username=$result['username'];
$adminID=$result['adminID'];
$userLevel=$result['UserLevel'];
$_SESSION['adminID']=$adminID;
$_SESSION['userLevel']=$userLevel;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
if($userLevel == '1')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to Admin page! ");
</script>
<?php
header('Location:admin.php');
exit();
}
elseif($userLevel == '0')
{
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script type="text/javascript">
alert("Welcome <?php echo "$username" ?> to User page! ");
</script>
<?php
header('Location: user.php');
exit();
}
else
{
?>
<script type="text/javascript">
alert("Invalid Username or Password! ");
//window.location.href = "index.php";
</script>
<?php
}
}
?>
Use PHP Header:
for userLevel1:
header("Location: admin.php");
for userLevel2:
header("Location: user.php");
Name in your submit so it will enter your PHP code block:
<input type="submit" name="submit" value="login"/>
try the following code and replace into your code. see whether can work or not. you try on the first if condition first and see on the result. if cannot work tell me what problem you face.
<?php
if($userLevel == '1')
$sql = "UPDATE admin SET status = 'AKTIF' where username = '$username' ";
$result = mysql_query($sql) or die('Cannot UPDATE.'.mysql_error());
?>
<script>
var a = alert("Welcome <?php echo "$username" ?> to Admin page! ");
if (a === true){
window.location.href="admin.php";
}
else{
window.location.href="admin.php";
}
</script>
<?php
}