I am having trouble trying too check theses two inputs uname and passwod. I can get one to work on its own but I keep getting an error when I try to pass them both back up.
<?php
// define variables and set to empty values
$usernameErr="";
$passwordErr="";
$username= "";
$password="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["uname"]))
{
$usernameErr = " username is required <br>";
print $usernameErr;
}
else
{
$username = checkUserData($username);
}
if (empty($_POST["passwd"]))
{
$passwordErr = " password is required <br>";
print $passwordErr;
}
else
{
$password = checkUserData($password);
}
}
Here is were the problem is. I am passing down to check the data to stop attacks. I have tried multiple ways of joining them together but everything has failed.
function checkUserData($username)
{
$username = htmlspecialchars($username);
$username = trim($username);
$username = stripslashes($username);
return $username;
}
function checkUserData($password)
{
$password = htmlspecialchars($password);
$password = trim($password);
$password = stripslashes($password);
return $password;
}
I'm printing just to check it's working.
print ("welcome " .checkUserData($_POST["uname"]));
print ("welcome " .checkUserData($_POST["passwd"]));
?>
Any help would be great.
Both functions are doing the same thing so generalise them
function SanitizeData($var)
{
$var= htmlspecialchars($var);
$var= trim($var);
$var= stripslashes($var);
return $var;
}
Now in your checking process call
$username = SanitizeData($_POST["uname"]);
Or
$password = SanitizeData($_POST["passwd"]);
Although this sanitization is unnecessary at best and destructive at worst if you are going to use these fields in a query, it would be better to use a parameterized query and the PDO database extension.
Related
I'm trying to validate the form using AJAX. This is what I've done so far:
$('#login-form').submit(function(e) {
e.preventDefault();
var user = username.value;
var pass = password.value;
if (user != '' && pass != '') {
$('#login').html('Proccessing...');
$.ajax({
url: 'login.php',
type: 'POST',
data: {
username: user,
password: pass
},
processData: false,
contentType: false,
success: function(response) {
if (response == 'success') {
window.location.href = 'admin.php';
} else {
$('.login_message').html('Incorrect Credentails');
$('#login').html('Login');
}
}
});
} else {
$('.login_message').html('Fill All Fields');
$('#login').html('Login');
}
})
and it seems like response doesn't return success. Below is the login.php file
<?php
session_start();
$password = $username = '';
$_SESSION['user'] = $_SESSION['error'] = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['login'])) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
echo 'username: ' . $username . ' and ' . ' password: ' . $password;
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
;
$_SESSION['user'] = $username;
header('Location: admin.php');
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
} else {
echo mysql_error();
}
}
}
?>
If it happens you have found the solution, please explain to me how you find the solution and what I've done wrong.
Thank you in advance.
Since this is ajax request,we need to send some response from server. As you did in your question check if(response=='success'). To do that, you need to send success to your client. If everything is ok (data send to server and query) then in your login.php edit this line
if($password == $dbpass) {
$_SESSION['user'] = $username;
//comment this line
//header('Location: admin.php');
echo "success";
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
Here I put one line code echo "success"; and I believe this will resolve your issue.
Returning values from PHP back to JS
When using AJAX, I believe if you do echo in the PHP target file (here login.php) it will act as a return. Therefore the code after a echo will not run as you might expect.
Also in your code you have: echo $_SESSION['error'] = '';
Use == to compare two object, = is the assignment operator.
Retrieving AJAX data in PHP file
The use of the ajax() method from jQuery in your code looks correct to me. So when the call is made the information is sent asynchronously to the server. More precisely it will send the parameters to the PHP file you've specified in the ajax object properties: login.php.
In login.php you can access your passed parameters in the $_POST array.
You would have the following:
$username = $_POST['username'];
$password = $_POST['password'];
// process information...
$state = 'success'
// now you can return a JSON object back to your page
// I strongly recommend using a PHP array and converting it to JSON
// this way it's very easy to access it back with JS
$response = array(state=$state)
echo json_encode($response);
And back in your jQuery code you access the state value with response.state
if(response.state == 'success') {
alert('It is a succcess!');
}
Debugging PHP target files
Now you generally have problems in the code in this PHP files. And it's not an easy thing to debug it. So the way I proceed is: I set the parameters in stone in login.php for instance:
$username = 'usernameTest'; // $username = $_POST['username'];
$password = 'passwordTest'; // $password = $_POST['password'];
Then I would open the PHP file in a browser and run it do see if it echoes the object and if there are any bugs.
Then you can put back $username = $_POST['username']; and $password = $_POST['password'];.
Actual code
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
$state = 'success';
} else {
$state = 'failed';
}
} else {
echo mysql_error();
}
}
Warning mysql(), md5() and SQL injections
Don't use the deprecated and insecure mysql_* functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.
You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Using strip_tags() is far from a safe way to escape data.
Don't use md5() for password hashing. It's very insecure. Use PHP's password_hash() and password_verify() instead. If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality.
- Magnus Eriksson
I have a registration form whose snippet is as follows-
$email=$_GET['email'];
$pass=$_GET['pass'];
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $pass.$salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password.$salt);
}
mysql_query("INSERT INTO user_tbl(email, password, salt) VALUES ('$email','$password','$salt')");
For a specific password following string is getting stored in db-
df22e53c7fb2d599d64597a04fd28ca47bc79675ac50a2381c9a17fd4e07b263
Now i also have a login form. Whose code snippet is as follows-
$email=$_GET['email'];
$pass=$_GET['password'];
$result=mysql_query("SELECT * from user_tbl where email='$email'");
$row=mysql_fetch_array($result);
$salt = $row['salt'];
$password = hash('sha256', $pass.$salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password.$salt);
}
if(strcmp($row['password'],$password)!=0)
{
echo "wrongpassword";
exit();
}
else
{
echo "Success";
}
Now i could see that the hashed password which the login form is evaluating to is also df22e53c7fb2d599d64597a04fd28ca47bc79675ac50a2381c9a17fd4e07b263 . Which is same as what registration form is submitting to database.
They should match. But they are not. The String compare test is always failing.
The length of both fields i.e. password and salt are 200 each and are of type VARCHAR which is sufficient i think because above algo will generate a 64 character long string only. Still What is the problem? Please help me out here.
You just need a simple correction in your IF condition:
if(strcmp($row['password'],$password)!==0) // change here :)
{
echo "wrongpassword";
exit();
}
else
{
echo "Success";
}
Please see the documentation: http://php.net/manual/en/function.strcmp.php
Ok, so I've successfully linked a Contact Form for my website to a MySQL database and I'm super stoked about figuring it out, however on my registration page my code isn't working. I ran this connection check:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "It's Working!";
}
and it says: "It's working!" So i know i've established a connection to my SQL database.
Let me try to clarify further:
I've got 2 main files for this particular program (obviously we won't be needing to care about styles.css or the linked files for other pages in my site): register.php and db.php. Here is my code for both. It's simply a project website so i don't care if people see/use my code... It's not working anyway so knock yourselves out, LOL!
First, db.php:
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'forms1');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
Now here's the php in register.php, which I've place at the top BEFORE any HTML at all:
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$lname = $_POST["lname"];
$a1 = $_POST["a1"];
$a2 = $_POST["a2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$lname = mysqli_real_escape_string($db, $lname);
$a1 = mysqli_real_escape_string($db, $a1);
$a2 = mysqli_real_escape_string($db, $a2);
$city = mysqli_real_escape_string($db, $city);
$state = mysqli_real_escape_string($db, $state);
$zip = mysqli_real_escape_string($db, $zip);
$phone = mysqli_real_escape_string($db, $phone);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users(name,lname,a1, a2, city, state, zip, phone, email, password) VALUES ('$name', '$lname', '$a1', '$a2', '$city', '$state', '$zip', '$phone', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
mysqli_close($db);
I should probably mention that JavaScript is included in the HEAD section of my HTML:
(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)
$(document).ready(function() {
$('form.required-form').simpleValidate({
errorElement: 'em',
ajaxRequest: true,
completeCallback: function($el) {
var formData = $el.serialize();
}
});
});
$("form[name='form1']").submit(function(){
.... JS code ....
return error;
});
</script>
<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};
Well, I tried to include the HTML code for the form but it wasn't appearing properly, but believe me when i tell you that ALL the inputs of the the form fields have a name="" that corresponds to the fields within my table within my database within MySQL. The HTML is most certainly not the problem. I've check syntax and spelling over and over. It's not the HTML. Somewhere there is an error, though.
PLEASE HELP!!!
Thank you all very much.
-Maj
P.S. I purposely deleted the opening and closing php/html tags here in these examples so it'd be easier to read, but i have them placed in my original code.
After that if($query){ } block try adding else { print(mysqli_error($db)); }
perhaps there's an error, but what is the response you got from register.php?
you should start to debug your source code, but if you don't use a debugger, put some "die(SOME VARIABLE);" to locate your trouble area and without javascript, for the first. Just use some simple html-formular and to get row datas, put the answer into <PRE> tags ( or use curl in a terminal, i like this way, but for you it is not necessary ).
If you don't debug your php-code or you your browser-relevant-code, means "html, css, javascript, ..." (you can see with firebug, what data you are sending and what is coming back), you can use echo "INSERT .... BLA ...$VAR ...;" and copy-paste the SQL-Statement and testing it in PhpMyAdmin, to see you get a proper statement, maybe there is a type-converting-problem or many other thinks are possible.
If everything is going well, it is probably some trouble in your javascript-code. But probably you need to convert a type of some variable, you should copy and paste your SQL-Statement and execute it in phpmyadmin to make a verification of your SQL-Statements which you put in your Php-Code. Cheers.
I have a PHP file getting data from my SQL database and I am trying to set and get two session variables like $_SESSION['fname'] and $_SESSION['userID'] by $theFName and $theId.
$email = $_POST['email'];
$pass = $_POST['pass'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
$sql = "SELECT id, email, fname, lname, type FROM users WHERE `email`=? AND `pass`=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $email,$pass);
$stmt->execute();
$stmt->bind_result($theId,$theEmail,$theFName,$theLname,$theType);
if ($stmt->fetch()) {
echo 'true';
$_SESSION['LOGIN_STATUS'] = true;
$_SESSION['fname'] = $theFName;
$_SESSION['userID'] = $theId;
} else {
echo 'false';
}
in JavaScript file I have
<script>
var tok = "var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
but I am getting empty string!
can you please let me know what I am doing wrong?
I'm not quite sure I understand what you are trying to do in the JS file, but it is not valid JS in any case - the quotes don't match and it seems like you are trying to do an assignment inside a string.
I think what you are looking for is something more along the lines of this:
<script>
var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
However, please note that dynamically generating JS files using PHP is likely not the best way to go about this. Check out this SO answer on the various methods you can use to pass variables from PHP to JS, along with their various pros and cons.
I'll make this as short and sweet as possible.
I have this script called usernameget.php which echos the currently logged in username:
<?php
include 'functions.php';
include 'db_connect.php';
sec_session_start();
$userId = $_SESSION['user_id'];
if(login_check($mysqli) == true) {
$con=mysqli_connect("localhost","myusername","mypass","mysqldb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT members.username FROM members WHERE id= $userId");
while ($row = mysqli_fetch_assoc($result))
{
echo $row['username'];
}
/* free result set */
mysqli_free_result($result);
mysqli_close($con);
} else {
echo 'Null User <br/>';
}
?>
This script uses functions.php (part of a secure login script located here: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL#Create_PHP_Functions ) in order to function. sec_session_start(); is just a custom session_start, but functions.php also makes it possible to get the username via $user_id.
The problem is, when I include usernameget.php in the main page (which also uses functions.php to secure,) it throws errors because it's trying to redeclare sec_session_start();
I can strip usernameget.php of this security but obviously since it banks on functions.php / sec_session_start(); it doesn't work afterwards. I've tried to write a specific USERNAMEGETfunctions.php without the session stuff for usernameget.php to use but I'm not adept enough to get it working, and it feels like an inelegant solution.
So as I understand it: functions.php and sec_session_start(); are used to secure the main page so the includes on the main page can't use functions.php or it will conflict. Would anyone be able to show me how to get this script going without redeclaring/conflicting?
Included below is the entire functions.php
<?php
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
function login($email, $password, $mysqli) {
// Using prepared Statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) { // If the user exists
// We check if the account is locked from too many login attempts
if(checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
// Password is correct!
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
function checkbrute($user_id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $user_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there has been more than 5 failed logins
if($stmt->num_rows > 5) {
return true;
} else {
return false;
}
}
}
function login_check($mysqli) {
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if($stmt->num_rows == 1) { // If the user exists
$stmt->bind_result($password); // get variables from result.
$stmt->fetch();
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
?>
Don't use plain include for core function libraries, the kind which tend to get included in ALL your scripts. Use include_once instead, so that PHP will only ever include the file once, and then ignore any further include attempts. This will prevent your function redeclaration errors.
You must use require_once instead include_once because your program not will run without that files...
include_once produce warning when try to include the file and it fails.
require_once produce fatal error when try to include the and it fails.
For core libs, you should use require_once. (http://www.php.net/manual/pt_BR/function.require.php)
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.