here is my code below that i use to register a user
<?php
header("Content-Type: application/json");
require_once("config.php");
if(isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"])){
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
}
$con = mysqli_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME);
if($con){
echo "connection good";
}
$response = array();
$statement = mysqli_prepare($con, "SELECT * FROM accounts WHERE email = ? OR username = ?");
mysqli_stmt_bind_param($statement, "ss", $email, $username);
$result = mysqli_stmt_execute($statement);
$row = mysqli_num_rows($result);
if($row > 0){
$response["success"] = false;
$response["message"] = "Email or Username already exists.";
}else{
mysqli_stmt_close($statement);
$statement2 = mysqli_prepare($con, "INSERT INTO accounts (email, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement2, "sss", $email, $username, $password);
$result2 = mysqli_stmt_execute($statement2);
$row2 = mysqli_affected_rows($statement2);
if($row2 > 0){
$response["success"] = true;
$response["message"] = "Account created successfuly.";
}else{
$response["success"] = false;
$response["message"] = "Creation error.";
}
}
$output = json_encode($response);
echo $output;
mysqli_close($con);
?>
at the end of the file when i check the localhost it echos "good connection br" which i cant use it with json .. how to avoid it so i caan use the response in jsonobject later
Related
I need a second pair of eyes to have a look at my code and tell me what I am missing, as I think I have identified the portion of code that doesn't work, I just don't know why.
Basically I am trying to register a user to a database, in a way that it prevents SQL injection. For the life of me however, it doesn't work. When I deconstruct the code and make it less secure, it works. Anyway, code is here:
//require_once 'sendEmails.php';
session_start();
$username = "";
$email = "";
$user_dob = "";
$user_fname = "";
$user_lname = "";
$user_telephone = "";
$errors = [];
$servername = '';
$login = '';
$password = '';
$DBname = '';
$rows = 0;
$query = "";
$conn = new mysqli($servername, $login, $password, $DBname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn) {
echo "Connected successfully";
}
// SIGN UP USER
if (isset($_POST['signup-btn'])) {
if (empty($_POST['username'])) {
$errors['username'] = 'Username required';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email required';
}
if (empty($_POST['password'])) {
$errors['password'] = 'Password required';
}
if (isset($_POST['password']) && $_POST['password'] !== $_POST['passwordConf']) {
$errors['passwordConf'] = 'The two passwords do not match';
}
if (empty($_POST['dob'])) {
$errors['dob'] = 'Date of birth required';
}
if (empty($_POST['fname'])) {
$errors['fname'] = 'First name required';
}
if (empty($_POST['lname'])) {
$errors['lname'] = 'Last name required';
}
if (empty($_POST['telephone'])) {
$errors['telephone'] = 'Telephone number required';
} //--checks input in browser
//I think it works untill this point...
$token = bin2hex(random_bytes(50)); // generate unique token
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); //encrypt password
$user_dob = $_POST['dob'];
$user_fname = $_POST['fname'];
$user_lname = $_POST['lname'];
$user_telephone = $_POST['telephone'];
$email = $_POST['email'];
//Above assigns inputted values into variables declared at the start
//echo $token, $email; //-- this works
//nl2br() ; // -- line break in php
// Check if email already exists
//$result = $mysqli->query("SELECT * FROM User_tbl WHERE email='$email' LIMIT 1");
$sql = "SELECT * FROM User_tbl WHERE email='$email' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > $rows) {
$errors[] = $email;
echo "Email already exists";
}
$errorsInt = count($errors);
echo mysqli_num_rows($result);
echo count($errors);
echo $errorsInt;
if ($errorsInt === $rows) {
$query = "INSERT INTO User_tbl SET token=?, username=?, password=?, user_dob=?, user_fname=?, user_lname=?, user_telephone=?, email=?";
// "INSERT INTO User_tbl VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
echo $query;
//---------------------------------------------------------------------------
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
echo $result;
if ($result) {
$user_id = $stmt->insert_id;
$stmt->close();
$_SESSION['id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['verified'] = false;
$_SESSION['message'] = 'You are logged in!';
$_SESSION['type'] = 'alert-success';
header('location: index.php');
} else {
$_SESSION['error_msg'] = "Database error: Could not register user";
}
}
}
The problem I believe starts here:
$stmt = $conn->prepare($query); //first
$stmt->bind_param('sssissis', $token, $username, $password, $user_dob, $user_fname, $user_lname, $user_telephone, $email);
$result = $stmt->execute();
When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>
im still developing android my android project i really need help, my problem is i couldn't get the user id of the user that login in my system so when they put a record a user id will attached to it data .. i want to do this to output their own data in my system. hope someone could help. its only php code thank you someone who would help.
<?php
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM tbl_userinfo WHERE username = '$username' AND password='$password' LIMIT 1";
$res = mysqli_query($con,$sql);
$response = array();
$response["success"] = false;
$row = mysqli_fetch_array($res);
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
session_start();
$_SESSION['user_id'] =$userID;
}
echo json_encode($response);
?>
thats for log in, here's for saving data..
<?php
session_start();
$userID ="";
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
if(!isset($_SESSION['user_id'])){
$userID = $_SESSION['user_id'];
$checkdate = $_POST["checkdate"];
$checkno = $_POST["checkno"];
$datepaid = $_POST["datepaid"];
$clientname = $_POST["clientname"];
$bank = $_POST["bank"];
$amount = $_POST["amount"];
$status = "UNFINISHED";
$statement = mysqli_prepare($con, "INSERT INTO tbl_checkinfo (user_id,checkno, checkdate, datepaid, clientname, bank, amount, status) VALUES (?,?, ?, ?, ?,?,?,?)");
mysqli_stmt_bind_param($statement, "iissssis", $userID, $checkno, $checkdate, $datepaid, $clientname, $bank, $amount, $status);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = false;
if($statement){
$response["success"] = true;
}
echo json_encode($response);
}
?>
and for displaying user data.
<?php
// Connection Details altered to hide actual values.
$con = mysqli_connect("localhost", "db_user", "db_password", "db_name");
$checkdate = $_POST["checkdate"];
$checkno = $_POST["checkno"];
$datepaid = $_POST["datepaid"];
$clientname = $_POST["clientname"];
$bank = $_POST["bank"];
$amount = $_POST["amount"];
$status = "UNFINISHED";
$sql = "Select * from tbl_checkinfo";
$result = mysqli_query($con, $sql);
// $statement = mysqli_prepare($con, "Select * from tbl_checkinfo");
// mysqli_stmt_execute($statement);
// mysqli_stmt_store_result($statement);
// mysqli_stmt_bind_result($statement, $user_id, $checkdate, $checkno, $datepaid, $clientname, $bank, $amount, $status);
$response = array();
$info=array();
$flag = array();
$response["success"] = false;
if( mysqli_num_rows( $result ) > 0 ) {
while($row = mysqli_fetch_array($result))
{
$flag[checkdate]=$row[checkdate];
$flag[checkno]=$row[checkno];
$flag[datepaid]=$row[datepaid];
$flag[clientname]=$row[clientname];
$flag[bank]=$row[bank];
$flag[amount]=$row[amount];
$flag[status]=$row[status];
array_push($info, $flag);
}
$response["success"] = true;
$response["message"] = $info;
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No entries yet";
echo json_encode($response);
}
?>
Firstly, when posting questions on public forums, please remove your host, DB name, password, etc from the code. :)
Secondly, try to print_r($row) and see on which index is the user id available, then in your code, add this line:
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
$response["user_id"] = $row[USER_ID_INDEX];
session_start();
$_SESSION['user_id'] =$row[USER_ID_INDEX];
}
Where you defined $userID variable, You have to assign proper value to session variable,
if(mysqli_num_rows($res)> 0){
$response["success"] = true;
session_start();
$_SESSION['user_id'] =$row[USER_ID_INDEX];
}
$row['user_id_in_table'] should give you the id.
I am creating a web service for android and PHP registration process.
I am following this tutorial http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
The Issue is: My JSON works on localhost but not on a server. On a server it gives me this error but it stores the data on database successfully.
Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/pmc/public_html/zeusonline.me/zeus/include/DB_Functions.php on line 45
and the line 45 is:
$user = $stmt->get_result()->fetch_assoc();
Code samples->
Register.php file
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("status" => TRUE);
if (isset($_GET['username']) && isset($_GET['email']) &&
isset($_GET['country']) && isset($_GET['phone_number']) &&
isset($_GET['password']) && isset($_GET['lat']) && isset($_GET['lon'])) {
// receiving the post params
$username = $_GET['username'];
$email = $_GET['email'];
$country = $_GET['country'];
$phone_number = $_GET['phone_number'];
$password = $_GET['password'];
$lat = $_GET['lat'];
$lon = $_GET['lon'];
// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
// user already existed
$response["status"] = FALSE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
}
else if ($db->isUserExisted($phone_number)) {
// user already existed
$response["status"] = FALSE;
$response["error_msg"] = "User already existed with " . $phone_number;
echo json_encode($response);
}
else {
// create a new user
$user = $db->storeUser($username, $email, $country , $phone_number,
$password, $lat, $lon);
if ($user) {
// user stored successfully
$response["status"] = TRUE;
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["username"] = $user["username"];
$response["user"]["email"] = $user["email"];
$response["user"]["country"] = $user["country"];
$response["user"]["phone_number"] = $user["phone_number"];
$response["user"]["country"] = $user["country"];
$response["user"]["height"] = $user["height"];
$response["user"]["weight"] = $user["weight"];
$response["user"]["is_number_verified"] =
$user["is_number_verified"];
$response["user"]["is_safe"] = $user["is_safe"];
$response["user"]["is_login"] = $user["is_login"];
$response["user"]["lat"] = $user["lat"];
$response["user"]["lon"] = $user["lon"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
} else {
// user failed to store
$response["Status"] = False;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["Status"] = TRUE;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
DB_Functions.php file
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($username, $email, $country, $phone_number,
$password, $lat, $lon) {
$uuid = uniqid('', true);
$height = 0;
$weight = 0;
$is_number_verified = False;
$is_safe = True;
$is_login = False;
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users (unique_id, username,
email, country, phone_number, password, salt, height, weight,
is_number_verified, is_safe, is_login, lat, lon, created_at) VALUES(?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,NOW())");
$stmt->bind_param("ssssssssssssss", $uuid, $username, $email, $country,
$phone_number, $encrypted_password, $salt, $height, $weight,
$is_number_verified, $is_safe, $is_login, $lat, $lon);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE phone_number
= ?");
$stmt->bind_param("s", $phone_number);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
?>
The URL for testing :
http://pakmanzil.com/zeusonline.me/zeus/register.php?username=bilal&email=bi#gmail.com&country=england&phone_number=03333524145&password=123&lat=0.0&lon=0.0
Change the email and phone_number to make it works please :)
I have tried out some code for user registration..every gose fine code works and user data is stored into data base but in register.php file the execution is not entering if($user) statement as the $response of user details..!plz help me out and correct me if am wrong some were...
hear gose the
/DB_Functions.php/
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
/**
* Storing new user
* returns user details
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
$dbh->execute();
$result = $this->db->query($sql);
if ($result) {
// get user details
$id = $this->db->lastInsertId(); //last inserted id
$sql = "SELECT * FROM db_name WHERE email = '$email'";
$result = $this->db->query($sql);
$no_of_rows = $result->fetchColumn();
// returns confirmation message if completed
if ($no_of_rows > 0) {
return "existsandcompleted";
}
}
}
catch (Exception $e) {
$error = 'Error accessing database: ' . $e->getMessage();
}
}
}
?>
and here gose the /register.php/ file were the main problem is...!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['mobile'])) {
// receiving the post params
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$password = $_POST['password'];
$mobile = $_POST['mobile'];
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (fname, lname, email, password or mobile) is missing!";
echo json_encode($response);
}
?>
Problem:
user data is stored into data base but in register.php file the execution is not entering if($user) statement as the $response of user details
Solution:
I'm pretty sure the problem is because of the following line,
$sql = "SELECT * FROM db_name WHERE email = '$email'";
^
I think it should be,
$sql = "SELECT * FROM users WHERE email = '$email'";
^
Moreover, your storeUser() method should be like this:
// your code
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
echo 'Error accessing database: ' . $e->getMessage();
}
return false;
}
// your code