POST'ed data being read as empty in sign up script - php

I'm trying to build a sign up script with PHP for a website, however whenever I input information into one of the "input" tags, for some reason they're being returned as empty, although they really aren't.
In my signup.php I have created this form to post data:
<form class="form-inline" action="includes/signup-inc.php" method="post">
<div class="">
<input type="text" name="email" class="form-control transparent" placeholder="Your email here...">
<input type="password" name="pwd" class="form-control transparent" placeholder="Your password here...">
<input type="text" name="uid" class="form-control transparent" placeholder="Your username here...">
<button type="submit" name="submit" class="btn btn-danger btn-fill">Sign Up</button>
</div>
</form>
Which brings the data over to my signup-inc.php file to allow a user to signup for an account. Whenever I try to signup for an account on my website, the error I created called "emptyInputSignup" keeps being thrown back.
This is what I have in my signup-inc.php:
if(isset($_POST["submit"])){
$email = $_POST["email"];
$pwd = $_POST["pwd"];
$uid = $_POST["uid"];
require_once 'dbh-inc.php';
require_once 'functions-inc.php';
if(emptyInputSignup($email, $pwd, $uid) !== false){
header("location: ../signup.php?error=emptyinput");
exit();
}
And the function being referenced, which I have created in my 'functions-inc.php' is here:
<?php
function emptyInputSignup($email, $pwd, $uid){
$results;
if(empty($email) || empty($pwd) || empty($uid)){
$results = true;
}
else {
$results = false;
}
}
Personally what I've done to try to debug to see if any data is in fact coming through is nulled the error handle which brings you back a page, to signup.php and instead echo'd a statement into the signup-inc.php page with the data being input. All 3 variables are echoed to the signup-inc.php page with the exact string written in the input field.
Any ideas on what I could be missing?

I'm not sure if this is it, but I don't see you actually return the result from the helper function. I think you can simplify it a bit as well, maybe give this a try
<?php
function emptyInputSignup($email, $pwd, $uid){
return empty($email) || empty($pwd) || empty($uid);
}

Related

How to pass and put variable from a php page into a another page(form)?

I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I'm strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here's my code:
First page - contato.html
<form action="validate.php" method="POST" name="emailform">
<div class="form-group">
<input type="text" id="name" name="nome" placeholder="Type your name">
</div>
<div class="form-group">
<input type="text" id="email" name="email" placeholder="type your#email.com here">
</div>
<div class="form-group">
<textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page - validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome'];
if(isset($_POST['email'])) $email_visitante = $_POST['email'];
if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem'];
// if does not meet the criteria, redirect to contato.html and update the form with the info
if(empty($nome)){
Header("location:contato.html");
}
if(empty($email_visitante)){
Header("location:contato.html");
}
if(empty($mensagem)){
Header("location:contato.html");
}
// check for letters and space only
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
Header("location:contato.html");
}
// check if e-mail address is well-formed
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
Header("location:contato.php");
}
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php
// page 1
session_start();
// Set session variables
$_SESSION["nome"] = $nome;
$_SESSION["email"] = $email_visitante;
$_SESSION["mensagem"] = $mensagem;
<?php
// page 2|3|N - any other page
session_start();
// Get session variables
$nome = $_SESSION["nome"];
$email_visitante = $_SESSION["email"];
$mensagem = $_SESSION["mensagem"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}

Login form validation message

Whenever I try to login with incorrect information I don't get the error message, It just resets my form when I try to login with incorrect information. I think I might have a conflicting code somewhere. Is there something wrong with my code? Or if possible is there any other way to provide validation based on my code?
Everything works fine. I just need the validation.
My PHP:
<?php
session_start();
ob_start();
//Include the database connection file
include "database_connection.php";
//Check to see if the submit button has been clicked to process data
if(isset($_POST["submitted"]) && $_POST["submitted"] == "yes")
{
//Variables Assignment
$username = trim(strip_tags($_POST['username']));
$user_password = trim(strip_tags($_POST['passwd']));
$validate_user_information = mysql_query("select * from `signup_and_login_users_table` where `username` = '".mysql_real_escape_string($username)."' and `password` = '".mysql_real_escape_string($user_password)."'");
//Validate against empty fields
if($username == "" || $user_password == "")
{
$error = '<br><div class="info">Sorry, all fields are required to log into your account. Thanks.</div><br>';
}
elseif(mysql_num_rows($validate_user_information) == 1) //Check if the information of the user are valid or not
{
//The submitted info of the user are valid therefore, grant the user access to the system by creating a valid session for this user and redirect this user to the welcome page
$get_user_information = mysql_fetch_array($validate_user_information);
$_SESSION["VALID_USER_ID"] = $username;
$_SESSION["USER_FULLNAME"] = strip_tags($get_user_information["fullname"]);
header("location: home.php");
}
else
{
//The submitted info the user are invalid therefore, display an error message on the screen to the user
$error = '<br><div class="info">Sorry, you have provided incorrect information. Please enter correct user information to proceed. Thanks.</div><br>';
}
}
?>
My form:
<div class="login">
<font color="black" size="5"><p>Employee Login</p></font>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="username" placeholder="Username" required="required" />
<input type="password" name="passwd" placeholder="Password" required="required" />
<input type="hidden" name="submitted" id="submitted" value="yes">
<button type="submit" name="submit" class="btn btn-primary btn-block btn-large">Login</button>
<p></p>
<a href="index.php"><img src="img/homebutton.png" height="35px" width="35px">
</form>
</div>
First of all use mysqli functions not mysql because they are now deprecated.
Secondly, the reason you are not getting the error message is because you have not printed the error message. You should add echo $error; after you defined your error variable

not getting entries from text boxes php

For the last couple of days I have been having an issue where my PHP code will not get the text from a form text box that has worked for 7 or 8 years. Has anyone else has this issue or is there something that may need to be running that isn't?
My PHP form is a username textbox and password textbox and submit button
this is the code that is going to the die because the username isn't being set:
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
} else {
die('User is blank'); //$username = "";
}
this error is going to my error_log
PHP Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 4 in /home/
I know I know... no mysqli
form html:
<form method="post" onsubmit="return vloginform(this);"
action="https://www..com/php_include/processlogin.php"
name="loginform">
<div id="pleft">
<div class="uandp">Username: </div><div class="inputbox"><input type="text"
name="username" maxlength="30" class="buttonsboxes" style="width: 180px;" />
</div>
<div class="uandp">Password: </div><div class="inputbox"><input
type="password" name="password" maxlength="30" class="buttonsboxes"
style="width: 180px;" /></div>
</div>
<div id="pright">
<p><input class="buttonsboxes" type="submit" value="login" name="submit"
id="submit" /><input class="buttonsboxes" type="reset" value="reset"
name="reset" id="reset" /></p>
</div>
Not sure how you are fetching the records but using mysql_fetch_array instead of manually fetching every column value will fix this issue. Try analysing the result before fetching it. If result is empty, skip fetching.
Something like this:
$result = mysql_query("SELECT * FROM tablename");
if (!$result || !mysql_num_rows($result)) {
die('No records.');
}
while ($row = mysql_fetch_array($result)) {
// Your code goes here
}
Just use the tag required in the textbox or if you are using the $_POST VARIABLE.
POST:
if(isset($_POST['username'])) {
$username = $_POST['username'];
} else {
die('User is blank'); //$username = "";
}
You might want to use $_REQUEST variable instead of $_SESSION variable because whenever the data is transferred from a form to php page, it is transferred in $_REQUEST variable not in $_SESSION variable.
Use can do something like:
if(isset($_REQUEST['username'])) {
$username = $_REQUEST['username'];
} else {
die('User is blank'); //$username = "";
}
UPDATE
As per your code, you are using post method to send the data, so you should you $_POST variable to get the data from the form:
$username = $_POST['username'];
and you can check whether it is empty or not by writing following line of code:
if ($username == null) {
die('User is blank'); // if username = "", this line will be executed
} else {
// do the required task...
}
I just tried the function - isset($_REQUEST['username']) and isset($_POST['username']) also, but it is not giving the desired result. But I have got above code to work.
Hope this helps:)

Possible stupid error! IF statement not running?

A little context, the registration part works fine, however I want to now add a login system. I want to test to see if the username exists but this isn't working.
Can anyone spot the error here?
Feel free to check it on a server over here - it's a WIP so there's still lots to do. The username "Lewis" is currently entered into the database for testing purposes.
As you can see, after the form has been filled etc. none of the echo statements run, in fact, even if an echo is put directly below the first 'IF' statement, it still doesn't print, so what is the problem? I've also tried changing the IF to:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
Still no luck.
PHP:
//error_reporting(E_ALL);
//ini_set('display_errors', TRUE);
require 'vdb_includes/db.php';
require 'functions.php';
if(!empty($_POST['username']) && !empty($_POST['pw'])){
$verifyUsername = $_POST['username'];
$verifyPassword = $_POST['pw'];
$usernameCheck = mysqli_query($con, "SELECT * FROM users WHERE username='".$verifyUsername."'");
if($usernameCheck->num_rows){
echo "Username exists";
} else {
echo "Non existant";
}
}
HTML:
<form id="login_form" action="http://valhq.com/login" method="POST">
<div class="login_form_content">
<div class="login_form_input">
<input type="text" class="login_input_style" placeholder="Username" id="username" name="username" maxlength="20">
</div>
<div class="login_form_input">
<input type="password" class="login_input_style" placeholder="Password" id="pw" name="pw" maxlength="56">
</div>
<input type="submit" id="submit" name="submit" class="login_submit" value="Login">
<div class="login_notMember">
Don't have an account? Sign up.
</div>
</div>
</form>
You have a 301 redirect to add a slash at the end of your url when it's missing. You haven't got a slash at the end of your form action and because of that the form post gets redirected to the url with the slash. Solution: add a slash at the end of the form action and it will work.

Displaying differnt border color if field is valid

So I have my form which I have supplied pictures of below. The left side picture is a normal border color but then the red outline on the right is when the form input is invalid.
How would I do this through PHP? Here's the corresponding code
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
exit($e->getMessage());
}
// Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
// Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)) {
echo "Complete all fields";
}
// Password match
if ($password != $password1) {
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
And my HTML form
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
So if the input satisfies the if statement how would I display the color?
When your form has errors, you need to re-display it. It's hard to give a recommendation without knowing your code structure, but I will assume that your HTML is rendered via a call to php. Generally, I have done something like
$error = false
//this $_GET['submit'] variable could be part of the URL of your submitted form.
//alternately, you could check the HTTP method of the page request
if ($_GET['submit']) {
//run your form logic
//if you have success, run your php query and then redirect
//to your "success" page using a 302 (using a header("Location:... sort of call)
//you would also want to call die() or something right here
}
//if you make it this far, display your page including the bits about errors
//your form's action goes right back to the same page that rendered it, but with
//some change to the url to let the script know that you want to process the form
With PHP5 and with warnings about undefined variables turned on, you would need to define all of your error message variables before checking whether or not the form is being submitted.
Asuming you are using twitter bootstrap since you have form-control all over the place, (assuming >= 3.0.0), you can use (for the graphical side of things) has-suceess, has-error, etc like shown here: http://getbootstrap.com/css/#forms-control-validation.
When you re-display the form due to bad data, pass along your error messages to whatever renders your html. An example with your thing would be (assuming your form has access to $passmatch, $emailvalid,$passlength):
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
</div>
<div class="form-group <?php if (!empty($emailvalid)) { echo 'has-error'; } ?>">
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
</div>
<div class="form-group <?php if (!empty($passmatch) || !empty($passlength)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group <?php if (!empty($passmatch)) { echo 'has-error'; } ?>">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
I would recommend using a templating engine or something to separate the view from the actual code.
As for the help text, you can use something like this after the elements with errors:
<div class="form-group <?php if (!empty($yourVariable)) { echo 'has-error'; }?>">
<input type="text" class="form-control" />
<span class="help-block"><?php echo $yourVariable; ?></span>
</div>
The fun part is, if you have no error message, the help block won't even be shown because that variable won't have anything in it.
EDIT
Example page: http://content.kevincuzner.com/register.php
Example source: https://gist.github.com/kcuzner/11323907
I would handle this on the client side with JavaScript. On submission of the form, you can check whether the input is valid or not and then just update the border color using JavaScript.
The <?php ?> you can fill in above (if you want to go this route) can just depend on some variable that checks validity:
echo "Complete all fields";
$fieldsValid = false;
border-color: <?php $fieldsValid ? 'blue' : 'red' ?>
But you need to do a full page reload for this to work. JavaScript is a better route:
document.forms[0].addEventListener("submit", function () {
var usernameInput = document.querySelector("[name=username]");
if (!usernameInput.value) {
usernameInput.style.borderColor = "red";
}
});

Categories