Form Registration not getting a error - php

so i edited my code but still unable to get the results part of code is responsible for reporting error that do not work too
i'm open to other ways of coding to do the work as long as it fits in the code here comes the code
<?php
require 'core.inc.php';
if(!loggedIn()) {
//check mikunim ke tamame field ha dar form vojod darand va set shudan
if(isset($_POST['username'])&&isset($_POST['password'])&&isset($_POST['password_again'])&&isset($_POST['firstname'])&&isset($_POST['surname'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$password_again = $_POST['password_again'];
$firsname = $POST['firstname'];
$surename = $POST['surename'];
//HALA CHECK MIKUNIM KHALI HASTAND YA NA
if(!empty($username)&&!empty($password)&&!empty($email)&&!empty($firstname)&&!empty($surename)){
echo 'ok' ;
} else {
echo ' All fields are required';
}
}
?>
<form action="register.php" method="POST">
Username:<br> <input type="text" name="username"><br> <br>
Password:<br> <input type="password" name="password"><br><br>
Password again:<br> <input type="password" name="password_again"><br><br>
Firstname:<br> <input type="text" name="firstname"><br><br>
Surname:<br> <input type="text" name="surename"><br><br>
<input type="submit" value="register">
</form>
<?php
} else if (loggedIn()) {
echo 'you \'re already logged in';
}
i edited again now i get this
Notice: Undefined index: HTTP_REFERER
$http_referer = $_SERVER['HTTP_REFERER']
i used this from tutorial

change this
$firsname = $POST['firstname'];
$surename = $POST['surename'];
to this:
$firstname = $_POST['firstname'];
$surename = $_POST['surename'];

Related

issues with multiple forms on php page

i am trying to make a simple login system, with password recovery option,, so i made a password reset link.
hwoever, it is not working, meaning that form2's button just leads back to form1 (leads back to username and email form && i have three different forms), so i separated it into three different if statements, for each button clicked, but the same issue keeps on happening.
please tell me what is happening and ho to fix it
thank you.
(code is below)
//not actually js, but is php
session_start();
if(isset($_SESSION['username']) && isset($_SESSION['password'])){
header("Location: changepass.php");
}
if(($_SERVER["REQUEST_METHOD"] == "POST")) {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "test";
$con = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connection failed: %s\n". $con -> error);
$GLOBALS['email'] = $_POST['email'];
$GLOBALS['username'] = $_POST['username'];
$result = mysqli_query($con,"SELECT * FROM login WHERE email='" . htmlspecialchars($GLOBALS['email']) . "' and username = '". htmlspecialchars($GLOBALS['username'])."'");
$count = mysqli_num_rows($result);
//Part 1
if($_POST['submit1']) {
if($count==0) {
echo "<script>
document.getElementById('error').innerHTML += 'Invalid Username or Email.';
</script>";
} else {
echo "<script>
document.getElementById('main').style.display = 'none';
</script>";
echo "<script>
document.getElementById('next').style.display = 'inline-block';
</script>";
echo "<script>
document.getElementById('verify').innerHTML += 'A verification email has been sent to you. Copy the verification code and paste it above.';
</script>";
$GLOBALS['token'] = bin2hex(random_bytes(3));
echo $GLOBALS['token'];
$to = $GLOBALS['email'];
$subject = "Password Reset";
$msg = "Hello. Your token is <strong>" . $GLOBALS['token'] . "</strong>. <br>Good day.";
$msg = wordwrap($msg,70);
$headers = "From: email#example.com";
mail($to, $subject, $msg, $headers);
}
}
//Part 2
if($_POST['submit2']) {
if($_POST['code'] != $GLOBALS['token']) {
echo "<script>
document.getElementById('error2').innerHTML += 'Invalid verification code.';
</script>";
} else {
echo "<script>
document.getElementById('next').style.display = 'none';
</script>";
echo "<script>
document.getElementById('final').style.display = 'inline-block';
</script>";
}
}
//Part 3
if($_POST['submit3']) {
$np = $_POST['np'];
$cnp = $_POST['cnp'];
if($np != $cnp) {
echo "<script>
document.getElementById('error3').innerHTML += 'Passwords do not match.';
</script>";
} else {
$sql = "UPDATE login SET password='$cnp' WHERE email=" . $GLOBALS['email'];
$rs = mysqli_query($con, $sql);
if($rs) {
echo "Changed password successfully! Click <a href='login.php'>here</a> to sign in.";
} else {
echo "An unknown error occurred. Please try again.";
}
}
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reset Password</title>
</head>
<body>
<fieldset>
<legend>Reset Password</legend>
<form name="frmContact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="main">
<label for="email">Email</label>
<input type="email" style="display:inline-block" name="email" id="email" required autofocus />
<br>
<br>
<label for="username">Username</label>
<input type="text" style="display:inline-block" name="username" id="username" required />
<br>
<p id="error" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit1" id="submit1" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact2" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="next" style="display:none;">
<p id="verify" style="color:green"></p>
<label for="code">Verification Code</label>
<input type="text" style="display:inline-block" maxlength="6" name="code" id="code" required autofocus /> <p style="color:red;display:inline-block" id="validatecode"></p>
<br>
<p id="error2" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit2" id="submit2" value="Reset Password" /> Create an Account Sign in
</p>
</div>
</form>
<form name="frmContact3" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="final" style="display:none;">
<label for="np">New Password</label>
<input type="text" style="display:inline-block" name="np" id="np" required autofocus /> <p style="color:red;display:inline-block" id="validatenp"></p>
<br>
<label for="cnp">Confirm New Password</label>
<input type="text" style="display:inline-block" name="cnp" id="cnp" required autofocus /> <p style="color:red;display:inline-block" id="validatecnp"></p>
<br>
<p id="error3" style="color:red"></p>
<p> </p>
<p>
<input type="submit" name="submit3" id="submit3" value="Reset Password" />
</p>
</div>
</form>
</fieldset>
</body>
</html>
Just for sake of debugging remove all extra stuff from that file and focus on 3 if statements
Also try using
if(isset($_POST['submit1']))
Always try to close in onto the problem at hand and remove extra stuff that is in there. It helps make simpler but better decisions.

PHP- Form Validation Errors

This is my first time validating, I am having the hardest time have spent endless hours on this already. I have a registration form that needs to be validated, i have tried 2 scripts for this. The script that works best can be seen below: however every time I try to echo the error message to display under my text field i receive the following error messages:
Notice: Undefined variable: c_email in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 161
Notice: Undefined variable: c_emailErr in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 163
Notice: Undefined variable: c_pass1Err in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 169
C_emailErr and c_pass1Err are both defined.
any help would be appreciated.
HTML
<section class="container">
<form id="myform " class="Form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" accept-charset="utf-8">
<!--<div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value="<?= $c_email ?>" required >
<br>
<span class="error"><?php echo $c_emailErr; ?></span>
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="<?= $c_pass1 ?>" placeholder="Password" maxlength="30" required>
<br>
<span class="error"><?php echo $c_pass1Err; ?></span>
<br>
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
<?php
?>
</form>
</section>
PHP
<?php
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo ("<b id='email'> This is a valid email address </b>");
} else {
echo ("<b id='email'> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
} elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>
You are defining those variables, but you are defining them inside of an if block.. Move them outside of the if block.
<?php
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];

PHP variables not being passed to the next page

So I have two files. The first is the index.php in the root folder the other is an index.php found in a controller folder named post_link. I want to pass email, password, and action from the form in index.php of the root to the index.php of post_link but its just passing empty values when I try to get them using, filter_input(INPUT_POST, 'value'). How do I pass variables from index.php of the root to the index.php of post_link?
index.php of the root:
<?php
session_start();
require_once('model/fields.php');
// Add header
include '/view/header.php';
// Add fields with optional initial message
$validate = new Validate();
$fields = $validate->getFields();
$fields->addField('first_name');
$fields->addField('last_name');
$fields->addField('password');
$fields->addField('email', 'Must be a valid email address.');
// Makes sure the pages uses a secure connection
if(!isset($_SERVER['HTTPS'])) {
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: " . $url);
exit();
}
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = 'login';
$email = '';
} else {
$action = strtolower($action);
}
if ($email == '') {
$login_message = 'Login or register if you are a new user.';
}
else {
$login_message = '<span class="error">Invalid email.</span>';
}
?>
<main>
<h2>Login</h2>
<form action="post_list" method="post" class="aligned">
<fieldset>
<legend>Customer Login</legend>
<input type="hidden" name="action" value="login">
<label>Email:</label>
<input type="text" class="text" name="email">
<br>
<label>Password: </label>
<input type="text" class="text" name="password">
<br>
<label> </label>
<input type="submit" value="Login">
<br>
</fieldset>
</form>
<form action="." method="post" class="aligned">
<fieldset>
<legend>Customer Registration</legend>
<input type="hidden" name="action" value="reset">
<label>You must be registered to view posts</label>
<input type="submit" value="Register here">
</fieldset>
</form>
<p><?php echo $login_message; ?></p>
</main>
<?php include 'view/footer.php'; ?>
index.php of the controller:
<?php
// session_start();
require_once('../model/database.php');
require_once('../model/customers_db.php');
require_once('../model/validate.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = 'login';
$email = '';
} else {
$action = strtolower($action);
}
switch ($action) {
case 'login':
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST,'password');
if (is_valid_customer_login($email)) {
$_SESSION['is_valid_customer'] = true;
$customer = get_customer($email);
$first_name = $customer['firstName'];
$last_name = $customer['lastName'];
if (is_valid_customer_login_password($email, $password)) {
include('../view/customer_menu.php');
} else {
$login_message = '<span class="error">Invalid password.</span>';
include('../index.php');
}
} else {
if ($email == '') {
$login_message = 'Login or register if you are a new customer.';
}
else {
$login_message = '<span class="error">Invalid email.</span>';
}
}
break;
case 'reset':
// Reset values for variables
$first_name = '';
$last_name = '';
$email = '';
$password ='';
// Load view
include 'view/register.php';
break;
case 'register':
// Copy form values to local variables
$first_name = trim(filter_input(INPUT_POST, 'first_name'));
$last_name = trim(filter_input(INPUT_POST, 'last_name'));
$email = trim(filter_input(INPUT_POST, 'email'));
$password =trim(filter_input(INPUT_POST, 'password'));
// Validate form data
$validate->text('first_name', $first_name);
$validate->text('last_name', $last_name);
$validate->email('email', $email);
$validate->password('password', $password);
// Load appropriate view based on hasErrors
if ($fields->hasErrors()) {
include 'view/register.php';
} else {
add_customer($first_name, $last_name, $email, $password);
include 'view/customer_menu.php';
}
break;
case 'logout':
$_SESSION = array(); // Clear all session data from memory
session_destroy(); // Clean up the session ID
$login_message = 'You have been logged out.';
include('view/login.php');
break;
}
?>
This ain't gonna work this way, You have to use the action as "post_list/index.php". So modify your form as:
<form action="post_list/index.php" method="post" class="aligned">
<fieldset>
<legend>Customer Login</legend>
<input type="hidden" name="action" value="login">
<label>Email:</label>
<input type="text" class="text" name="email">
<br />
<label>Password: </label>
<input type="text" class="text" name="password">
<br>
<label> </label>
<input type="submit" value="Login">
<br>
</fieldset>

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

PHP: Why not get the data of the image that I will insert into the database?

I've the next problem: The code to validate the name, address and email works, but to validate the image does not work and do not know why that happens. As always prints "Select an image"
I did a test and set the line to print the temporary name of the image with "print $photo" but nothing prints!
form.php
<form id="formregister" name="formregister" action="register.php" method="post">
<input id="name" name="name" type="text"/>
<input id="address" name="address" type="text"/>
<input id="email" name="email" type="email" />
<input id="photouser" name="imguser" type="file"/>
<input id="bregister" name="bregister" type="submit" value="Registrer"/>
</form>
register.php
..............
$name = $_POST['name'];
$address = $_POST['address'];
$email = $_POST['email'];
$photo = $_FILES['imguser']['tmp_name'];
$errors = array();
if(!isset($photo)) {
$errors[] = "Select an image";
} else {
$fototemp = addslashes(file_get_contents($_FILES['imguser']['tmp_name']));
$fotoname = addslashes($_FILES['imguser']['name']);
$fotosize = getimagesize($_FILES['imguser']['tmp_name']);
if ($fotosize == false) {
$errors[] = "Invalid format";
}
}
//Code to validate the other fields (name, address, email)
....................
You are missing the proper enctype for file uploads on your form. It should be enctype='multipart/form-data'
<form id="formregister" name="formregister" action="register.php" method="post" enctype='multipart/form-data'>
Rather than accessing the secondary tmp_name key directly, test if it is set first to avoid undefined index notices:
if (isset($_FILES['imguser']) {
$photo = $_FILES['imguser']['tmp_name'];
}

Categories