Please be patient with me. I've been spending 1 hour on internet trying to look for a solution, but nothing seems working. And yet I thought I understood how it works.
I'm hosting my website on Altervista. What I would like to do is the following: I send login credentials, if there is some problem, echo an error message (depending on the type of error), else go to the home page:
process_info.php
<?php
ob_start();
if($_POST["nickname"] and $_POST["password"]) {
$username = $_POST["nickname"];
$password = $_POST["password"];
}
else
{
echo "Please fill the form";
exit();
}
$conn = new mysqli("localhost", $username, $password, "db");
if ($conn->connect_error) {
echo "Connection failed"; // $conn->connect_error
}
$conn->close();
session_start();
$_SESSION["nickname"] = $username;
$_SESSION["password"] = $password;
ob_end_clean();
header("location: ../interno/home/home.php");
exit();
?>
This is how I send the login information in my login.php:
<script>
$(document).ready(function(){
$("#invia").click(function(){
var n = $("#nickname").val();
var p = $("#password").val();
$.post("php/invia_credenziali.php",
{
nickname: n,
password: p
},
function(data,status){
//alert("Data: " + data + "\nStatus: " + status);
window.alert(data);
});
});
});
</script>
But my browser doesn't jump to home. Instead I get the window.alert message.
How can I solve this?
Related
I have a login form that checks the password and username entered and if correct it will give a message and makes login session true. But the session doesn't work. When it redirects you to dashboard you won't be able to visit it the value of session login is unknown. So when you enter userpass correct the session is not created for that moment but when you redirect it to another page your session is gone.
<?PHP
session_start();
// Starting session
include 'config.php';
$pass = $_POST['pass'];
$user = $_POST['user'];
if (isset($_POST['user']) and isset($_POST['pass'])){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $link->query("SELECT user FROM users2 WHERE user = '$user'");
if($result->num_rows == 0) {
echo '<script type="text/javascript">
$(document).ready(function(){
demo.initChartist();
$.notify({
icon: "pe-7s-bell",
message: "Username of password was wrong. Please try again."
},{
type: "info",
timer: 4000
});
});
</script>';
} elseif ($result->num_rows == 1){
$userpass = $link->query("SELECT pass FROM users2 WHERE user = '$user'");
$row = $userpass->fetch_assoc();
$userpasss = $row["pass"];
if ($pass == $userpasss){
echo '<script type="text/javascript">
$(document).ready(function(){
demo.initChartist();
$.notify({
icon: "pe-7s-bell",
message: "You are logged in successfully! Redirecting ..."
},{
type: "info",
timer: 4000
});
});
</script>';
$_SESSION['login'] = "true";
$_SESSION['username'] = "$user";
echo "<meta http-equiv='refresh' content=3;URL='dashboard.php' /> ";
echo $_SESSION["login"];
echo $_SESSION["username"];
// Storing session data
} else {
echo '<script type="text/javascript">
$(document).ready(function(){
demo.initChartist();
$.notify({
icon: "pe-7s-bell",
message: "Username of password was wrong. Please try again."
},{
type: "info",
timer: 4000
});
});
</script>';
}
}
}
echo $_SESSION["login"];
?>
Where is the problem in the code?
Thank you
Warm regards
Put session_start(); at the Top of this page as you are accessing in global scope so you will get the session value.
And i will suggest you to create different file for authentication purpose.
You need to write all the page of the top session_start()
After successful login then redirect to dashboard.php need to add the first line
<?php session_start(); echo $_SESSION['login]; ?>
I have a button (id="deleteAccount"). If the user clicks on it, I want them to be logged out and delete their account from the database and then redirect to the site's homepage. I'm using SESSION to identify the user.
Right now, I'm able to only delete their data from the but not log them out and redirect them to the homepage.
Here's my deleteUserAccount.php
<?php session_start();
if(!isset($_SESSION["username"]))
{
header("Location:blocked.php");
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
}
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_SESSION["username"];
$deleteSQL = "DELETE FROM `users` WHERE Username='$user'";
$deleteQuery = $conn->query($deleteSQL);
if($deleteQuery) {
unset($_SESSION["username"]);
unset($_SESSION["password"]);
header("Location:index.php");
}
else {
echo "error";
}
?>
And here's my JS file:
$(document).ready(function() {
$('#deleteAccount').click(function() {
$.ajax({
type: "POST",
url: 'deleteUserAccount.php'
});
});
});
THANKS
$.ajax({
type: "POST",
url: 'deleteUserAccount.php',
success : function() {
$(location).attr('href', 'yoursite/index.php')
}
});
You are doing an ajax call here and you redirect user using php thats why user not redirect to the home page. You need to do with client side script in your ajax success callback.
So I'm working on a login/register system with php which I can use for my Android app (working with Android Studio 2.3.1).
I can already register via my phone. But I found out that if I turn off the wifi and my data and I try to register an empty message gets displayed. I would like to fill this empty message with the text: "Error: no connection" but I really don't know how.
My code is:
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "databasename";
$conn = mysql_connect($hostname, $username, $password);
if (!$conn)
{ die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $conn);
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$repeatpassword = $_POST["repeatpassword"];
if($name == '' || $username == '' || $password == '' || $email == ''){
echo 'Please fill in the missing fields';
}else{
$checkusername = mysql_query("SELECT * FROM users WHERE
username='$username'");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$email'");
$testusername = mysql_fetch_array($checkusername);
$testemail = mysql_fetch_array($checkemail);
if($testemail) {
echo 'Email is already used';
}else {
if ($testusername){
echo 'Username already exists';
} else{
if ($_POST["password"] <> $_POST["repeatpassword"]) {
echo 'Passwords do not match';
}else {
if (mysql_query("INSERT INTO users (name, username, password, email) VALUES
('$name','$username', '$password','$email')")){
echo 'Successfully registered. Now try logging in.';
}else{
echo 'Oops! Please try again!';
}
}
}
}
}
mysqli_close($conn);
}
I'm not very experienced with php and its functions yet, or with stackoverflow for that matter and thus I haven't been able to figure out the solution myself yet and I can't find it online because all I'm getting is people having trouble connecting to the wifi, but I don't have that. I just want a message to get displayed if there is no internet connection available.
You should check with javascript on the client side, because the php is server side and will be executed only if is online
<script>
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('offline')
},
success: function() {
alert('ONline')
}
})
</script>
If you got no connection, how should you be able to load the PHP page? You have to check on the client if you got an internet access, e.g. by pinging the server.
Alternatively if you're handling the sites output ('Username already exists' and so on), you could check for
if(answer = "") {
//seems to have no connection
//your code goes here
}
I'm trying to create a very simple MySQL login function using PHP. The username and password are posted the PHP through AJAX. The AJAX function is:
function login(){
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
$.ajax({
url : "login.php",
type : "POST",
data : {
username : user,
password : pass
},
success : function(response){
alert(response);
},
error : function(response){
alert(response);
}
});
}
The login script:
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$user = $_POST['username'];
$pass = $_POST['password'];
$query="SELECT * FROM Users WHERE email = '$user' AND password ='$pass' LIMIT 1";
$result = $conn->query($query);
$count = $result->num_rows;
if($count == 1){
echo "success";
}else{
echo "incorrect login details";
}
$conn->close();
?>
It seems that $count is always zero, even when the username and password are correct. I've verified that the username and password are being successfully retrieved in PHP.
An even simpler query, SELECT * FROM Users also returns a count of 0.
Attempting to echo or var_dump $result results in object Object being displayed.
Can anyone see any glaring issues with this code? A fresh set of eyes would be greatly appreciated.
Note: This simple function is not designed to be secure, hence the insecure query formatting.
I'd suggest changing the following to strings and running the PHP script. If the strings appear in your DB, you can then rule out if it's caused by the PHP script, in which case it will be the html and ajax elements.
//$user = $_POST['username'];
//$pass = $_POST['password'];
$user = 'userTest';
$pass = 'userPass';
I am having problems with an ajax login form. I am getting an a error from ajax saying that my username and password variables in my login_check.php file are undefined. Yet, when I initialize the variables to blank, the error goes away. The problem is, when I initialize the variables to blank, even if I put the right information into the login box, it will not let me log in. I am sure the problem is minor, but I just can't see it. I just need the PHP and AJAX to work together and then I'm done. Thanks in advance.
login_check.php
<?php
require_once 'config.php';
require_once 'login.class.php';
$error = NULL;
$success = FALSE;
$username = $_POST['username'];
$password = $_POST['pass'];
$login = new Login();
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
//Clean Data to prevent malicous injections
$username = mysql_real_escape_string(strip_tags(stripcslashes(trim($_POST['username']))));
$password = $login -> encrypt(mysql_real_escape_string(strip_tags(stripcslashes(trim($_POST['pass'])))));
$sql = mysql_query("SELECT * FROM admin WHERE username = '$username' AND password = '$password'") or die("Query to database failed.");
$numrows = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
if ($numrows > 0) {
session_start();
$_SESSION['username'] = $row['username'];
$success = TRUE;
echo json_encode(array("success" => "Login successful."));
} else {
$success = FALSE;
echo $error = 'Invalid username or password!';
echo json_encode(array("error" => "Invalid username or password! (PHP response)"));
}
?>
JQuery file
$('#login_form').submit(function(e) {
e.preventDefault();
var username = $('.username').val();
var password = $('.password').val();
$.ajax({
type : "POST",
url : "includes/login_check.php",
data : "Username=" + username + "&Password=" + password,
dataType : 'json',
cache : false,
success : function(data) {
if(data.error) {
$('.login div.error').show().html(data.error);
} else {
$('.login div.success').show().html(data.success);
}
//return false;
},
error : function(jqXHR, textStatus, errorThrown) {
alert("error " + textStatus + ": " + errorThrown);
},
beforeSend : function() {
$(".load").html("Loading...");
}
});
});
By the way, the error from AJAX is:
error parsererror: SyntaxError: JSON.parse: unexpected character
Thank you again friends.
Several problems:
This:
$username = $_POST['username'];
$password = $_POST['pass'];
should be this:
$username = $_POST['Username'];
$password = $_POST['Password'];
Those keys have to match the parms you specified here:
data : "Username=" + username + "&Password=" + password,
...and even that should be changed to:
data : {"Username":username,"Password":password},
This line is producing invalid JSON:
echo $error = 'Invalid username or password!';
I think you meant to code just this?
$error = 'Invalid username or password!';
EDIT #1:
Also this line needs to be the very first thing in the PHP code:
session_start();
First of all, what's the purpose of doing this:
$username = $_POST['username'];
$password = $_POST['pass'];
when later on in your script, you do this?
$username = mysql_real_escape_string(strip_tags(stripcslashes(trim($_POST['username']))));
$password = $login -> encrypt(mysql_real_escape_string(strip_tags(stripcslashes(trim($_POST['pass'])))));
You are fetching the POST data twice. Instead, use the $username and $password. Don't forget to check if they exist in the POST array. Using data that isn't existing may yield unexpected results.
Then also, this part of the code presents an error. You are echoing invalid JSON.
echo $error = 'Invalid username or password!';
echo json_encode(array("error" => "Invalid username or password! (PHP response)"));
looks like this in the returned data:
Invalid username or password!{"error":"Invalid username or password! (PHP response)"}
remove the first echo
The POST array corresponds to the query string/data you passed in the AJAX call. Therefore:
data : "Username=" + username + "&Password=" + password,
is:
$username = $_POST['Username'];
$password = $_POST['Password'];
delete or comment out this line:
echo $error = 'Invalid username or password!';
And add header('Content-Type: application/json');
Username != username and Password != pass :-)
If you can get a copy of what is being returned(should be able to to with debugging the error) then paste it into http://jsonlint.com/ and it should help track down the JSON syntax error.