I have the following script where the user enters some data from the android phone in order to register.
<?php
include("connect.php");
include("functions.php");
if(logged_in())
{
header("location:profile.php");
exit();
}
$error = "";
$j = new stdClass();
$string = "";
if (isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['email']) && isset($_POST['password'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
//echo $firstName."<br/>".$lastName."<br/>".$email."<br/>".$password."<br/>".$passwordConfirm."<br/>".$image."<br/>".$imageSize."<br/>";
//We need to encrypt our password.
$password = md5($password);
$insertQuery = "INSERT INTO users(firstName,lastName,email,password) VALUES('$firstName','$lastName','$email','$password')";
$result = mysqli_query($con,$insertQuery);
if(!$result){
$j->status = "Fail";
$j->message = "No users in database";
$string = json_encode($j);
echo "No inserted data";
//echo $string;
}else{
$j->status = "success";
$j->message = "Successfully registered";
echo "Data inserted";
$string = json_encode($j);
}
echo $string;
}
?>
Unfortunately nothing happens. I can't even generate JSON from the url itself. For example I enter the url's link
http://localhost/android_reg/
and get nothing back. Shouldn't I get
{
"status":"fail",
"status":"No users in database"
}
when there is not data in the database? Surely there is something wrong with my php code.
No. You shouldn't get anything thing back. The main part of your code checks various $_POST variables to see if they're set. Requesting the page in your web browser is a HTTP GET request, so you'll never see any output because the POST variables will never be set.
Make sure your script generates json-output in any case.
Since the fail-branch is usually shorter I prefer to handle it first. In your case: if there is any POST parameter missing -> bail out.
Your script is also prone to sql injections. Prepared statements can avoid that.
<?php
require 'connect.php';
require 'functions.php';
if(logged_in())
{
header("location:profile.php");
exit();
}
// isset() can take multiple arguments and only returns true if all variables are set
if ( !isset($_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['password']) ) {
$result = array('status'=>'fail', 'message'=>'missing POST parameter(s)');
}
else {
$stmt = $con->prepare('
INSERT INTO
users
(firstName,lastName,email,password)
VALUES
(?,?,?,?)
');
if ( !$stmt ) {
$result = array('status'=>'fail', 'message'=>'prepare failed');
}
else if ( !$stmt->bind_param('ssss', $_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['password']) ) {
$result = array('status'=>'fail', 'message'=>'bind failed');
}
else if ( !$stmt->execute() ) {
$result = array('status'=>'fail', 'message'=>'execute/insert failed');
}
else {
$result = array('status'=>'success', 'message'=>'Successfully registered');
}
}
// single, unconditional exit/output point (ok, except for the if(logged_in())/exit() thing)
echo json_encode($result);
Related
After I run my PHP code, hello1 is printed on the screen, but not hello2. I assume there's something wrong with my code for connect.
I can't find what's wrong with my code. Unfortunately to me my code seems correct even after going over it multiple times. How can I fix it?
BTW, I am running MAMP on a MacBook Air.
<?php
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
if (!$connect) {
printf("Connection failed: %s\n", $mysqli->connect_error);
die();
echo "hello3";
}
session_start();
if (isset($_POST["Sign Up"]))
{
if (empty($_POST["Email"]) || empty($_POST["Password"]))
{
echo '<script> alert ("Both Feldsa are required)</script">';
}
else
{
$_SESSION['email'] = $_POST['Email'];
$_SESSION['password'] = $_POST['Password'];
$_SESSION['Repeatpassword'] = $_POST['Repeatpassword'];
$_SESSION['name'] = $_POST['name'];
$_SESSION['weight'] = $_POST['weight'];
$_SESSION['feet'] = $_POST['feet'];
$_SESSION['inches'] = $_POST['inches'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['goal'] = $_POST['Goal'];
// Escape all $_POST variables to protect against SQL injection
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$RepPassword = $mysqli->escape_string(password_hash($_POST['Repeatpassword'], PASSWORD_BCRYPT));
$name = $mysqli->escape_string($_POST['name']);
$Weight = $mysqli->escape_string($_POST['weight']);
$feet = $mysqli->escape_string($_POST['feet']);
$inches = $mysqli->escape_string($_POST['inches']);
$age = $mysqli->escape_string($_POST['age']);
$goal = $mysqli->escape_string($_POST['goal']);
$hash = $mysqli->escape_string(md5(rand(0, 1000)));
// Check if user with that email already exists
// We know user email exists if the rows returned are more than 0
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'") or die($mysqli->error);
if ($result->num_rows > 0) {
$_SESSION['message'] = 'User with this email already exists!';
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO User (Email_Address, Password, Full Name, Weight, Feet, Inches, Age, Goal, hash) "
. "VALUES ('$email', 'password', 'name', 'Weight', 'feet', 'inches', 'age', 'goal', 'hash')";
}
if (! $mysqli->query($sql)
{
$_SESSION['message'] = 'Registration successfully';
echo $_SESSION['message'];
header("location: loginaccount.html");
}
}
else {
$_SESSION['message'] = 'Registration failed!';
echo $_SESSION['message'];
}
}
if (isset($_POST["Login"]))
{
$email = $mysqli->escape_string($_POST['Email']);
$result = $mysqli->query("SELECT * FROM User WHERE Email_Address='$email'");
if ($result->num_rows == 0) { //
{
$_SESSION['message'] = "User with that email doesn't exist!";
echo $_SESSION['message'];
}
else {
$user = $result->fetch_assoc();
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['email'] = $user['Email_Address'];
$_SESSION['name'] = $user['Full Name'];
$_SESSION['weight'] = $user['Weight '];
$_SESSION['feet'] = $user['Feet '];
$_SESSION['inches'] = $user['Inches '];
$_SESSION['age'] = $user['Age '];
$_SESSION['goal'] = $user['Goal '];
$_SESSION['logged_in'] = true;
$_SESSION['active'] = $user['Active'];
header("location: loginaccount.html");
}
}
mysqli_close($connect);
session_destroy();
?>
At the start of your script:
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
At line 3 here, you try and use $mysqli. That variable doesn't exist. You haven't declared it, so at that point, you are going to get a PHP runtime error when you try and reference the method of an object, which is in fact a non-existent variable.
It's actually worse than that, because you are mixing procedural mysqli with object oriented mysqli. What you really need is this, but the obvious issue is that your mysqli connection variable is named $connect!
echo "hello1";
$connect = new mysqli("localhost:8888", "Capstone", "", "capstone");
$connect->set_charset('utf8');
You can also use try/catch to find more about errors
try{
echo "hello1";
$connect = mysqli_connect("localhost:8888", "Capstone", "", "capstone");
$mysqli->set_charset('utf8');
echo "hello2";
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
P.S. - in $mysqli->set_charset("utf-8"); $mysqli is not defined, use $connect here
I have made a login system which enables a user to sign in using a previously defined email and password, however in the testing section, I have noticed the passwords say they don't match although I know they are correct as I wrote the test one down as I made it. I cant seem to see why this is happening, I think it may be something to do with my hashing of the passwords but I don't know what.The login page check is from document, login.php:
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$data['email']]);
if(!$row = $stmt->fetch())
{
// email didn't match
$errors['login'] = "Login failed. on email";
}
else
{
// email matched, test password
if(!password_verify($data['password'],$row['password']))
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The insertion to the database with hashing is, from insert.php:
if (isset($_POST['name'])){
$name = $_POST['name'];
}
if (isset($_POST['email'])){
$email = $_POST['email'];
}
if (isset($_POST['password'])){
$pword = $_POST['password'];
}
if (isset($_POST['busName'])){
$busName = $_POST['busName'];
}
if (empty($name)){
echo("Name is a required field");
exit();
}
if (empty($email)){
echo ("email is a required field");
exit();
}
if (empty($pword)){
echo("You must enter a password");
exit();
}
$pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
//insert html form into database
$insertquery= "INSERT INTO `cscw`.`users` (
`accountID` ,
`businessName` ,
`name` ,
`emails` ,
`password`
)
VALUES (
NULL , '$busName', '$name', '$email', '$pword'
);";
and on the web page i am shown from login.php, "Login failed. on password". If you need to see any more code please let me know.
It does not recognize $row['password'].
Be always organized with your query **
1)Prepare
2)Execute
3)Fetch
4)Close
5)THEN YOU EXPLOIT the fetched data.
The fetched data need to be sorted as shown with the returnArray function.
Hoping that there are UNIQUE emails and the $data array exists.Try this.
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=:emails";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':emails', $data['email']);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->CloseCursor();
$stmt=null;
/* Return the results is a more handy way */
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
if( empty($rows) )
{ // email didn't match
$errors['login'] = "Login failed. on email";
}
else
{ // email matched, test password
if( !password_verify( $data['password'], returnArray($rows,'password') ) )
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The login Page is not finished the query is not inserting. Be carefull you might be vunerable to SQL injections because your do not escape user manipulated variables.(To strengthen security add a form validation, it will be great).
You have used $pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
I removed ."/n" part. I seems that you are using a concatenation operator '.' to add /n add the end of the password_hash.
Your $insertquery is not finished and not readable. You don't need to insert backticks in your query. And no need to SELECT accountID it will autoincrement (See if A_I for accountID is ticked in your database).
Do something like this in your login page.
/* trim and escape*/
function escapeHtmlTrimed( $data )
{
$trimed = trim( $data );
$htmlentities = htmlentities( $trimed, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' );
return $htmlentities;
}
if ( isset( $_POST['name'] ) ){
$name = escapeHtmlTrimed( $_POST['name'] );
}
if ( isset($_POST['email']) ){
$email = escapeHtmlTrimed( $_POST['email'] );
}
if ( isset($_POST['password']) ){
$pword = escapeHtmlTrimed( $_POST['password'] );
}
if ( isset($_POST['busName']) ){
$busName = escapeHtmlTrimed( $_POST['busName'] );
}
if ( empty($name) ){
echo("Name is a required field");
exit();
}
if ( empty($email) ){
echo ("email is a required field");
exit();
}
if ( empty($pword) ){
echo("You must enter a password");
exit();
}
/*Remove this your adding "./n"*/
$pword = password_hash($pword, PASSWORD_DEFAULT);
//insert html form into database
$insertquery= "INSERT INTO users (businessName ,name ,emails,
password) VALUES (:busName , :name, :email , :pword)";
$stmt = $pdo->prepare($insertquery);
$stmt->bindParam(':busName', $busName);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':pword', $pword);
$stmt->execute();
$stmt->CloseCursor();
$stmt=null;
How do I get a user_id for a PHP file from another PHP file. I'm using $_SESSION['user_id'] to do it but it's not working for me. Can anyone show me how to do it and where the $_SESSION['user_id'] should be placed in the PHP files, or if there is a better way of doing it. I think I have it placed in the right place in the login.php file but not sure about fitness.php. I'm using them for my Android app. The two PHP files are below. Any help will be greatly appreciated, thank you.
login.php
<?php
session_start();
$error = NULL;
include_once('connection.php');
if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
$username = $_POST['txtUsername'];
$password = $_POST['txtPassword'];
$query = "SELECT username, password, user_id FROM user WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if($username == $error || $password == $error) {
echo "Login Failed <br>";
}
elseif($result->num_rows > 0){
$_SESSION['user_id'] = 'user_id';
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Login Successful";
// header("location: login.php");
}
else{
echo "Login Failed <br>";
}
}
?>
fitness.php
<?php
session_start();
$error = NULL;
include_once('connection.php');
if(isset($_POST['pulseOne']) && isset($_POST['pulseTwo']) && isset($_POST['pulseThree'])){
$pulseOne = $_POST['pulseOne'];
$pulseTwo = $_POST['pulseTwo'];
$pulseThree = $_POST['pulseThree'];
$fitnessResult = 100;
$overall = 30000;
$fitnessScore = -1;
$fitnessScore = $pulseOne + $pulseTwo + $pulseThree;
if($fitnessScore != 0){
$fitnessResult = $overall/$fitnessScore;
$fitnessResult = round($fitnessResult, 0);
}
else{
$fitnessResult = NULL;
}
// $fitnessResult = mydivide($overall/$fitnessScore);
$date = date("Y-m-d");
$time = date("h:i:sa");
// $user_id = $_POST['user_id'];
$query = "INSERT INTO `fitness`(`fitnessScore`, `fitnessDate`,`fitnessTime`, `user_id`) VALUES ('$fitnessResult','$date','$time', 42)";
$result = mysqli_query($conn, $query);
if($pulseOne == $error || $pulseTwo == $error || $pulseThree == $error){
echo "Insert Failed";
}
elseif($result > 0){
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Insert Successfully";
}
else{
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "Registration Failed";
exit;
}
echo "Insert Failed";
}
}
?>
So many things to note here, first of all restructure your If and else statements if you are using else if use them properly. you are using mysqli no prepared statements plain query, try to learn better way so your code dont stay vulnerable. Last but not the least you are facing this proble because you are trying to use Session variable value with post keyword, try this:
$user_id = $_SESSION['user_id'] ; and it will be solved.
you can do like this First save your session variable in another variable than try to insert in database
$user_id = $_SESSION['user_id'] ;
Try to echo it thisway
echo $user_id;
once you get it use it or insert it in database
change your code from
$_SESSION['user_id'] = 'user_id';
this to
$_SESSION['user_id'] = $row['user_id'];
I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.
Here is my login.php script.
When it runs, it dumps the array (error 2) of what was input, completely skipping everything (i think). I have absolutely no idea what's wrong.
<?php
include('../../content/php/base.php');
// Get data
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
// Encrypt password
include('../../content/php/salt.php');
$pass = crypt($pass,$salt);
// Check database for user / check session
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['user'])) {
header("Location: websiteURL");
} elseif(!empty($user) && !empty($pass)) {
$user = mysqli_real_escape_string($con, $user);
if($result = mysqli_query($con, "SELECT * FROM users WHERE `user`='".$user."' AND `pass`='".$pass."'")) {
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 1) {
$row = mysqli_fetch_array($result);
$email = $row['email'];
$_SESSION['user'] = $user;
$_SESSION['email'] = $email;
$_SESSION['LoggedIn'] = 1;
header("Location: websiteURL");
} else {
echo "Error 1";
die();
}
} else {
echo "<pre>"; // dumps the array onto multiple lines instead of one
print_r($_REQUEST);
echo "</pre>";
echo "Error 2";
die();
}
} else {
echo "Error 3";
die();
}
?>
Here is the full output of the print_r($_REQUEST); :
Array
(
[user] => username
[pass] => password
[PHPSESSID] => 5958246ece69dfdff197ec46e4771aac
)
Error 2
Your query is obviously failing
if($result = mysqli_query($con, "SELECT * FROM users WHERE `user`='".$user."' AND `pass`='".$pass."'") {...}
Is $con a valid connection?
Try putting backticks around the table name users.
You should do some error checking. Take a look at the output of
// You can add this to the Error 2 block (for testing.. not production use)
echo mysqli_error($con);
This will give you an "idea" of what's going wrong, and will help others much in helping you.
Try using session_start(); before any of the includes. This ensures the server session is started