PHP Post Is Not Recieving Vars Correctly - php

I have this script here:
<?php
//Tell the requester to output response as JSON
//header('Content-Type: application/json;charset=utf-8');
//POST information.
$name = $_POST['username'];
$pass = $_POST['password'];
$mysql_server = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_dbname = 'test';
//Set up variables needed for middle-end
$return_code = 0;
$error_message = '';
//Connect to the Database
$conn = new mysqli($mysql_server, $mysql_user, $mysql_pass, $mysql_dbname);
if ($conn->connect_error)
{
//Return an error (in JSON format) that MySQL server wont connect
$return_code = -1;
$error_message = 'Failed to connect to MySQL: ' . $conn->connect_error;
}
else
{
//Query for a User/Pass match
$sqlquery = "SELECT ucid FROM test WHERE ucid = '" . $name . "' AND password = '" . hash('sha256', $pass) . "'";
$result = mysqli_query($conn, $sqlquery);
if (mysqli_num_rows($result) > 0)
{
//On Successful User/Pass
$return_code = 1;
}
elseif(mysqli_num_rows($result) == 0)
{
//On Failed User/Pass
$return_code = 0;
$error_message = 'Incorrect Username or Password';
}
else
{
//Something went wrong
$return_code = -1;
$error_message = 'You messed something up real good.';
}
}
if($return_code == 1)
{
$jsonResults = array('return_code' => $return_code);
}
elseif ($return_code == (0 || -1))
{
$jsonResults = array('return_code' => $return_code, 'error_message' => $error_message);
}
$echoJSON = json_encode($jsonResults, 1);
echo $echoJSON;
echo '<br><br>';
echo 'return code = ' . $return_code . ' and message: ' . $error_message;
echo '<br>Query Passed: ' . $sqlquery;
echo 'Username passed was: ' . $name . 'and Password passed was: ' . $pass;
?>
Basically put, you pass it a username & password, the script then connects to a MySQL server and does a SQL query of the username + the password after its been sha256 hashed. The point of the query is to see if the username + password is valid combination. If one of them is wrong, the query should show 0 results, thus resulting in an 'Incorrect username or password' message
However, when I run the script and echo the results, apparently nothing is getting passed:
<b>Notice</b>: Undefined variable: jsonResults in <b>C:\xampp\htdocs\alpha-test\db.php</b> on line <b>62</b><br />
null<br><br>return code = 0 and message: Incorrect Username or Password<br>Query Passed: SELECT ucid FROM test WHERE ucid = '' AND password = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'Username passed was: and Password passed was:
I do not know what I am doing wrong.

The problem seems to be something to do with postman ( I've never used that ). The best way to test this is to create a form on a new page and actually post the data and make sure that is working.
1) When I can't figure out why something doesn't work, I simplify the problem and reduce the possibility of other errors causing problems. So change your php script by adding these lines.
$name = $_POST['username'];
echo $name;
exit;
You need to make sure $name is getting set.
2) Create a form that posts to this page.
<form action="yourscript.php" method="post">
username: <input type=text name="username"><br>
password: <input type=text name="password"><br>
<input type=submit value="submit">
</form>
Submit the form and make sure you are capturing $_POST['username'] and $_POST['password'] before you worry about mysql or other issues.
3) Just so you know, I tried this locally and I had no problems posting that form and then having $name be set correctly. So the problem must be something to do with how you setup postman.
GL

<b>Notice</b>: Undefined variable: jsonResults in <b>C:\xampp\htdocs\alpha-test\db.php</b> on line <b>62</b><br />
First thing I notices the above error, To remove this, you should declare $jsonResults globally, currently its scope is local to block where you are setting values in this.
Next issue is blank username and password, for this please share your form, from where you are sending these. Possibly you are missing name property or some spelling error.

You are using $_POST to retrieve GET parameters. This is why you fail to get the username / password.
As you said, your are testing with this request, which means you are passing the parameters in the URL:
alpha-test/db.php?username=test&password=test
You must replace $_GET with $_POST or $_REQUEST. I've written a simple working code below. I use here $_REQUEST to be able to retrieve GET/POST variables using the same code.
<?php
//POST information.
$name = $_REQUEST['username'];
$pass = $_REQUEST['password'];
$sqlquery = "SELECT ucid FROM test WHERE ucid = '" . $name . "'' AND password = '" . hash('sha256', $pass) . "'";
echo $sqlquery;
?>

Related

Mysql call stops all forms of output php

Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.

AJAX Login Form: Undefined PHP variables

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.

Simple PHP not working

I am creating a ajax notification and this is part of my system allowing a user to favorite, or archive, that notification. The problem is that this php code below won't work and there is no error in the queries because the or die returns nothing. What is returned is just error. That is all it is echoing. I know the javascript is correct and sending the correct information because I have checked the network tab to see. Are there any major errors that I am missing?
<?php
require_once('.conf.php');
$notid = mysql_real_escape_string($get['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($get['action']);
if ($action == 'add') {
$insert = mysql_query("UPDATE updates SET object_fav = 1 WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'success';
} elseif($action == 'sub') {
$remove = mysql_query("UPDATE updates SET object_fav = 0 WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'remove';
} else {
echo 'error';
}
?>
PHP has no default array called $get. Perhaps you intend to use the $_GET superglobal.
$action = mysql_real_escape_string($_GET['action']);
$notid = mysql_real_escape_string($_GET['notification_id']);
It prints error when $action is not matched in your if/else chain, because the variable isn't correctly set.
Be sure that you are developing with display_errors turned on, and error_reporting(E_ALL);. The undefined variable $get would display warnings on screen.
ini_set('display_errors', 1);
error_reporting(E_ALL);

PHP display data from MySQL using GET

I'm trying to look up user's username using $_GET but not actually seing the result of the query. Here's the code:
<?php
$host = "localhost";
$username = "root";
$password = "toor"; // :)
$database = "db";
$link = mysql_connect($host, $username, $password);
if(!$link){
exit('Could not connect to database: '. mysql_error());
}
$email = mysql_real_escape_string(htmlspecialchars(stripslashes($_GET["e"])));
$query = "SELECT username FROM cc_card WHERE email = '$email'";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$user = mysql_fetch_assoc($result);
echo $user['username'];
} else {
echo "Something's wrong";
}
it's only returnung "Something's wrong". I wanted it to display the username field of the cc_card table where email = email. What am I doing wrong?
If you're getting "Something's wrong" from the posted code it means nowhere in the cc_card table does the email column match the email value you specify in your query.
You need to verify that the contents of your sanitized $email variable do, in fact, exist somewhere in the table. Try:
} else {
echo "Something's wrong";
var_dump($email);
}
To see the contents of the sanitized $email variable and manually query the database from the shell (or phpmyadmin or whatever) to find whether the value you're specifying exists or not. I'm betting it doesn't exist.
You'd better add the error check after the query.
if (!$result) {
die('Error: ' . mysql_error());
}
If no error, then it means there is no matched email in your database.

Php login error - Notice: Undefined index:

I looked at previos Undefined error questions to see if I could find help for my question, but I can't seem to fix it for my problem.
So when I try to log in a user I get an error that says Undefined index:
No sure why Im getting this message on my login.php page
I have a database and a table called users with data inserted
this is what I use to connect to the database
conn.php
<?php
session_start();
$dbhost = "127.0.0.1"; // my database
$dbname = "fxdme";
$dbuser = "root";
$dbpass = "";
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) or die("MySQL Error: " . mysqli_error("Cant Connect"));
?>
the login script
login.php
<?php include 'template/header.php';?>
<form action="login.php" method="POST">
User Name: <input type="text" name="username" />
Password: <input type="password" name="password"/>
<input class="submit" name="submit" type="submit" value="Log In"/>
</form>
<?php
$result=$mysqli->query('SELECT * FROM users WHERE username = "' .
$_POST['username'] . '" AND password = "' . $_POST['password'] . '"');
//set session user
$row = $result->fetch_assoc();
$_SESSION['user_id'] = $row['id'];
if ($_SESSION['user_id']) {
echo "You are logged in, $session_username. <a href='logout.php'>Log out</a>"; }
else {
echo " cant log in";
}
?>
// Index page
My index page
index.php
//in the template header is where Im calling my conn file
<?php include 'template/header.php'; ?>
<?php
if (isset($_GET['invalid'])) {
echo "<tr><td colspan='2' align='right'>Invalid login.</td></tr>";
}
?>
Im trying to get the error fixed so I'm not worried about sql injections at the moment. I just want to be able to login and and worry about the other stuff later.
You will find that $_POST["username"] will return invalid index if username is not in the post variables.
I usually create a set of variables to hold the my post variables so I can do validation and normalisation of the data first
So before your query statement
$username=(isset($_POST) && isset($_POST["username"]) ? $_POST["username"] : "";
$password=(isset($_POST) && isset($_POST["password"]) ? $_POST["password"] : "";
then use $username and $password in your query. You could event turn the previous statements into a function call passing in the variable name to check.
function getPostVar($name) {
return (isset($_POST) && isset($_POST[$name]) ? $_POST[$name] : "";
}
$username=getPostVar("username");
$password=getPostVar("password");
Obviously your code is ripe for sql injection with at username of ' union select * from users --
There is not anything in your code to make a query string in URL to fetch by $_GET. How can you have an index when you don't have anything ?
For what you said, you must use a header('location:index.php?invalid=1'); if the user can not log in to your system.
Might not be the same issue for you but I had this same error when converting to mysqli and my fetch statement looked the same as yours.
try changing.
$row = $result->fetch_assoc();
to
$row = $result->fetch_array(MYSQLI_ASSOC));

Categories