A little problem with a GET request in PHP - php

I have created a simple registration/login system with PHP/SQL in MVC pattern.
It works perfectly but I noticed a little bug; when I login with user and email that they are not in my database, I can't never visualize the warning message "These user and email are not in our database". I noticed that in the http bar on the top I visualize the GET request "action="error" ONLY when then I refresh the page, and not when I immediately click the submit button for the fields control. Where is the problem?
Here my login page code:
<h2>Login</h2>
<?php
$login = new MvcTemplate();
$login -> loginUserController();
if(isset($_GET['action'])){
if($_GET['action'] == 'error'){
echo '<div class="alert alert-warning">Ops, these user and email are not in our database!</div>';
}
if($_GET['action'] == 'captchafail'){
echo '<div class="alert alert-warning">Ops, flag the Captcha!</div>';
}
}
?>
<form method="POST">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="La tua Mail" name="mail" required>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="La tua Password" name="password" required>
</div>
<div class="g-recaptcha my-5" data-sitekey="6LdJAwodAAAAALA5PrlYI9n96h5f4AmSab7SOSKC"></div>
<div class="d-grid">
<button type="submit" class="btn btn-primary" name="login">Entra</button>
</div>
</form>
Here the managing of the Login feature in the Controller:
// Gestione della funzione di Login;
public function loginUserController(){
if(isset($_POST['login'])){
// Cifratura della password mediante funzione "crypt";
$securePass = crypt($_POST['password'], '$5$zyPltHmiO9ZqMg7JHRWktNhB_GZ0jiQWvDe0c4N7$');
$dataController = array(
'mail' => $_POST['mail'],
'password' => $securePass
);
$responseDb = Data::loginUserModel($dataController, 'users');
// Controllo di ReCaptcha;
$secret = '6LdJAwodAAAAAOlQKWxeJ2LCydsRpl1M9SrsXqOZ';
$response = $_POST['g-recaptcha-response'];
$remoteIP = $_SERVER['REMOTE_ADDR'];
$verify = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteIP");
$result = json_decode($verify);
if($result -> success){
if($responseDb['email'] == $_POST['mail'] && $responseDb['pass'] == $securePass){
// Inizializzo una sessione;
session_start();
// Creo una variabile di sessione;
$_SESSION['validation'] = true;
header('location:users');
}
}elseif(empty($_POST['g-recaptcha-response'])){
header('location:captchafail');
}
else{
header('location:error');
}
}
}
And here the page links.php in the Model directory:
<?php
class Pages{
public static function showPages($links){
if( $links == 'login' ||
$links == 'users' ||
$links == 'update' ||
$links == 'logout'
){
$moduleNav = 'views/modules/'.$links.'.php';
}elseif($links == 'index'){
$moduleNav = 'views/modules/register.php';
}elseif($links == 'ok'){
$moduleNav = 'views/modules/register.php';
}elseif($links == 'error'){
$moduleNav = 'views/modules/login.php';
}elseif($links == 'captchafail'){
$moduleNav = 'views/modules/login.php';
}elseif($links == 'edit'){
$moduleNav = 'views/modules/users.php';
}else{
$moduleNav = 'views/modules/register.php';
}
return $moduleNav;
}
}

Related

AJAX Contact form unable to find API Route, throwing 404 Error in console in Codeigniter 4

i have a user profile page (index.php | View) where any user can fill the contact form and send a message to particular user(whose profile is open). when i am trying to submit from it give me 404 Error and unable to find the route for contact_user Controller function.
here is my code for the same
here is the contact form code from profile view
<!-- Contact -->
<section class="resume-section" id="contact">
<div class="resume-section-content">
<h2 class="mb-5">Contact</h2>
<form method="POST" name="contact_us_form" id="contact_us_form">
<?php
foreach ($user_data as $key) {
?>
<input type="hidden" id="user_id" name="id" value="<?= $key->user_id ?>">
<?php
}
?>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_name" name="contact_form_name"
placeholder="Your Name">
<span class="text-danger" id="error_name"></span>
</div>
<br>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_mobile" name="contact_form_mobile"
placeholder="Your Mobile" pattern="[1-9]{1}[0-9]{9}">
<span class="text-danger" id="error_mobile"></span>
</div>
<br>
<div class="form-group">
<input type="email" class="form-control" id="contact_form_email" name="contact_form_email"
placeholder="Your Email">
<span class="text-danger" id="error_email"></span>
</div>
<br>
<div class="form-group">
<input type="text" class="form-control" id="contact_form_subject" name="contact_form_subject"
placeholder="Message Subject">
<span class="text-danger" id="error_subject"></span>
</div>
<br>
<div class="form-group">
<textarea class="form-control" id="contact_form_message" name="contact_form_message"
placeholder="Message" rows="3"></textarea>
<span class="text-danger" id="error_message"></span>
</div>
<br>
<div class="form-group">
<div class="thankyou-message" id="thankyou-message" style="color:green"></div>
</div>
<br>
<input type="submit" class="btn btn-primary btn-block" id="contact_us" name="contact_us" value="SUBMIT">
</form>
</div>
</section>
here is my javascript Ajax code
jQuery('#contact_us_form').on('submit', function(e){
// alert('hello');
e.preventDefault();
// Name Validation
if ($.trim($('#contact_form_name').val()).length == 0) {
error_name = 'Please enter your name';
$('#error_name').text(error_name);
} else {
error_name = '';
$('#error_name').text(error_name);
}
// Mobile Validation
if ($.trim($('#contact_form_mobile').val()).length == 0) {
error_mobile = 'Please enter your Mobile';
$('#error_mobile').text(error_mobile);
} else {
error_mobile = '';
$('#error_mobile').text(error_mobile);
}
// Email Validation
if ($.trim($('#contact_form_email').val()).length == 0) {
error_email = 'Please enter your Email';
$('#error_email').text(error_email);
} else {
error_email = '';
$('#error_email').text(error_email);
}
// Subject Validation
if ($.trim($('#contact_form_subject').val()).length == 0) {
error_subject = 'Please enter Message Subject';
$('#error_subject').text(error_subject);
} else {
error_subject = '';
$('#error_subject').text(error_subject);
}
// Message Validation
if ($.trim($('#contact_form_message').val()).length == 0) {
error_message = 'Please enter Your Message';
$('#error_message').text(error_message);
} else {
error_message = '';
$('#error_message').text(error_message);
}
if (error_name != '' || error_mobile != '' || error_email != '' || error_subject != '' ||
error_message != '') {
return false;
}else{
var data = {
'user_id': $('#user_id').val(),
'contact_name': $('#contact_form_name').val(),
'contact_mobile': $('#contact_form_mobile').val(),
'contact_email': $('#contact_form_email').val(),
'contact_subject': $('#contact_form_subject').val(),
'contact_message': $('#contact_form_message').val(),
};
$.ajax({
method: "post",
url: "/Home/contact_user",
// headers: {'X-Requested-With': 'XMLHttpRequest'}
data: data,
success: function(response){
jQuery('#contact_us_form')['0'].reset();
jQuery('#contact_us').val('SUBMIT');
jQuery('#contact_us').attr('disabled', false);
alertify.set('notifier','position', 'top-right');
alertify.success("Done");
// response.preventDefault();
}
});
}
});
here are my Routes
$routes->get('/', 'Home::index'); // Default route, if no username redirect to welcome view
$routes->post('/Home/contact_user', 'Home::contact_user'); //contact form API Route, submit form data to this route
$routes->get('/(:any)', 'Home::user/$1'); // User Profile, if username found, show user profile
and here is my contact_user function from Home Controller
public function contact_user(){
$Home_Model = new \App\Models\Home_model();
$data = [
'user_id' => $this->request->getPost('user_id'),
'contact_name' => $this->request->getPost('contact_name'),
'contact_mobile' => $this->request->getPost('contact_mobile'),
'contact_email' => $this->request->getPost('contact_email'),
'contact_subject' => $this->request->getPost('contact_subject'),
'contact_message' => $this->request->getPost('contact_message')
];
$Home_Model->save($data);
$data = ['status' => 'successful'];
return $this->response->setJSON($data);
}

how to popup an alert when form is submitted

I have a registration form and when people compile the form and submit it I want to show a popup, but the problem is it's not working. here is the code:
<?php
// result is when it's all good
if ($result) {
echo '<div class="vai-accedi">
<div class="vai-accedi2">
<div class="vai-accedi3">
<p>Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere</p>
Ok
</div>
</div>
</div>';
}
?>
All the code
<!-- signup backend connection -->
<?php
include 'dbcon.php';
session_start();
// error_reporting(0);
// if (isset($_SESSION['nome'])) {
// header("Location: header.php");
// }
if (isset($_POST['submit'])) {
$nome = mysqli_real_escape_string($conn,$_POST['nome']);
$cvn = mysqli_real_escape_string($conn,$_POST['cittàvn°']);
$numerodicell = mysqli_real_escape_string($conn,$_POST['numerodicell']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$confpassword = mysqli_real_escape_string($conn,$_POST['confpassword']);
$password = md5($_POST['password']);
$confpassword = md5($_POST['confpassword']);
if ($password == $confpassword) {
$sql = "SELECT * FROM utenti WHERE email='$email'";
$result = mysqli_query($conn, $sql);
if (!$result->num_rows > 0) {
$sql = "INSERT INTO utenti (nome,cittàvn°, numerodicell, email, password, confpassword)
VALUES ('$nome','$cvn','$numerodicell','$email','$password','$confpassword')";
$result = mysqli_query($conn, $sql);
if ($result) {
// echo "<script>alert('Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere')</script>";
echo '<div class="vai-accedi">
<div class="vai-accedi2">
<div class="vai-accedi3">
<p>Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere</p>
Ok
</div>
</div>
</div>';
// header( "Refresh:1; url='login.php'");
$nome = "";
$cvn = "";
$numerodicell = "";
$email = "";
$_POST['password'] = "";
$_POST['confpassword'] = "";
} else {
echo "<script>alert('oops! qualcosa è andato storto.')</script>";
}
} else {
echo "<script>alert('oops! Email già registrata.')</script>";
}
} else {
echo "<script>alert('le due password non combaciano.')</script>";
}
}
?>
<!-- signup backend connection -->
<div class="registrati">
<div class="registratiinner registratiinner2">
<h1>Registrati</h1>
<form action="" class="sign-up-form" method="POST" style="width:100%;">
<div class="input-wrapper">
<input type="text" placeholder="Nome" name="nome" required>
</div>
<div class="input-wrapper">
<input type="text" placeholder="Citta,Via,n°" required name="cittàvn°">
</div>
<div class="input-wrapper">
<input type="text" placeholder="Numero di Cellulare" required name="numerodicell">
</div>
<div class="input-wrapper">
<input type="email" placeholder="Email" required name="email">
</div>
<div class="input-wrapper">
<input type="password" placeholder="Crea una Nuova Password" required name="password">
</div>
<div class="input-wrapper">
<input type="password" placeholder="Conferma Password" required name="confpassword">
</div>
<div class="accetti">
<p style="font-size: 1.8rem; margin-top: 0;">Inviando accetti Termini & Condizioni</p>
</div>
<button type="submit" class="contact-button" style="border-radius: .5rem;" name="submit" type="submit">Registrati</button>
</form>

Cannot display alert once the user login inputs incorrect credentials PHP PDO

index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>

Address user after login to a specific page based on the type of role he has

As the title suggests, I would like the user to login to two specific pages based on the type of role.
By default in the role field the letter "N" is defined
So if it is equal to N, go to
Otherwise go to
login.php:
<?php session_start(); ?>
<?php
$messaggio = "";
if (isset($_POST['submit'])) {
include 'FILE_DI_CONNESSIONE.php';
//REAL_ESCAPE_STRING ANTI STRINGA BUCA DB
$email = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['email']);
$password = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['password']);
$query = $VARIABILE_FILE_DI_CONNESSIONE->query("SELECT id, password FROM tabella WHERE email='$email'");
if ($query->num_rows > 0) {
$data = $query->fetch_array();
if (password_verify($password, $data['password'])) {
$_SESSION['NOME_SESSIONE'] = true;
//IMPLEMENTAZIONE SICUREZZA PER ACCESSO AI DATI SOLO SE LA SESSIONE DELLA LOGIN PAGE E' UGUALE ALLA PAGINA DOPO DEL LOGIN
?>
<?php
}else
$messaggio = "Gentilmente inserisci correttamente la tua username e la tua password.";
}}
?>
<?php if ($messaggio != "") echo $messaggio . "<br><br>"; ?>
<form method="post" action="index.php">
<input class="form-control" name="email" type="email" placeholder="email..."><br>
<input class="form-control" minlength="5" name="password" type="password" placeholder="Password..."><br>
<input class="btn btn-primary" name="submit" type="submit" value="Log In"><br>
</form>
There are different ways to implement a redirect. But assuming the variable with the role is $role and that can be either N or O you can redirect this way
if($role == 'N')
{
// Role N
?><meta http-equiv="refresh" content="0;url=page1.php"/><?php
}
elseif($role == 'O')
{
// Role O
?><meta http-equiv="refresh" content="0;url=page2.php"/><?php
}
else
{
// no role?
}
Besides a meta refresh, you can also redirect like this:
if($role == 'N')
{
// Role N
header("Location: page1.php");
}
elseif($role == 'O')
{
// Role O
header("Location: page2.php");
}
else
{
// no role?
}
Edit: Try this for the entire code:
<?php session_start();
$messaggio = "";
if (isset($_POST['submit'])) {
include 'FILE_DI_CONNESSIONE.php';
//REAL_ESCAPE_STRING ANTI STRINGA BUCA DB
$email = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['email']);
$password = $VARIABILE_FILE_DI_CONNESSIONE->real_escape_string($_POST['password']);
$query = $VARIABILE_FILE_DI_CONNESSIONE->query("SELECT id, password, role FROM tabella WHERE email='$email'");
if ($query->num_rows > 0) {
$data = $query->fetch_array();
if (password_verify($password, $data['password'])) {
$_SESSION['NOME_SESSIONE'] = true;
//IMPLEMENTAZIONE SICUREZZA PER ACCESSO AI DATI SOLO SE LA SESSIONE DELLA LOGIN PAGE E' UGUALE ALLA PAGINA DOPO DEL LOGIN
if($data['role'] == 'N')
{
// Role N
?><meta http-equiv="refresh" content="0;url=page1.php"/><?php
}
elseif($data['role'] == 'O')
{
// Role O
?><meta http-equiv="refresh" content="0;url=page2.php"/><?php
}
else
{
// no role?
}
}else
$messaggio = "Gentilmente inserisci correttamente la tua username e la tua password.";
}}
?>
<?php if ($messaggio != "") echo $messaggio . "<br><br>"; ?>
<form method="post" action="index.php">
<input class="form-control" name="email" type="email" placeholder="email..."><br>
<input class="form-control" minlength="5" name="password" type="password" placeholder="Password..."><br>
<input class="btn btn-primary" name="submit" type="submit" value="Log In"><br>
</form>

Inserting angularjs form values into database using php

I have created angularjs form. I want to store the form values into data base using PHP and before inserting I want to check weather the email is already exists or not. I am new to PHP. Any help would be appreciated. Thanks.
Register.html:
<div class="container col-lg-10" style="margin-top:2em; margin-left:2em;" >
<div class="panel panel-default">
<div class="panel-body" ng-app="TempleWebApp" ng-controller="RegisterCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && (userForm.name.$dirty || submitted)}">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="user.name" placeholder="Your Name" ng-required="true">
<p ng-show="userForm.name.$error.required && (userForm.name.$dirty || submitted)" class="help-block">You name is required.</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && (userForm.email.$dirty || submitted)}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Your Email Address" ng-required="true">
<p ng-show="userForm.email.$error.required && (userForm.email.$dirty || submitted)" class="help-block">Email is required.</p>
<p ng-show="userForm.email.$error.email && (userForm.email.$dirty || submitted)" class="help-block">Enter a valid email.</p>
</div>
<!-- PASSWORD -->
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && (userForm.password.$dirty || submitted)}">
<label>Password</label>
<input type="Password" name="password" class="form-control" ng-model="user.passwrd" placeholder="Your Password" ng-required="true">
<p ng-show="userForm.password.$error.required && (userForm.password.$dirty || submitted)" class="help-block">Your password is required.</p>
</div>
<!-- TERMS & CONDITIONS -->
<div class="form-group" ng-class="{ 'has-error' : userForm.terms.$invalid && (userForm.terms.$dirty || submitted)}">
<label>Accept Terms & Conditions</label>
<input type="checkbox" value="" name="terms" ng-model="user.terms" ng-required="true" />
<p ng-show="userForm.terms.$error.required && (userForm.terms.$dirty || submitted)" class="help-block">Accept terms & conditions.</p>
</div>
<!-- ng-disabled FOR ENABLING AND DISABLING SUBMIT BUTTON -->
<!--<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Register</button>-->
<button type="submit" class="btn btn-primary col-lg-offset-6">Register</button>
</form>
<pre>{{user}}
</pre>
</div>
</div>
</div>
Main.js:
var app = angular.module('TempleWebApp', [ 'ngRoute']);
app.controller('RegisterCtrl', function ($scope,$location, $http) {
$scope.user = {};
$scope.user.name= "" ;
$scope.user.email ="";
$scope.user.passwrd="";
$scope.user.terms="";
// function to submit the form after all validation has occurred
$scope.submitForm = function () {
// Set the 'submitted' flag to true
$scope.submitted = true;
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
console.log("Inserted Successfully!");
});
};
});
PHP code.
<?php
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = $data->password;
$con = mysql_connect("localhost","root","");
mysql_select_db("userregister");
$sql = "insert into user(username,email,password) values($username,'$email','$password')";
$result = mysql_query($sql);
?>
Try using mysqli in the following manner (Also note you should create the variable $dbname and assign the right dbname to it:
$data = json_decode(file_get_contents("php://input"));
$username = #$data->username;
$email = #$data->email;
$password = #$data->password;
$dbname = '';
$conn = new mysqli("localhost","root","",$dbname);
$check = "SELECT * FROM user WHERE email='$email'";
//The following rows check whether this email already exists in the DB
$results = $conn->query($check);
if($results && mysqli_num_rows($results)>0)
{
echo "email";
die;
}
//The following rows will work only if there is no such email in the DB
if($conn->connect_error)
{
echo "false";
die;
}
$sql = "INSERT INTO user VALUES values($username,'$email','$password')";
if ($conn->query($sql) === true)
{
echo "true";
}
You will also need to change your Javascript to fit the possible events:
$http.post("register.php",{'username':$scope.user.name,'email':$scope.user.email,'password':$scope.user.passwrd})
.success(function(data,status,headers,config){
if(data == 'true'){
console.log("Inserted Successfully!");
}
else if(data == 'email'){
console.log("The email already exists");
}
else{
console.log("There was an issue connecting to the DB");
}
});

Categories