Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
this is my page when i run it i got the excption which sayes that the formSubmit is not define . i know that i have to check if the post contents that variable but i couldn't know the solution
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formPassword']))
{
$errorMessage .= "<li> You forgot to enter your password!</li>";
}
if(empty($_POST['formName']))
{
$errorMessage .= "<li> You forgot to enter a name!</li>";
}
$varPassword = $_POST['formPassword'];
$varName = $_POST['formName'];
if(empty($errorMessage))
{
require('Document1.php');
User::add_user($varName, $varPassword);
exit;
//header("Location: normal.php");
}
}
?>
<html>
<head>
<title>SIGN UP</title>
<style type="text/css">
<!--
.style1 {
font-size: xx-large;
color: #0000CC;
}
-->
</style>
</head>
<body>
<p align="center"><br>
<span class="style1">SIGN UP</span></p>
<p> </p>
<form action="myform1.php" method="post">
<p>
What is Your NAME ?<br>
<input type="text" name="formName" maxlength="50" value="" />
</p>
<p>
What is Your PASSWORD ?<br>
<input type="text" name="formPassword" maxlength="50" value="" />
</p>
<?php
/*
?>
<p>
What is Your Email ?<br>
<input type="text" name="formEmail" maxlength="50" value="" />
</p>
*/
?>
<input type="submit" name="formSubmit" value="Submit" />
<input type=reset value = "delete fields ">
</form>
</body>
</html>
any help would be appreicated
The reason is because the PHP code also runs the very first time when the page loads, even though the form isn't yet submitted. The solution is to change your first IF statement as follows:
<?php
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit")
{
// OTHER CODE REMAINS AS IT IS
}
?>
It will now check that not only $_POST['formSubmit'] is set to "Submit" but also that it exists. When the page first loads, $_POST['formSubmit'] will not be available and therefore no exception will be thrown.
Hope it helps!
I suggest using .
if (isset($_POST['formSubmit']) && ($_POST['formSubmit'] == "Submit")) {
/* ... */
}
isset() method will check if value exists
You can check that its a $_POST request with $_SERVER['REQUEST_METHOD'] === 'POST' also add errors to an array this way you can place the errors where you want.
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$error = array();
if(empty($_POST['formPassword']))
{
$error['pass'] = "You forgot to enter your password!";
}
if(empty($_POST['formName']))
{
$error['name'] = "You forgot to enter a name!";
}
if(empty($error))
{
require('Document1.php');
User::add_user($_POST['formName'], $_POST['formPassword']);
exit;
//header("Location: normal.php");
}
}
?>
Then if error just add <?php echo isset($error['name']) ? $error['name'] : null ?> where you want the message specific to the error. like next to the input for name.
It's always a good practice to use isset() to check if a variable is set.
Change
if($_POST['formSubmit'] == "Submit")
to
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit"){
//rest of the code
}
See also: empty()
Before you try to get the value of $_POST['formSubmit'], you should check if it is set with isset($_POST['formSubmit'])
if (isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit") {
// your code
}
I think it also work with:
if ($_POST['formSubmit'] && $_POST['formSubmit'] == "Submit") {
// your code
}
but is better to use isset()
Rather than using isset() everywhere, I prefer to declare default values. For example...
$defaults = array(
'formSubmit' => '',
'formPassword' => '',
'formName' => '',
);
$form = $_POST + $defaults;
if ($form['formSubmit'] == 'Submit') {
// ...
Related
This is my first post. So sorry if I get the format wrong :)
Im trying to build a program, that asks for a input using html, sets that input as a php variable, and then calculates that variable. Everything is ready except for the input part, which I find extremely challenging. My code is as follows:
<?php
$x = 1;
$answer = ($x = 1);
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
?>
The variable I'm trying to set is the ($x = 1) part. The codes purpose is to see if a mathematical calculation is true or false. The code has already been tested.
I have already searched the internet for an answer, and sadly I only saw answers for questions that were way different.
There's one small issue with your current code: You're using = to compare a value to another, which will not work, single = is used to assign a variable. You should use == instead.
When you want to use a user's input, you will need something called $_POST, this is a method that you can set in a form using the method="POST" attribute. When the form is submitted it will create an array with the values in the form.
You can then access these values using a certain key, which is equal to the name="" attribute of the input, select or textarea in the form.
Example
Consider this form, with some PHP code:
<form method="post">
<input type="text" name="myName" placeholder="Enter your name!">
<input type="submit" value="Submit">
</form>
<?php
// When the server gets a $_POST request
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set the variable name to whatever the user put in
$name = $_POST['myName']; // equal to the name="" attribute in the form
echo "Hello, " . $name . "!";
}
?>
If I submit the form with my name, it will echo: Hello, rpm192!
For your situation, it would look something like this:
<form method="post">
<input type="number" name="answer" placeholder="Your answer">
<input type="submit" value="Submit answer">
</form>
<?php
// When the server gets a $_POST request
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set the variable X to whatever the user put in
$x = $_POST['answer'];
$answer = ($x = 1);
// Check if $answer is true or false
if($answer) {
echo "True!";
} else {
echo "False!";
}
}
?>
For that you need to have a form which can submit values to calculation script or same page if script is in same page.
Also in your script you are not comparing anything as the condition is always true as answer is always 1 and condition is always satisfied, so for that you can compare the user input to answer as I did in example.
For example calc.php
<?php
echo"<form method="POST" action="">Your answer:<input type="text" name="val" /><br><input type="submit" /></form>";
#$val=$_POST['val'];
if($val){
$answer = 1;
if($answer==$val) {
echo "The answer is: True";
}
else {
echo "The answer is: False";
}
}
?>
In PHP '=' means assignment operator.
Equal check operator should be '=='.
So, your code should be refactored as:
<?php
$x = 1;
$answer = ($x == 1); // this will return true or false
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
?>
You can also use ternary operator to shorten your code instead of if/else statement like this:
<?php
$x = 1;
$answer = ($x == 1); // this will return true or false
echo $answer ? 'The answer is: true' : 'The answer is: false';
?>
you need to create form to get input from html. there is many different approaches to create form.
I think your are begginer, so simply you can create form on the same page.
you can separate php code from html form write your php code on the top of the page like example below
<?php
if(isset($_POST['submit'])){
$x = $_POST['myinput'];
$answer = $x;
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
}
?>
<form method="POST" action="">
<input type="Text" name="myinput" >
<inpu type="submit" name="submit" value="submit button">
</form>
action="" is used for same page. if you want to use separate page for html part you can give action="yourPHPPage.php"
Did u mean this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
$answer = $_POST['input'];
if($answer == 1) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
}
?>
<form action="" method="post">
Enter value: <input name="input" type="text" />
<input name="submit" type="submit" />
</form>
</body>
</html>
As the purpose is to check if a mathematic function's value is True or False, I propose a simple CLI script.
<?php
print ((isset($argv[2]) && ($argv[2] === 1)) ? "\nAnswer is True\n\n" : "\nAnswer is false\n\n");
Save this as myfile.php
Open command line navigate to the folder and type in
>php myfile.php 1 // Returns Answer is True
So if you want to change the input you can do that also..
>php myFile.php 4 // Answer is False
Note that if you're passing String "1", this would also return True.
I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}
This may be a simple question for some of you but i've been investigating it for the last hour and couldn't find the answer. I have a simple login form/script that has the following structure;
<?php
PHP code here to check for token (if true) and then check the db for username and password
if the token is false display error message
?>
<HTML>
HTML logon form here that sets the token
</HTML>
Now if there is an issue with the logon, i.e the password is incorrect the php will output the error message, trouble is that it will echo the output at the top of the form. I'd like to be able to insert it at another point of the form. i have a vague idea that i could inject it into the html with something like {logon_error} but i don't know what method thats called or how to use it.
You can store the error message in a php variable , for e.g. $error_msg = "Error! ... ";
And display that wherever you want in the html page like this:
<html>
...
<body>
...
<span><?= $error_msg; ?>
</body>
</html>
Store the error message in a variable, and use it afterwards.
Here's a working example to help you understand:
<?php
if (isset($_POST['FormSubmit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === 'admin' && $password === 'hunter2') {
# success
} else {
$error = 'Invalid credentials';
}
}
?>
<html>
<div id="errorContainer">
<?php echo (isset($error)) ? $error : ''; ?>
</div>
<form action="" method="post">
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" name="FormSubmit" value="Submit!" />
</form>
</html>
If you have multiple checks, and want different error messages to be output, then you could store the error messages in an array instead. Your validation code should look like:
if (condition) {
$error[] = '...'
}
elseif (condition) {
$error[] = '...'
}
else (condition) {
$error[] = '...'
}
And then, to output it in your HTML, you can use a foreach construct with the alternate syntax:
<div id="errorContainer">
<?php foreach($errors as $error): ?>
<p class="error-content">
<?php echo $error; ?>
</p>
<?php endforeach; ?>
</div>
Note that this is a very basic example and is just for demonstration purposes. You should never trust user input. Your original form should contain all the necessary validation and should not be just a couple of if statements.
You would have to store the message in the session or take a look at https://github.com/plasticbrain/PHP-Flash-Messages
the main idea is $error_mesage = 'your error mesage here';
loadView('your-view')->with($error_message);
It's really simple, if you give more information about what kind of framework you are working with we may be able to assist you further.
You can do like this:
PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{$userErr = "Username is required";}
}
HTML:
<span class="error">* <?php echo $userErr;?></span>
You can do whatever you like using <?php echo ""; ?> in php to call it on your html.
I wanted to create a registration validation system (to make sure that the user registered has valid info) with PHP and Javascript Alert Boxes. Each time a user does not do a field correctly, I want him to get an alert box saying that it is incorrect. So here it is:
Code #1 - For generating alerts in PHP (This is for the event in the button).
function alert($string)
{
echo "javascript:alert('$string');";
}
Code #2 - PHP placed inside the onclick="" attribute for the submit button.
if (!isset($fname) || empty($fname))
{
alert('Please enter your first name!');
}
elseif (!isset($lname) || empty($lname))
{
alert('Please enter your last name!');
}
elseif (!isset($gender) || empty($gender))
{
alert('Please specify your gender!');
}
elseif (!isset($phone) || empty($phone) || strlen($phone) != 10)
{
alert('Please enter your correct Phone Number!');
}
elseif (!isset($user) || empty($user) || strlen($user) > 10 || strlen($user) < 5)
{
alert('Please enter a Username that is 5-10 characters long!');
}
elseif (!isset($pass) || empty($pass) || strlen($pass) > 10 || strlen($pass) < 5)
{
alert('Please enter a Password that is 5-10 characters long!');
}
elseif (!isset($repass) || empty($repass) || $pass != $repass)
{
alert('Please repeat your Password');
}
else
{
$query = mysql_query($query_send_form);
query_error($query);
}
As you have probably realised, the variables are actually equal to the $_POST values of the field in the form.
So the problem is that the onclick of the button is ALWAYS equal to onclick="
javascript:alert('Please enter your first name!');" It wouldn't change.
Please don't give me a complete javascript alternative to the system, I want to learn PHP for now.
Thanks for your help in advance.
EDIT #1
An important thing I forgot to mention was that the form target is just an iframe on the same page, so that the content the user has entered stays while he is being shown the error.
<form method="post" target="frame" action="register.php">
register.php is the same page where the form HTML and the validation PHP is.
EDIT #2
The data is being posted. Here are the declared varibles:
#$fname = $_POST['fname'];
#$lname = $_POST['lname'];
#$gender = $_POST['gender'];
#$phone = $_POST['phone'];
#$user = $_POST['user'];
#$pass = $_POST['pass'];
#$repass = $_POST['repass'];
You really shouldn't do that kind of validation like that...
Anytime you want to tell the user something is invalid because of logic rules, it is done with javascript on the front side. There are some good plugins out there written in either jquery or javascript out here. You can also make something simple on your own. This helps the user because then they don't have to submit the page to find out that their password isn't long enough.
You still need to do validation after POST and before putting things in the database because of sql injection. That kind of validation is a little different because you're just looking for things that are harmful.
This example is self-contained. The messages go to a div instead of alerts.
<?php
$message = "";
$submit = (isset($_POST['submit'])) ? $_POST['submit'] : '';
if (!empty($submit)) {
$message = "thanks for submitting the form!";
}
?><div id="errors"><?php echo $message ?></div>
<form id="my_form" name="my_form" action="" method="post">
<div style="display:inline-block;">Name<br/>
<input name="first_name" type="text" size=8 class="required"/>
<input name="last_name" type="text" size=16 class="required"/>
</div>
<div style="display:inline-block;">Gender<br/>
<select name="gender" class="required">
<option value=''></option>
<option value='M'>M</option>
<option value='F'>F</option>
</select>
</div>
<div style="display:inline-block;">Phone Number<br/><input name="phone" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Username<br/><input name="username" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Password<br/><input name="password" type="password" class="required"/></div>
<div style="display:inline-block;">Repeat Password<br/><input name="repeat_password" type="password" class="required"/></div><br/>
<div style="display:inline-block;">Description<br/><textarea name="description"></textarea></div><br/>
<button type="submit">Submit</button>
<input type="hidden" name="submit" value="submit"/>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style> .invalid {border-color:red}</style>
<script>
$(document).ready(function(){
$("#my_form").submit(function(e){
var messages = perform_validation();
if (messages.length!==0) {
$("#errors").empty();
$.each(messages,function(i,msg){
$("#errors").append(msg+"<br/>");
});
e.preventDefault();
return false;
}
// else continue to submit form normally
});
function perform_validation()
{
var messages = [];
$("#my_form :input.required").removeClass("invalid");
$("#my_form :input.required").each(function(){
if ($(this).val().length===0) {
$(this).addClass("invalid");
var name = $(this).attr('name').replace('_',' ');
messages.push("Please provide a "+name+".");
}
});
var password = $("input[name='password']").val();
if (!(password.length>=5 && password.length<=10)) {
messages.push("Password length must be between 5 and 10 characters.");
}
else {
if (password!=$("input[name='repeat_password']").val()) {
messages.push("Repeat password doesn't match first password.");
}
}
return messages;
}
});
</script>
Unless you have magic quotes turned on (and I hope you don't), your values such as $fname will always be undefined. You probably want to replace those with $_POST['fname'].
On a side note, you can use just empty() without !isset() since empty() will return FALSE if the value is not set.
I am trying to create a php log in form. I want to just make a few adjustments but when i've tinkered with it, it stops working...
If you can't see from the code, I'm trying to create a (mock) log in form that asks for a username and password.
I want any blank textbox to show a red message to the right of the textbox. (i have the red error message, but I can't get it to the left of the box)
I want a sticky form that keeps either field if its filled in (again, I think I have this set up but don't think its working all the way)
I would like a person who enters the username: user and the password: abc123 to see a welcome message. If you don't use that username/password combo I want a message that says that they are not authorized. (This is what i really don't know how to do)
I want this all in a redux (also think i have that working but not 100% sure)
Any help would be greatly apprecaited!!
And here is my code:
<?php
define('TITLE', 'LOG IN');
// CSS
print '<style type="text/css" media="screen">
.error { color: red; }
</style>';
// Checking
if ( isset($_POST['submitted']) ) {
$problem = FALSE;
// Each value
if (empty($_POST['email'])) {
$problem = TRUE;
print '<p class="error">Please enter the username!</p>';
}
if (empty($_POST['password1'])) {
$problem = TRUE;
print '<p class="error">Please enter the password!</p>';
}
if (!$problem) { //No problem
// Printing the log in message
print '<p>Thank you for logging in!</p>';
$_POST = array();
} else {
print '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
<p>"Username": <input type="text" name="username" size="20" value="<?php if (isset($_POST['username'])) { print htmlspecialchars($_POST['username']); } ?>" /></p>
<p>Password: <input type="password" name="password1" size="20" /></p>
<p><input type="submit" name="submit" value="Log in" /></p>
<input type="hidden" name="submitted" value="true" />
</form>
Ok, here is a simple login that is not meant for real world usage. Please read the comments included in the code to see what I have to say about each. Doing logins is quite tricky for a number of reasons, so this example is not meant to demonstrate a real world working codebase, but a very simple username/password check.
The security issues associated with a more sophisticated use are perhaps beyond this answer, but the below code is the way I would interpret what you have posted above, without getting to detailed (to the point of possibly making it hard to understand the simplest steps occurring).
Let me know if you have any questions. To see the form in action, check:
http://jfcoder.com/test/simplelogin.php
Also, I use PHP's HEREDOC syntax instead of quoted strings for simplicity. To read more about this sometimes handy form, see
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc.
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<?php
// Note, in most cases you will set a SESSION variable
// of $_SESSION['loggedin'], which would require you to
// use session_start() before you access any session
// variables.
// Note, this defaults to false.
$loggedin = false;
// If I get an error, I will put it in this variable.
$error = '';
// If the username is provided, run the code. Otherwise,
// act as if the login form was not submitted. This makes
// a hidden `submitted` value superfluous, and guarantees
// your users at least provide a username.
if ($_POST['username']) {
// NOTE!!! In mose cases, you're querying a database
// for a username/password match. In PHP, this often
// means a MySQL query. DO NOT USE THE BELOW IF YOU
// ARE DOING SO!!! This will allow what's called a
// SQL injection. You MUST wash your data with something
// like mysql_real_escape_string() for the $_POST
// values (NEVER trust submitted data, always validate
// and escape as necessary), or use the PHP PDO library.
// In this example, though, I use a switch to check the
// values for exact matches, which means I do not need
// to escape (and mysql_real_escape_string() requires
// a database connection to use).
$username = $_POST['username'];
$password = $_POST['password'];
// Here, I check if the username and password match.
// This is, of course, hardcoded, but to match your
// attempt, I chose to keep the form, although you
// rarely see this in use in the real world.
switch ($username) {
// My one case. For each additional user, you
// would need to add a new entry with password
// check. And I set my error text according to
// the result of the code.
case 'user':
if ($password === 'abc123') {
$loggedin = true;
} else {
$error = 'Username/Password did not match.';
}
break;
default:
// Note, I don't give a descriptive error
// here. If someone reports this error, I
// know what may have gone wrong, but the
// user is not told the username does not
// exist.
$error = 'Unknown error. Try again.';
}
}
// I will only show the welcome message if the user has
// successfully logged in.
if ($loggedin === true) {
echo <<<HTML
<h1>Welcome!</h1>
<p>Thank you for logging in $username</p>
HTML;
} else {
// If an error text is set, display that error.
if ($error != '') {
$error = "<h4>Login error</h4><p class='error'>$error</p>";
}
// Here's my form, only shown if the user has not
// successfully logged in (note, this is only a one-
// time check when the POST data is submitted; I
// would need to use sessions to "remember" the requestor
// had logged in across page accesses.
echo <<<FORM
<h1>Login Form</h1>
<form action="simplelogin.php" method="POST">
$error
<p><label>Username: <input type="text" name="username"/></label></p>
<p><label>Password: <input type="password" name="password"/></label></p>
<p><input type="submit" value="Login"/> <input type="reset"/></p>
</form>
FORM;
}
?>
</body>
</html>
Here's my full code. I pretty much rewrote the whole thing, so I appologize if the coding style differs too much:
<?php
// Output our CSS code
echo '<style type="text/css" media="screen">
.error
{
color: red;
}
</style>';
// Define our variable
$problem = false;
// Check if the form has been submitted
if (isset($_POST['submitted']))
{
// If either user or password are empty, we have a problem
if (empty($_POST['username']) || empty($_POST['password']))
{
$problem = TRUE;
}
// If there is no problem, username is user, and password is abc123, we're good
if (!$problem && $_POST['username']=='user' && $_POST['password']=='abc123') {
// Print our login message
echo 'Thank you for logging in!<br />';
}
// Ok, there's either a problem or the username or password is wrong, so no entry for them
else
{
echo '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
Username: <input type="text" name="username" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['username']))
{
echo $_POST['username'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['username']))
{
echo '<span class="error">Please enter a username!</span>';
}
?>
<br />Password: <input type="password" name="password" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['password']))
{
echo $_POST['password'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['password']))
{
echo '<span class="error">Please enter the password!</span>';
}
?>
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>