i'm making a website. It has a login form, that transfer to the admin section when you're logged in. It works perfectly, it searches everything in the database, it's everything ok. But the register link isn't working properly. The cadastro.php file should do the register to the cadastra_usuario.php and transfer right to the login page if everything went ok. It also should bring a warning if the password don't match or if some space are missing. It doesn't even register in the database and don't do nothing of this. Here's the codes:
The include's and the form of cadastro.php:
<body>
<div class="container container-twelve">
<div class="four columns offset-by-four">
<h1 class="titles">Cadastro</h1>
<?php if(isset($_SESSION["success"])) {?>
<p><?= $_SESSION["success"] ?></p>
<?php }?>
<?php unset($_SESSION["success"]); ?>
</div>
<div class="four columns offset-by-four" id ="login">
<form action="cadastra_usuario.php" method="post">
<label for="nome">Nome</label>
<input type="text" name="nome" placeholder="Digite seu nome">
<label for="email">Email de usuário </label>
<input type="text" name="email" placeholder="Seu email para login">
<label for="senha">Senha</label>
<input type="password" name="senha" placeholder="Sua senha">
<label for="senha2">Repita sua senha</label>
<input type="password" name="senha2" placeholder="Repita sua senha">
<input type="submit" value="Cadastrar">
</form>
<p> << Voltar para o site</p>
<p> Já tenho um cadastro >> </p>
</div>
</div>
</body>
cadastra_usuario.php:
<?php
include('conecta.php');
include('functions.php');
include('function_usuario.php');
$senha = $_POST['senha'];
$senha2 = $_POST['senha2'];
$cadastra = cadastraUsuario();
if($senha != $senha2){
$_SESSION["danger"] = "As senhas não conferem!";
header("Location: cadastro.php");
}
if($cadastra == null){
$_SESSION["danger"] = "Complete todos os campos!";
header("Location: cadastro.php");
} else {
$_SESSION["success"] = "Usuário cadastrado com sucesso.";
header("Location: login.php");
}
?>
and the function:
function cadastraUsuario($conexao, $nome, $email, $senha){
$nome = $_POST['nome'];
$email = $_POST['email'];
$senha = $_POST['senha'];
$conexao = mysqli_connect('mysql.hostinger.com.br','u374984363_ozzy','ozzy#123', 'u374984363_ncars');
$query = "insert into usuarios (nome, email, senha) values ('{$nome}', '{$email}', '{$senha}')";
return mysqli_query($conexao, $query);
}
Hard to tell, but:
function cadastraUsuario($conexao, $nome, $email, $senha)
awaits $conexao which should be the DB connection, right? But when you call the function, you are not giving the connection:
$cadastra = cadastraUsuario($_POST['nome'], $_POST['email'], $_POST['senha']);
This won't work.
Maybe this a solution:
function cadastraUsuario($nome, $email, $senha) {
$query = "insert into usuarios (nome, email, senha) values ('{$nome}', '{$email}', '{$senha}')";
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query($query)) {
echo "Insert failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
Some advices from a developer:
Never write $_POST variables directly to the DB. This allows SQL injection aka security issue!
Write a log function and do application logs as much as possible
Check phperror.log for error if you encounter an error
Related
Have a PHP form for a registration system:
<div class="col-md-6 login-right">
<h2> Register Here </h2>
<form action="registration.php" method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="user" class="form-control" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary"> Register</button>
</form>
</div>
And a registration.php created:
<?php
session_start();
$con = mysqli_connect('localhost','root', 'test');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = " select * from usertable where name = '$name'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo " Username Already Taken";
}else{
$reg = " insert into usertable(name , password) values ('$name' , $pass')";
mysqli_query($con, $reg);
echo" Registration Successful";
}
?>
Also have a MySQL database created with Database: userregistration »Table: usertable. And the MySQL not sure, quite new to this isn't being populated with the inputted data from the php. When the data is inputted into the php form it requests the registration.php page which works successfully but doesn't populate the table with the data inputted.
You should be actively checking that the connection is successful first, and then also checking that the query was successfully executed too in order to debug this further.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (mysqli_query($conn, $reg)) {
echo "New record created successfully";
} else {
echo "Error: " . $reg . "" . mysqli_error($conn);
}
You should then also close the connection
Good day.
So below i have a php script that is supposed to query my db and look for user details. the db is set up and the data is available in it. the issue here seems that once i click the submit button with my user entered details, it fails on the first if statement, to see if the email exists. i am not sure why.
But here is the submit form.
<form action = "submit2.php" method="Post" >
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" name="email" class="form-control" placeholder="Your user name">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="text" id="password" name="password" class="form-control" placeholder="Your Password">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-primary">
</div></form>
and here is the submit2.php that is supposed to manipulate the data from the form and query the db.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$useremail = mysqli_real_escape_string($connection,$_POST['email']);
$userpassword = mysqli_real_escape_string($connection, $_POST['password']);
if (empty($useremail) || empty($userpassword)){
header("Location: customerportal.php?login=empty");
exit();
}
else{
$sql = "SELECT * FROM 'USERS' where EMAIL ='$useremail';";
$emailresult = mysqli_query($connection, $sql);
$emailresultcheck = mysqli_num_rows($emailresult);
//check if email exists
if($emailresultcheck == 0){
header("Location: customerportal.php?login=invalidEmail");
}
else {
if($row = mysqli_fetch_assoc($emailresult)){
//dehash the password
$hashedPWDCheck = password_verify($userpassword,$row['ENCRYPTEDPWD']);
if($hashedPWDCheck == false){
header("Location: customerportal.php?login=passwordincorrect");
exit();
}
elseif($hashedPWDCheck == true){
$_SESSION['email'] = $email;
// header("Location: Landingpage.php");
echo "Success";
}
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
}
}
?>
The submit always fails else statement and returns the invalidEmail header location and i am not sure why. the Connection file is below.what am i missing?
<?php
$connection = mysqli_connect("localhost", "root", "");
if(!$connection){
echo "Failed to connect database" . die(mysqli_error($connection));;
}
$dbselect = mysqli_select_db($connection, "dhctest");
if(!$dbselect){
echo "Failed to Select database" . die(mysqli_error($connection));
}
?>
Change this
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
to this
$sql = "select * from users where email = $useremail";
Okay, so solved the issue, by running a var_dump() on everyone of my variables until i came across the error that was being outputted by my sql code.
On the line
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
I had to remove the '' and replace with ``.
And that seems to have solved the issue.
Thank you for everyone who assisted.
hi guys please l need some help. lm setting up a user registration sign up form. but l was NOT ABLE TO INSERT THE USER INFO IN TO THE DATABASE. And the code did not display any error message, meaning that everything is fine.
But when l tried to sign up it gives the form's error message "Failed to Register User".
this is the code: (and check at the bottom the connect.php code)
<?php
require_once('connect.php');
//print_r($_POST);
if(isset($_POST) & !empty($_POST)) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// storing the sign up info in to the database
$sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";
//executing the query
$result = mysqli_query($connection, $sql);
if($result){
echo "User Registered Successfully";
}
else{
echo "Failed to Register User";
}
}
?>
<div id="form-signup">
<form id="signup-form" name="sign-up" action="sign.php" method="POST">
<h1>Create your profile</h1>
<p>
<input type="text" name="username" id="username" class="signup-input" required="required" placeholder="Full name*" >
</p>
<p>
<input type="email" name="email" class="signup-input" required="required" placeholder="Email*" >
</p>
<p>
<input type="password" name="password" class="signup-input" required="required" placeholder="Mot de passe*">
</p>
<!-- <p>
<input type="password" name="confirmpassword" class="signup-input" required="required" placeholder="Confirmez mot de passe*">
</p> -->
<p class="agree"> By signing up, you agree to Tout-Passe's <br> Terms of use<br> and Privacy Policy.
</p>
<p>
<input type="submit" class="signup-btn" name="btn-signup" value="Create Account">
</p>
<p class="already">Already on Tout-Passe? Log in</p>
</div><!--END OF PHASE-1-->
</form> <!--END OF SIGN-UP-->
</div><!--END FO ALLFORM-->
CONNECT CODE
<?php
$connection = mysqli_connect('localhost', 'root', '');
if(!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'listing');//listing = database
if(!$select_db){
die("Failed to select database" . mysqli_error($connection));
}
?>
You did a mistake line 4, if(isset($_POST) & !empty($_POST)) { you have only one & you should have two like this: if(isset($_POST) && !empty($_POST)) {
Beside this, when your message tell you that it failed to register the user, it does not explain why, to solve this you have to add a mysqli_error() like this:
require_once('connect.php');
//print_r($_POST);
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// storing the sign up info in to the database
$sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";
//executing the query
$result = mysqli_query($connection, $sql);
if($result){
echo "User Registered Successfully";
}
else{
echo "Failed to Register User, reason: " . mysqli_error($connection);
}
}
Also there is two problems with your code:
It is faillibe to SQL injection. What is SQL injection?
You should test each of your global variables are set individually like this: if(isset($_POST['username']) && !empty($_POST['username'])) and not like this: if(isset($_POST) && !empty($_POST))
I'm trying do develop a simple log in form in order to learn php.
I've created the form and a function which send a query to a mysql database to retrieve username and password (stored in md5 encryption) and control it with data inserted by the user.
The problem is that this function (login() )is in a external file called fun_login.php and when I call it from the page login.php it opens the page fun_login.php and it doesn't come back to login.php (I think because there is some problem with the return value)
In login.php I've included the file fun_login.php with
<?php
include "fun_login.php";
?>
login.php
<div class="container">
<div class="row">
<div class="col-sm-2 col-sm-offset-5">
<form action="fun_login.php" role="form" method="post">
<div class="form-group">
<label for="nome">Username:</label>
<input type="textarea" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-default" id="submitlogin" name="submitlogin">Log In</button>
</form>
<?php
if(isset($_POST['submitlogin'])) {
$control = login($_POST['username'], md5($_POST['password']));
if($control) header("Location: ./index.php");
else header("Location: ./login.php");
}
?>
</div>
</div>
</div>
fun_login.php
<?php
function login($username, $password) {
$myconn = mysql_connect(localhost, root, password);
mysql_select_db('portfolio', $myconn);
$query = "SELECT username,password,admin FROM utenti WHERE username = '" . $username . "' AND password = '" .$password . "';";
$result = mysql_query($query, $myconn)or die('Error, insert query failed');
// conto il numero di occorrenze trovate nel db
$numrows = mysql_num_rows($result);
// se il database è vuoto lo stampo a video
if ($numrows == 0) return false;
// se invece trovo delle occorrenze...
else return true;
}
?>
At the time you're calling
<?php
if(isset($_POST['submitlogin'])) {
$control = login($_POST['username'], md5($_POST['password']));
if($control) header("Location: ./index.php");
else header("Location: ./login.php");
}
?>
in your login.php the headers have been already sent so header('Location:') won't work.
You need to put that before any output (echo or html) gets displayed.
If you look in the error log you'll probably see Warning: Cannot modify header information - headers already sent by
By the looks of it that file is included in a layout or something so your login() call has to be even before that.
What's the error message you are receiving?
use this command at the beginning of your php files:
// Report all PHP errors
error_reporting(E_ALL);
Then you will know which error has occurred, if at all.
I have thoroughly researched my topic before coming here and can't seem to figure out my problem.
I have an HTML page:
<form role="form" action="register.php" method="POST">
<div class="form-group">
<label>First Name:</label>
<input type="text" name="first_name">
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" name="last_name">
</div>
<div class="form-group">
<label>Student ID:</label>
<input type="number" name="student_id">
</div>
<div class="form-group">
<label>Email address:</label>
<input type="email" name="email">
</div>
<button type="submit" name="register" value="register">Register</button>
</form>
<form role="form" action="login.php" method="POST">
<div class="form-group">
<label>Email address:</label>
<input type="email" name="email">
</div>
<button type="submit" name="login" value="login">Login</button>
</form>
This functions and communicates perfectly well with my login page written in php, it checks if the submitted email address already exists in a MySQL database. It will then point the user to a profile page and the code exits itself.
My issue is with my register page, I use the same MySQL SELECT functions that I do on my login page, to check and see if the submitted student ID or email already exists in the database and if so, will return back to the form for the user to try again:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$student_id = $_POST['student_id'];
$email = $_POST['email'];
if (isset($_POST['register'])) {
register($conn, $first_name, $last_name, $student_id, $email);
}
function register($conn, $first_name, $last_name, $student_id, $email) {
$Ssql = "SELECT student_id FROM AidenLocke where student_id = '$student_id'";
$Sresult = mysqli_query($conn, $sql);
if (mysqli_num_rows($Sresult) > 0) {
header('Location: form.html');
} else {
$sql = "INSERT INTO AidenLocke (first_name, last_name, email, student_id)
VALUES ('$first_name', '$last_name', '$email', '$student_id')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br />" . $conn->error;
}
header('Location: profile.php');
}
}
(I have removed my database information for security reasons but there is no connection problem)
My main issue is with the else section of the second if statement, my code does not check if the student id already exists, and regardless of what information I enter into the form, makes a new entry in to the database.
I am quite confused and hoping someone can give me a valid answer, thanks!
You seem to have a typo in your variable when you query the database:
$Ssql = "SELECT student_id FROM AidenLocke where student_id = '$student_id'";
^^^^
$Sresult = mysqli_query($conn, $sql);
^^^
That is, you're using $sql instead of $Ssql