Undefined index PHP for a registration form - php

<?php
include('connection.php');
$username = $_POST['user'];
$password = $_POST['pass'];
//to prevent from mysqli injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);
$sql = "select *from login where username = '$username' and password = '$password'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1){
echo "<h1><center> Login successful </center></h1>";
}
else{
echo "<h1> Login failed. Invalid username or password.</h1>";
}
?>
I have to do a website that works like google forms, for school. The thing is that in the signup form I get this error and I don t understand why I'm pretty new to the whole PHP stuff and I didn't find much about this error.
The HTML file
<html>
<head>
<title>PHP Signup system</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="frm">
<h1>Signup</h1>
<form name="f1" action="registration.php" onsubmit="return validation()" method="POST">
<p>
<label> UserName: </label>
<input type="text" id="user" name="Username" />
</p>
<p>
<label> Password: </label>
<input type="password" id="pass" name="Password" />
</p>
<p>
<label> Password: </label>
<input type="password" id="passc" name="Confirm Password" />
</p>
<p>
<label> Email: </label>
<input type="text" id="email" name="Email" />
</p>
<p>
<input type="submit" id="btn" value="Submit" />
</p>
</form>
</div>
<script>
function validation() {
var id = document.f1.user.value;
var ps = document.f1.pass.value;
var psc = document.f1.passc.value;
var em = document.f1.email.value;
if (id.length == "" && ps.length == "") {
alert("User Name and Password fields are empty");
return false;
} else {
if (id.length == "") {
alert("User Name is empty");
return false;
}
if (ps.length == "") {
alert("Password field is empty");
return false;
}
if (em.length == "") {
alert("Email field is empty");
return false;
}
if (ps != psc) {
alert("Passwords do not match");
return false;
}
}
}
</script>
</body>
</html>
It is pretty simple, and it doesn't have to look good, just to work.
EDIT: I got it, the problem was in fact that I misused the post method and names and that after that I forgot to make the connection with the database. credits to the guy in comments

Your post value is not set.
$_POST['foo'] // <== if not set or falsy, returns an undefined index warning
You must check if $_POST is populated before proceeding to execute you backend logic. Place the following at the top of your script and replace foo on your input's name.
if(!isset($_POST['foo']) || !$_POST['foo']){
// $_POST is not set. Notify user then exit!
echo 'Field "foo" is required!';
exit;
}
Or if your submit functions are in the same file of your form, try this:
if(isset($_POST['foo']) && $_POST['foo']){
// place your backend logic here to ensure that the required field(s) are field
}

Related

Registration form validation problem using php and tetxt file

I created a registration form which is working fine. I save all of my users data in a txt file named users.txt which saves the the data after the button click like this:
username|password|email
here is my users.txt file:
asd|asd|asd
asd|asd|asd
sanyi|123456|asd#asd.hu
sanyi|123456|asd#asd.hu
sanyi|123456|asd#asd.hu
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
frici|123|vass.frigyes#gmail.com
I want to solve that the username must be unique! I tried to solve this by check the txt file before the registration and if I find the same username in the txt that the user submitted, kill the process. I can check the first line username but I have no idea how I can go to the next line, and so on...
My php code:
register.php:
<!-- html section -->
<!DOCTYPE html>
<html>
<head>
<title>Store form data in .txt file</title>
</head>
<body>
<form action="#" method="post">
REGISTRATION<br />
<input type="text" name="username" placeholder = "Username"/><br />
<input type="text" name="password" placeholder = "Password" /><br />
<input type="text" name="password2" placeholder = "Password Again"><br />
<input type="text" name="email" placeholder = "Email Adress"/><br />
<input type="submit" name="submit" value = "REGISTER" />
</form>
</body>
</html>
<!-- php section -->
<?php
if(isset($_POST['submit']))
{
//check if the username has been already taken
$usernameToCheck = $_POST["username"];
$userlist = file ('users.txt');
$success = false;
foreach ($userlist as $user) {
$user_details = explode('|', $user);
if ($user_details[0] == $usernameToCheck) {
die("This user is already exsists");
}
}
// the registreation itself
$username = $_POST["username"];
$password = $_POST["password"];
$password2 = $_POST["password2"];
$email = $_POST["email"];
if(empty($username) || empty($password) || empty($password2) || empty($email)){
die("You filled out the form wrongly! Don't let anything empty next time!");
}else if($password !== $password2){
die("Passwords doesnt match!");
}else{
$fp = fopen('users.txt', 'a');
$line = $username."|".$password."|".$email.PHP_EOL;
fwrite($fp, $line);
fclose($fp);
}
}
?>

Can I use jQuery to dynamically style a form after it's validated with PHP?

I'm trying to add styling to certain parts of my form based on what happens in my PHP script. For example, I'd like to add a class to an input that the user fills out incorrectly that will trigger CSS rules, such as making the input's border red.
I thought I might be able to do this using jQuery at the end of my PHP script, but I haven't been successful despite writing it several different ways. I checked to make sure my new CSS styling came after the default styling too. It may also be worthwhile to mention that I'm using AJAX to validate as well, so the user stays on the registration page if the form is not filled out properly.
Here is my PHP script (jQuery is at the end):
<?php
if (isset($_POST['submit']))
{
include_once "_databaseHandler.php";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$confirmPassword = mysqli_real_escape_string($connection,
$_POST['confirmPassword']);
$errorEmpty = false;
//Check for empty fields
if (empty($username) || empty($email) || empty($password) ||
empty($confirmPassword))
{
echo "<span class='form-error'>Please fill in all fields</span>";
$errorEmpty = true;
}
else
{
$sqlUsername = "SELECT * FROM userinfo WHERE userName = '$username'";
$resultUsername = mysqli_query($connection, $sqlUsername);
$resultCheckUsername = mysqli_num_rows($resultUsername);
$sqlEmail = "SELECT * FROM userinfo WHERE userEmail = '$email'";
$resultEmail = mysqli_query($connection, $sqlEmail);
$resultCheckEmail = mysqli_num_rows($resultEmail);
//Check length of username
if (strlen($username) < 4)
{
echo "<span class='form-error'>Your username must be at least 4
characters long</span>";
$errorEmpty = true;
}
//Check if username is taken
else if ($resultCheckUsername > 0)
{
echo "<span class='form-error'>This username is already
taken</span>";
$errorEmpty = true;
}
//many other checks with exact same syntax using else if...
//Insert the user into the database
else
{
$sql = "INSERT INTO userinfo (userName, userEmail, userPassword) VALUES (?, ?, ?);";
$statement = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($statement, $sql))
{
echo "<span class='form-error'>Database error</span>";
exit();
}
else
{
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($statement, "sss", $username, $email, $hashedPassword);
mysqli_stmt_execute($statement);
$emailSubject = "wtf";
$emailMessage = "Hello my son";
mail($email, $emailSubject, $emailMessage);
session_start();
$_SESSION['register-success'] = 'You have successfully registered! Please verify your email before logging in.';
echo
"<script type=\"text/javascript\">
window.location.href='../index.php';
</script>";
exit();
}
}
}
}
else
{
header('Location: ../index.php');
exit();
}
?>
<reference path="jquery-3.3.1.min.js"/>
<script type="text/javascript">
var errorEmpty = "<?php echo $errorEmpty; ?>";
if (errorEmpty)
{
$("#register-username").addClass(".input-error");
}
</script>
Full context of related code:
jQuery:
/// <reference path="jquery-3.3.1.min.js" />
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var username = $("#register-username").val();
var email = $("#register-email").val();
var password = $("#register-password").val();
var confirmPassword = $("#register-confirm-password").val();
var submit = $("#register-submit").val();
$(".form-message").load("../shared/_registerAccount.php", {
username: username,
email: email,
password: password,
confirmPassword: confirmPassword,
submit: submit
});
});
});
HTML:
<?php
include "shared/_header.php";
?>
<div class="wrapper-register">
<div id="register-account">
<div class="register-title">
<h2>REGISTER ACCOUNT</h2>
</div>
<form action="shared/_registerAccount.php" method="post">
<div class="register-input">
<input id="register-username" type="text" name="username"
maxlength="16" placeholder="Username" />
</div>
<div class="register-input">
<input id="register-email" type="text" name="email"
maxlength="128" placeholder="Email" />
</div>
<div class="register-input">
<input id="register-password" type="password" name="password"
maxlength="128" placeholder="Password" />
</div>
<div class="register-input">
<input id="register-confirm-password" type="password"
name="confirmPassword" maxlength="128"
placeholder="Confirm Password" />
</div>
<input id="register-submit" type="submit" name="submit"
value="SIGN UP" class="register-button" />
</form>
<p class="form-message"></p>
</div>
</div>
<?php include "shared/_footer.php" ?>
<script src="javascript/register.js"></script>
</body>
</html>
There can be following issues when CSS is not being applied"
You have not included the CSS file (I don't see the file inclusion in your code)
You are applying it on an undefined ID or the class doesn't exist (Both of them can't be verified from your provided code).
The class name you are applying is wrong (In your case, you are applying '.input-error' if your class name starts with a '.', you need to escape it.)

Check if username is being used

I'm wondering if and how I could check if a username is being used.
I heard you can do this with jQuery but i just want something simple since I'm a beginner.
I have tried it but i can't seam to get it right. I just have it connected to a mysql database but since when a username with the same password as another account tries to logon, theres an issue, so i need this to stop people adding multiple usernames.
Here is my simple code for the registration form and the php
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
</div>
<?php
require('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
?>
For starters you don't want to just rely on something like unique field for doing this, of course you will want to add that attribute to your username column within your database but above that you want to have some sort of frontal protection above it and not rely on your database throwing an error upon INSERT INTO, you're also going to want to be using mysqli for all of this and not the old version, mysql. It's vulnerable to exploitation and no longer in common practice, here's what each of your files should look like:
connect.php
<?php
$conn = mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
register.php
<form action="insertuser.php" method="POST">
Username:
<input type="text" name="username" placeholder="Username" />
<br />
Password:
<input type="password" name="password" placeholder="Password" />
<br />
Name:
<input type="text" name="name" placeholder="Name" />
<br />
Email address:
<input type="text" name="email" placeholder="Email address" />
<br /><br />
<input type="submit" value="Register" />
</form>
<?php
// If there's an error
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == "usernametaken") {
echo "<h4>That username is taken!</h4>";
} elseif ($error == "inserterror") {
echo "<h4>Some kind of error occured with the insert!</h4>";
} else {
echo "<h4>An error occured!</h4>";
}
echo "<br />";
}
?>
Already have an account? Login here
insertuser.php
<?php
// Stop header errors
ob_start();
// Check if form has been posted
if (isset($_POST['username'])){
// Requre database connection file
require('connect.php');
// Clean the variables preventing SQL Injection attack
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
// Check if the username exists
// Construct SELECT query to do this
$sql = "SELECT id FROM user WHERE username = '".$username."';";
$result = mysqli_query($conn, $sql);
$rowsreturned = mysqli_num_rows($result);
// If the username already exists
if ($rowsreturned != 0) {
echo "Username exists, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=usernametaken');
} else {
// Construct the INSERT INTO query
$sql = "INSERT INTO user (username, password, email, name) VALUES ('".$username."', '".$password."', '".$email."', '".$username."');";
$result = mysqli_query($conn, $sql);
if($result){
// User was inserted
echo "User inserted!";
/* DO WHATEVER YOU WANT TO DO HERE */
} else {
// There was an error inserting
echo "Error inserting, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=inserterror');
}
}
}
?>
Good luck with whatever you're working on and I hope this helps!
James
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "select username from user where username = '$username'";
$res = mysql_query($query);
$rows = mysqli_num_rows($res);
if ($rows > 0) {
print 'Username already exists...';
} else {
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
}
Here is another example :) , succes.
<?php
//Set empty variables.
$usernameError = $emailError = $passwordError = $nameError = $okmsg = "";
$username = $password = $email = $name = "";
if (isset($_POST['submit'])) {
//Check if empty labels form
if (empty($_POST['name'])) {
$userError = "The 'name' is required.";
echo '<script>window.location="#registrer"</script>';
} else { $name = $_POST['name']; }
if (empty($_POST['email'])) {
$emailError = "El 'Email' es requerido.";
echo '<script>window.location="#registrer"</script>';
} else {
$email = $_POST['email'];
//Check only contain letters and whitespace.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "El 'Email' is not valid. ";
echo '<script>window.location="#registrer"</script>';
}
}
if (empty($_POST['password'])) {
$passwordError = "The 'password' is requiered.";
echo '<script>window.location="#registrer"</script>';
} else {
$password = $_POST['password'];
}
}
//Check if correctly filled
if ($name && $username && $email && $password) {
require('connect.php');
//Query SQL
$sql = "SELECT * FROM user WHERE username='$username'"; //String SQL
$query = mysqli_query($ConDB, $sql);//Query
//Securite
$username = mysqli_real_escape_string($ConDB, $username);
$password = mysqli_real_escape_string($ConDB, $username);
$passw = sha1($password);//For securite.
$name = mysqli_real_escape_string($ConDB, $username);
$email = mysqli_real_escape_string($ConDB, $username);
if ($existe = mysqli_fetch_object($query)) {
$usernameError = "The 'Username' is already exists.";
echo '<script>window.location="#registrer"</script>';
} else {
$sql = "INSERT INTO user (username, password, email, name) VALUES ('$username', '$passw', '$email', '$name')";
mysqli_query($ConDB, $sql);
$okmsg = "Register with succes.";
mysqli_close($ConDB);//Close conexion.
echo '<script>window.location="#registrer"</script>';
}
}
?>
<a name="registrer"></a>
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<?php echo $nameError; ?>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<?php echo $usernameError; ?>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<?php echo $emailError; ?>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<?php echo $passwordError; ?>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
<?php echo $okmsg; ?>
</form>
--
-- DATA BASE: `user`
--
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE user (
id int(11) unsigned not null auto_increment primary key,
name varchar(50) not null,
email varchar(80) not null unique,
username varchar(30) not null unique,
password varchar(40) not null
)engine=InnoDB default charset=utf8 collate=utf8_general_ci;
You can try use jQuery AJAX for what you want.
First, add this to your registration.php file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user submit the form
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
So now your registration.php file will look like this
registration.php
<form action="" method="POST">
<p>
<label>name : </label>
<input id="password" type="text" name="name" placeholder="name" />
</p>
<p>
<label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" />
</p>
<p>
<label>E-Mail : </label>
<input id="password" type="email" name="email"/>
</p>
<p>
<label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user typing in 'username' textbox
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
Then create php file named check_username.php to check the username submitted by user if it is already existed in database or still available.
check_username.php
<?php
// Check if 'username' textbox is not empty
if(!empty($_POST['username'])){
$username = trim(mysqli_real_escape_string($_POST['username']));
// Check the database if the username exists
$query = "SELECT username FROM `user` WHERE username = '".$username."'";
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0){
// if username already exist
// insert into array, to be sent to registration.php later
$response['status'] = 'exists';
}
else{
// if username available
$response['status'] = 'available';
}
}
header('Content-type: application/json');
echo json_encode($response);
exit;
?>
Here is how it works:
1. When user click the register button, jQuery will call check_username.php.
2. Now in check_username.php it will check the database if the username submitted already exists or still available.
3. Whatever the result either exists or available, check_username.php will send the result back to registration.php as string contains 'exists' or 'available'.
4. registration.php now get the result and will check the result sent by check_username.php if it contain 'exists' or 'available'. If the string is 'exists' then alert will be triggered. If the string is 'available', the form will be submitted.

Why won't my log in page receive any information?

I made a login page for my website. The connection to the database is fine, and I am typing in to the login form the correct values that are in the database. I have a md5 on the password in both the database and the code. Yet, when I check to see if any rows come back, there are none. I would just like another set of eyes to look over what is probably a stupid mistake.
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($password);
$query = "SELECT * FROM users WHERE password = '$password' AND email='$email' AND activated='1'";
$queryrun = mysql_query($query);
while($row = mysql_fetch_assoc($queryrun)) {
$fname = $row['firstname'];
echo $fname;
}
$logincheck = mysql_num_rows($queryrun);
if ($logincheck > 0) {
echo 'good, you are in our database';
} else {
echo 'sorry, you are not in our database';
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
Login <br />
<form action="login.php" method="POST">
Email: <input type="text" name="email" />
Password: <input type="password" name="password" />
<input type="submit" value="Log in" />
</form>
</body>
</html>

Showing form errors on a dropdown form

my title might sound strange so I'll try to explain it better in here.
I have a login form that is hidden when you visit the page. It's located in the upper right corner as a small dropdown form. This is the code without the Jquery since I think it isn't needed for my problem:
<!DOCTYPE html>
<?php
include "core/init.php";
?>
<html>
<head>
<title>Swimstats</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<header>
<div id="border"></div>
<div id="login">
<div id="userName" class="toggleOff">
<?php
if(logged_in() === true){
echo '<p>Welcome ' . $_SESSION['userID'] . '</p>';
} else {
?>
<p>Have an account? <span id="test">Sign in here!</span></p>
<?php } ?>
</div>
<div id="login-content">
<form class="clearfix" action="checkuser.php" method="post">
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
</div>
</header>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
SO a simple dropdown form, but I whenever the user fills in faulty credentials or leaves something empty or whatever I need to show an error under the form or above, doesn't matter. I have the following code to catch the errors:
<?php
include "core/init.php";
if(empty($_POST) === false){
$email = $_POST['email'];
$password = $_POST['password'];
if(empty($email) === true || empty($password) === true){
$errors[] = 'You need to enter your email and password.';
} else if(user_exists($email) === false){
$errors[] = 'Unable to find that email.';
} else {
$login = login($email, $password);
if($login === false){
$errors[] = 'Email/password combination is incorrect!';
} else {
$_SESSION['userID'] = $login;
header('Location: index.php');
exit();
}
}
}
?>
But this method will just bring me to the checkuser.php page and show me the errors there while I have to get the errors show on the form, but I seriously have no clue how to get that.
Ok, found the solution:
Here's my Jquery part:
$(document).ready(function(){
$(".bt_login").click(function(){
email = $("#email").val();
password = $("#password").val();
if(email == '' || password == ''){
$(".errors").html("Please fill in both fields!");
return false;
}
$.ajax({
type: "POST",
url: "checkuser.php",
data: "email=" + email + "&password=" + password,
success: function(html){
if(html == 'true'){
window.location = "index.php";
} else {
$(".errors").html("Wrong username or password!");
}
}
});
return false;
});
});
and my checkuser.php:
<?php
include "core/init.php";
$email = $_POST['email'];
$password = md5($_POST['password']);
$query = "SELECT * FROM user WHERE email = '$email' AND password = '$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
$row=mysql_fetch_array($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['userID']=$row['userID'];
$_SESSION['last_name']=$row['last_name'];
$_SESSION['first_name']=$row['first_name'];
}
else{
echo 'false';
}
?>
Although it may not be the safest solution, it works for now :) Will try to build in more security later.

Categories