Is anything wrong with this code? - php

I used this code to create a user registration page in my website. I firstly connected to my database and then did the below codes ----->
<form action="index.php" method="post">
<p id="usr1">Name : </p><input id="input1" placeholder="Username" type="text" name="username" required> </br>
</br>
<p id="usr2">Password : </p><input id="input2" placeholder="Password" type="text" name="pwd" required> </br>
<p id="usr3">Password : </p><input id="input3" placeholder="Re-Type your password" type="text" name="cpwd" required> </br>
</br>
<input id="sub" name="subbox" type="submit">
</form>
<?php
if (isset($_POST['submit_button'])) {
$username= $_POST['username'];
$password=$_POST['pwd'];
$conpwd=$_POST['cpwd'];
}
if ($password == $conpwd) {
$query = "SELECT * FROM login WHERE name='$username' ";
$query_run = mysqli_query($con,$query);
if (mysqli_num_rows($query_run) > 1) {
echo '<script type="text/javascript">alert("This Username Already exists. Please try another username!")</script>';
// the above code will check if the username is already taken or not.
}else {
$query = "insert into login values('$username' , '$password')";
$query_run = mysqli_query($con,$query);
if ($query_run) {
echo '<script type="text/javascript">alert("Registration Successful!")</script>Click Here To Continue';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}else {
echo '<script type="text/javascript">alert("Server Error. Please try again after a few minutes!")</script>';
}
}
}else {
echo "Please check and re-type both passwords";
}
?>
But it always return some errors.This is what I see when i try to run the code

Is anything wrong with this code?
To answer your initial question, yes there is something wrong. Your code is vulnerable to SQL injection. You should have a look at: How can I prevent SQL injection in PHP? And password is stored plain in your database, which means no respect for your user. There are some other problems with code style but it's just bonus.
Anyway, the thing that cause you the "alert" problem is that submit_button button does not exists. There is no button with that name. Your if condition is always false. So you have to replace:
if (isset($_POST['submit_button'])) {
With
if (isset($_POST['subbox'])) {
And maybe add a value to your input (not sure it's required, I did not tested):
<input id="sub" name="subbox" type="submit" value="1">
Thanks to #Fred-ii-

Related

Login with different role (redirect to different page according to user type )

I am new to php. I could not log in either from the user or the admin. How do make it so the user could log in and will be redirected to index.php, and once the admin login will be redirected to admin.php.
I did some research with youtube and could not find anything helpful on what I need.
<form action="login.php" method="post">
<input class="space" name="username" type="text"
placeholder="Username/E-
mail" required="required"></input>
<br />
<input class="space" name="password" type="password"
placeholder="Password" required="required"></input>
<br />
<input type="submit" class="log-btn" value="Login" />
<button type="button" class="log-btn" onclick="return
abc(1,'reg.html')">Register</button>
</form>
This is the database table:
I had also included the admin username and password in the database so admin does not have to register
<?php
include ("conn.php");
session_start();
$sql="SELECT * FROM user WHERE email = '".$_REQUEST['username']."' and
password = '".$_REQUEST['password']."' or username =
'".$_REQUEST['username']."' and password = '".$_REQUEST['password']."'
LIMIT 1";
$result=mysqli_query($con,$sql);
if (mysqli_num_rows($result) <= 0) {
$cred = mysqli_fetch_row($result);
$_SESSION['user'] = $cred[1];
echo "<script>window.location.href='index.php';</script>";
} else {
echo "<script>window.location.href='index.php?msg=Invalid+Credential';
</script>";
}
if ($row=mysqli_fetch_array($result)) {
$_SESSION['role']=$row['user_role'];
}
if ($row['user_role']==="1"]) {
echo "<script>alert('Welcome back admin!');";
echo "window.location.href='admin.html';</script>";
}
I expect that the user will be able to login and will be redirected to the index.php and the admin will be able to login as well as but will be redirected to the admin.php. But what I am seeing a white page and some error code on line 20. I know my if-else statement has some issue but not sure on how to fix it to be working
Your login.php should be like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "root", "dbpass", "dbname"); // make seperate file
if($_POST){
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $_POST['username'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
session_start();
while($row = $result->fetch_assoc()) {
if($row['role'] == 1){
$_SESSION['message'] = $row['username'];
header("Location: admin.php");exit();
}else{
$_SESSION['message'] = $row['username'];
header("Location: index.php");exit();
}
}
}else{
echo "Wrong Credentials";
}
$stmt->close();
}
?>
<form action="login.php" method="post">
<input class="space" name="username" type="text"
placeholder="Username/E-
mail" required="required"></input>
<br />
<input class="space" name="password" type="password"
placeholder="Password" required="required"></input>
<br />
<input type="submit" class="log-btn" value="Login" />
<button type="button" class="log-btn" onclick="return
abc(1,'reg.html')">Register</button>
</form>
And For Both page admin.php and index.php you check active session using $_SESSION['message'].
In that you will get the name of the user.
NOTE: Please do not use store plain text passwords! Please use PHP's password_hash() for password security.

PHP- Login to account to working

its my first time creating a login page.
I want users to login, then the page redirects to the customer account page, if they have a account. I have added echo's so i can see whats happening. I have a "Logged in successfully" alert that works perfectly when i login. The page just does not redirect.
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="login.php" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required>
<input type="submit" name="login" value="login" class="btn ">
<br>
</form>
PHP
<?php
session_start();
require ('./mysql.inc.php');
?>
<?php
if (isset($_POST['login']))
//database varianbles
$c_email = $_POST['email'];
$c_password = $_POST['pass1'];
// select login details
$sel_c = "SELECT * FROM Cus_Register WHERE Cus_Email='$c_email' AND Cus_Password='$c_password'";
$run_c = mysqli_query($dbc, $sel_c);
//check if customer is on databse
$check_customer = mysqli_num_rows($run_c);
if ($check_customer == 0) {
echo "<script> alert('password or email is incorrect please try again')</script>";
exit();
}
else{
$_SESSION['Cus_Email'] = $c_email;
echo "<script> alert ('Logged in successfully')</script>";
echo "<script>window.open('./customer/Cus_Account.php'.'_self') </script>";
}
?>
You may use header() to redirect
else
{
$_SESSION['Cus_Email'] = $c_email;
header('Location: customer/Cus_Account.php');
exit();
}
hope it helps:)
Do you intend window.open('./customer/Cus_Account.php'.'_self') to be window.open('./customer/Cus_Account.php', '_self')?
window.open takes a location and a target parameter and in JavaScript parameters are separated by a comma, not a full stop. In this case './customer/Cus_Account.php' is the location and '_self' is the target.

How to make login when user is signing up to a system

Presently in my login system a user has to do login after sign up.
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>Not a member yet?.Sign up here.By Sign up You are accepting our terms and conditions </p>
<fieldset>
<legend>Registration Info</legend>
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /><br />
<label for="email">Email id:</label>
<input type="email" id="email" name="email" /><br />
<label for="password1">Password:</label>
<input type="password" id="password1" name="password1" /><br />
<label for="password2">Password (retype):</label>
<input type="password" id="password2" name="password2" /><br />
</fieldset>
<input type="submit" value="Sign Up" name="create" />
</form>
If the form submitted correctly
<?php
if (!empty($user_username) && !empty($user_password)) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM <database> WHERE username = '$username'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$query = "INSERT INTO <database> (username,last_name,password,join_date) VALUES ('$username','$email',SHA('$password1'), NOW())";
$result=mysqli_query($dbc, $query) or die("cant create an account");
}else{
die("Somthing went wrong");
}
}
?>
Once it is done he has to go to login page and requerd to login using the following codes
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Log In</legend>
<label for="username">Username:</label>
<input type="text" name="username" value="<?php if (!empty($user_username)) echo $user_username; ?>" /><br />
<label for="password">Password:</label>
<input type="password" name="password" />
</fieldset>
<input type="submit" value="Log In" name="submit" />
</form>
I dont want this system happend like this when the user is signing up that time itself the user has to be taken to home page. And the session variables also has to be setted while signing up process.
Try to reuse the code, it will help to manage your code and application , Please create a function for login process, and use the same function for normal login and after signup then call the same function with the details used for signup.
function authenticate($user_id, $pwd)
{
// do the logic for login,
//if success then set value in session and redirect to the respective page
//if failed then error page
}
if (!empty($user_username) && !empty($user_password)) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM <database> WHERE username = '$username'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$query = "INSERT INTO <database> (username,last_name,password,join_date) VALUES ('$username','$email',SHA('$password1'), NOW())";
$result=mysqli_query($dbc, $query) or die("cant create an account");
// call the authenticate function for login
authenticate($username, SHA('$password1'));
}else{
die("Somthing went wrong");
}
}
Try something like this :-
<?php
if (!empty($user_username) && !empty($user_password)) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM <database> WHERE username = '$username'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$query = "INSERT INTO <database> (username,last_name,password,join_date) VALUES ('$username','$email',SHA('$password1'), NOW())";
$result=mysqli_query($dbc, $query) or die("cant create an account");
$_SESSION["username"] = $username; // assign session variable here.
header("Location: home.php"); // redirect to home page
}else{
die("Somthing went wrong");
}
}
?>

If(..){include}, includes anyways

I am trying to make a simple Login system for admins. Nothing too special, since it's my first one. I am trying to verify if the username and password inputted are the same as the one in the database, and then include the rest of the page. No errors, everything works as it should, the database access is good, but it's like the if statement isn't there. It just includes the rest of the page on load.
<form action="admin.php" method="POST" class="login">
<input type="text" placeholder="Password" name="username" required>
<input type="password" placeholder="Password" name="password" required>
<input type="submit" value="Log In">
</form>
<?php
require('connect.php');
$admin = <<<SQL
SELECT *
FROM admins
SQL;
$username = $_POST['username'];
$pw = $_POST['password'];
$result = $db->query($admin);
while($row = $result->fetch_assoc()){
if($username == $row['username'] && $pw == $row['password']){
include('admininclude.php');
} else {
echo 'You are not cool enought to enter. (Username or Password wrong.)';
}
}
$db->close();
?>
Thanks in advance!

Simple PHP Login does not work

This is my script:
session_start();
include "../inc/conn.php";
if ($_GET['login']=="yes") {
echo 'test2';
$username=$_POST('username');
$password=$_POST('password');
echo $username.' '.$password;
$userq=mysql_query("SELECT * FROM members WHERE username='$username' AND password='$password'") or die(mysql_error());
if (mysql_num_rows($userq)=="1") { $_SESSION['chkuser']="confirmed"; $_SESSION['username']=$user; }
else { echo 'Потребителското име и/или паролата са грешни. Моля опитайте отново.'; }
}
echo $user.' '.$pass;
if ($_SESSION['chkuser'] <> "confirmed") {
echo '<div align="center"><strong>Моля въведете име и парола</strong>:<br/><br/><br/>';
?>
<form name="form1" method="post" action="?login=yes">
Потребител: <input type="text" name="username" />
Парола: <input type="password" name="password" /><br/><br/>
<p><input type="submit" name="Submit" value="Вход" /></p>
</div>
</form>
<?
exit();
}
Test 2 is echoed, but username and password are not sent via POST - scripts breaks after $_POST is used.. Do you guys see where my error is ?
Use [], not () to get data from $_POST array:
$username=$_POST['username'];
$password=$_POST['password'];
Also, I might mention that you should escape user input before using it in mysql query:
$username=mysql_escape_string($_POST['username']);
$password=mysql_escape_string($_POST['password']);
If you don't do this, anyone can insert something like this:
username=admin
password=blabbla' OR '1'='1
and will login as admin without knowing the password :)
Shouldn't this:
$username=$_POST('username');
$password=$_POST('password');
be
$username=$_POST['username'];
$password=$_POST['password'];
?

Categories