I has read all the various post on StackOverflow regards this same but that was not helpful ...
Php script not shows error alert when text box empty or in invalid pattern. I know only empty script which I mention below but I don't known How I add pattern error also.
Also when textbox empty it not show error why? Please help. Please don't mark as it is duplicate because I read various post but same issue that is why I posted a threads. Please help in full script.
Advance thank you..
<?php
if(isset($_POST['submit']))
{
$name= $_POST['name'];
if (!($name))
{
$m1 = "<Div class="alert">Enter your Name</Div>" ;
}
$email= $_POST['email'];
if (!($email))
{
$m2 = "<Div class="alert">Enter Your Email"</Div> ;
}
$_SESSION['name'] =$name;
$_SESSION['email'] =$email;
$_SESSION['otp']=$rndno;
header( "Location: next-page.php" );
}
?>
In HTML Body
<div>
<?php if(isset($m1)) { echo $m1; } ?>
<?php if(isset($m2)) { echo $m2; } ?>
</div>
Try This code it is runnable
<?php
if(isset($_POST['submit']))
{
$name= $_POST['name'];
if ( $name == '')
{
echo $m1 = "<script type='text/javascript'>alert('Please Enter Your Name');</script>" ;
}
$email= $_POST['email'];
elseif ( $email == '')
{
echo $m2 = "<script type='text/javascript'>alert('Enter Your E-mail');</script>" ;
}
$_SESSION['name'] =$name;
$_SESSION['email'] =$email;
$_SESSION['otp']=$rndno;
else{
header( "Location: next-page.php" );
}
}
?>
Related
I have 3 pages:
Register.php
Success.php
Login.php
Now when my user register the it's values validate on success.php and if not correct it returned on register page and if it get correct then it gone to login page. I want when it comes back to register page when values not correct then values which was filled before submit should remain as it.
You can do this by just returning the values the user sent in. Using $_GET
http://php.net/manual/en/reserved.variables.get.php
https://www.w3schools.com/php/php_forms.asp
Just take the paramaters the users sent in and pass them back in the url.
Like if failed, return to url:
register.php?uname=value1&email=value2
Then in register.php get the paramaters with
$username = $_GET['uname'];
Then echo it out in the form again as value:
<input id="uname" value="<?php if(isset($_GET['uname']){
echo $username;
}
else{echo "enter username";} ?>" />
Very simple example here, but just follow w3school and you should have everything you need to get this done.
As you are using PHP, so best option is to use SESSIONS.
You can create something like:
$name = $_SESSION['name'];
$email = $_SESSION['email'];
Than these values can be used in the 3 pages for processing.
Your first page is register.php, so in the beginning of page just add a php function session_destroy(); so that when user open page any live session will be destroyed and new session will be started with that specific user. Also don't forget to start sessions by using function session_start(); on every page. I hope this will solve your requirement.
Take a look at JavaScript's localStorage. (or sessionStorage)
With that you will be able to store information between pages. Then just pass all the information at the same time as POST data on the last page.
Example:
var existing = localStorage.getItem('user_name');
if (existing == null) {
// The user has not set their name, lets assume it's John Doe
existing = 'John Doe';
localStorage.setItem('user_name', existing);
}
alert('Hello ' + existing + '!');
Alternatively, on the pure PHP side of things, you could also use PHP sessions. This way all the information stays on the server instead of in the user's browser.
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
The easiest method, IMO, using PHP would be to use a session variable which holds the values of all POSTed data from register.php
A simple function can be called to retrieve the value from the session variable and consequently displayed in the HTML form fields. This is an example of how you could achieve the desired result.
<?php
/* success.php */
session_start();
function getvalue( $var='register', $field=false ){
if( isset( $_SESSION[ $var ] ) ){
return array_key_exists( $field, $_SESSION[ $var ] ) ? $_SESSION[ $var ][ $field ] : '';
}
return '';
}
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
a boolean to indicate if everything is OK with the submitted
data - to be updated later according to your rules
*/
$ok=false;
/* set the session variable */
$_SESSION['register']=$_POST;
/* process POST data - set value of $ok to true if everything is OK! */
/*
this is where you determine the rules for success or failure
*/
/* Determine where the use goes next */
if( $ok ){
exit( header('Location: login.php') );
} else {
exit( header('Location: register.php') );
}
}
?>
<?php
/* register.php */
session_start();
?>
<html>
<head>
<title>register.php</title>
</head>
<body>
<!--
the form fields should initially be blank, but if the user is redirected
back to the page the fields should show the values stored in the
session variable.
-->
<form name='register' method='post' action='success.php'>
<!-- various form fields - example -->
<input type='text' name='email' value='<?php echo getvalue('register','email'); ?>' />
<input type='text' name='username' value='<?php echo getvalue('register','username'); ?>' />
<!-- more fields -->
<input type='submit' />
</form>
</body>
</html>
<?php
session_start();
$_SESSION['namefeild_name'] = $_POST['namefeild_name'];
$_SESSION['mob'] = $_POST['mob'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['city'] = $_POST['city'];
if(isset($_POST['reg']))
{
$con=mysql_connect("localhost","root","");
if(!$con) { die('Could Not Connect: '.mysql_error()); }
mysql_select_db("database", $con);
if(!isset($_POST['namefeild_name']) ||
!isset($_POST['mob']) ||
!isset($_POST['pass']) ||
!isset($_POST['pas']) ||
!isset($_POST['email']) ||
!isset($_POST['city']))
{
die("<script type='text/javascript'>alert('We are sorry, but there appears to be a problem with the form you submitted.')</script>");
}
$uid = $_POST['namefeild_name']; // required
$name = $_POST['namefeild_name']; // required
$uname=$_POST['mob']; //required
$pass=$_POST['pass']; //required
$pas=$_POST['pas']; //required
$email = $_POST['email']; // required
$city = $_POST['city']; // not required
$type = 'BAL'; // not required
$id=md5($uname);
$error_message = "";
$string_exp = "/\b([A-Za-z]{1,30}[- ]{0,1}|[A-Za-z]{1,30}[- \']{1}
[A-Za-z]{1,30}[- ]{0,1}|[A-Za-z]{1,2}[ -\']{1}[A-Za-z]{1,30}){2,5}/";
if(!preg_match($string_exp,$name)) {
$error_message .= "<script type='text/javascript'>alert('Name does not appear to be valid.')</script>";
header('location:register.php?errorname');
}
$string_exp = "/^[7-9][0-9]{9}$/";
if(!preg_match($string_exp,$uname)) {
$error_message .= "<script type='text/javascript'>alert('Mobile Number does not appear to be valid.')</script>";
header('location:register.php?errormob');
}
$string_exp = "/\b([A-Za-z]{1,30}[- ]{0,1}){1}/";
if(!preg_match($string_exp,$pas)) {
$error_message .= "<script type='text/javascript'>alert('The password you entered does not appear to be valid.<br />Contain Atleast one Uppercase Letter<br />Contain atleast one lower case letter<br />contain atleast one number')</script>";
header('location:register.php?errorpass');
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$city)) {
$error_message .= "<script type='text/javascript'>alert('City does not appear to be valid.')</script>";
header('location:register.php?errorcity');
}
if(strlen($city) < 2) {
$error_message .= "<script type='text/javascript'>alert('City does not appear to be valid.')</script>";
header('location:register.php?errorcity');
}
if(strlen($error_message) > 0) {
die($error_message);
}
else
{
$query=mysql_query("select * from customer where uname='".$uname."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
header("location: register.php?useralreadyexits");
session_destroy();
}
elseif(!$res)
{
$datetime=Date("Y/m/d H:i:s");
$result=mysql_query("INSERT INTO customer VALUES('$id','$uname','$name','$pas','$email','$city','$datetime');");
$result2=mysql_query("INSERT INTO payment VALUES('$id','$uname','25','$datetime','$type');");
if($result && $result2)
{
header("location: login.php?success");
session_destroy();
}
else
{
$_SESSION['name']=$uname;
header('location:register.php?notregistered');
}
}
}
mysql_close($con);
}
?>
The title may seem a bit confusing, but let me just tell you what I am trying to do. So I have a registration form in register.php. The form data is processed by my register.class.php file on a keyup by the user, and any errors in the submitted data are then returned and put into a "#return" div (in register.php).
The "#return_error" is echoing just fine, I'm having no problems echoing that, but for some reason, even if there are no errors, the "#return_success" won't echo.
I'm fairly new to jQuery, so please forgive me.
Here are the files:
register.class.php
//this is just an excerpt from the file, the rest of the code in the file was just validation.
$register = new Register();
$username = $_POST['username'];
$email1 = $_POST['email'];
$email2 = $_POST['reemail'];
$pass1 = $_POST['pass'];
$pass2 = $_POST['repass'];
$register->Username($username, $mysqli);
$register->Email($email1, $email2, $mysqli);
$register->Password($pass1, $pass2);
// no errors are found
if ($register->getStatus() === true) {
echo "<div id=\"return_success\">";
echo "<ul>";
echo "<li><b>Everything is valid</b></li>";
echo "</ul>";
echo "</div>";
} else {
//errors found
echo "<div id=\"return_error\">";
echo "<ul>";
foreach ($register->errors as $error) {
echo "<li><b>" . $error . "</b></li>";
}
echo "</ul>";
echo "</div>";
}
script.js
$(document).ready(function() {
$("#return").hide();
$("#register input").keyup(function() {
$.post("classes/register.class.php", $("#register").serialize(), function(data) {
$("#return").html(data);
$("#return").show();
if (data === '') {
$("#return").hide();
}
});
});
});
The form inputs aren't displaying on the form.php page and negates my form validation. The error says undefined variable for all my variables on form.php. Please tell me what I have to edit in my code to make it display the form inputs on form.php. It works when I use it on the same page but I would rather it display on another page.
EDIT
Thanks so far but I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A".
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>
If you would like to transfer the data from contact.php to form.php you should use something like this:
contact.php
$data = urlencode(
serialize(
array(
"name" => $name,
"email" => $email,
"subject" => $subject,
"message" => $message)
));
header('Location: form.php?data=' . $data);
form.php
$data = unserialize(urldecode($_GET['data']));
$name = $data["name"];
$email = $data["email"];
$subject = $data["subject"];
$message = $data["message"];
This serializes the array of data from contact.php then URL encodes it and sends it as a GET variable to form.php. After, form.php URL decodes and unserializes the data for use.
The problem is when you header("Location:") to form.php, all the POST values are lost. You have to either resend them with the header, or modify them into GET and retrieve them again. It should be more efficient to have them both (contact.php AND form.php) in one page. That way, the form data only has to be sent once.
You could probably just send the POST values as GET over to form.php like this.
contact.php:
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject."&message=".$message);
form.php (to retrieve the values):
$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];
$subject = $_GET['subject'];
If you want to display form elements then you have to use this approach.
<form method="POST" action="contact.php">
Email<input type="text" name="email">
.......
.......
.......
// All elements
</form>
This may help you.
Give action in your form in contact.php
<form action="form.php">
I've created a test form that uses IF.. ELSE to validate data in a simple form. This works ok and any validation messages or errors are posted to the same page (userform.php) to inform the user of success or otherwise.
What I want to do now is take the user to a different page on successful completion of the form. Here's my code so far:
<?php
if (isset($_POST['email'], $_POST['password'])) {
$errors = array ();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form";
}
if (empty($email)) {
$errors [] = "You must enter an email address";
}
if (empty($password)) {
$errors [] = "You must enter a password";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
}
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
$result = "userform.php";
}
} else {
$result = "confirm.php";
}
?>
<form action="<?php echo $result ?>" method="post">
The idea is that the users success or otherwise in completing the form changes the $result variable which is used in the form action. The above code doesn't work, so how would I do it?
Is it even possible?
instead of "form action=" at the bottom:
<?php
include($result);
?>
As I understand it you want it to work like so:
User fills form
User submits form
Form submission goes to userform.php
If all values validate, continue to confirm.php
If not, return to userform.php
If that's the case, I don't think you want to change the form action: that would require that the user re-submit the form. Instead, use a HTTP redirect to send them to confirm.php:
header("Location: confirm.php");
... or if you wanna be really by-the-book about it:
header("Status: 303 See Other");
header("Location: http://exampel.com/confirm.php"); // according to the protocol,
// `Location` headers should be full URLs
<?php
/* ... */
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
}
?>
<form action="userform.php" method="post">
<?php
} else {
header("Location: confirm.php");
// if you need to pass additional information to confirm.php, use a query string:
// header("Location: confirm.php?var1=".$var1);
}
?>
The way you're doing it now, will redirect the user to confirm.php if they submit the form for a second time. You could change your code to this:
} else {
// $result = "confirm.php";
header("Location: confirm.php");
exit();
}
That way, if everything has been entered, the user will be redirected to confirm.php. But what do you do with the variables if everything is allright? They won't be taken to the new page.
} else {
$result = confirm.php;
foreach($_POST as $key => $val){
$input.="<input type='hidden' name='$key' value='$val' />";
}
$form = "<form method='post' name='confirm' action='confirm.php'>".$input."</form>";
$script = "<script type='text/javascript'>document.confirm.submit();</script>";
echo $form.$script;
}
empty ($errors)
will ALWAYS return empty. That's why you always get:
$result = 'confirm.php';
Check return values here
Also, I don't think you can do this easily. Instead, why don't you just create a check.php or whatever to check the variables/check for errors, etc. Then do whatever you want (redirect back to the form-filling page or proceeding to confirm.php page.
The whole idea is wrong. You have to fix 2 issues in your code.
1. A major one. Learn to properly indent nested code blocks!
It's impossible to read such an ugly mass with no indents.
2. A minor one.
I see no use of confirmation page here. What are you gonna do on that page? And from where you're going to get form values?
It seems you have to either use just simple Javascript code to show a confirmation or store entered data into session
And, I have to say, that show a confirmation page for simply a feedback form is quite uncommon practice.
So, I think you really need only one form action and only thing to ccare is properly filled form
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$errors = array();
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form. All fields required.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
if (!$errors) {
// do whatever you wish to this data
// and then redirect to whatever address again
// the current one is a default
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['fiestname'] = $form['lasttname'] = $form['email'] = $form['password'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($errors): ?>
<? foreach($errors as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form method="POST">
<input type="text" name="firstname" value=<?=$form['firstname']>
... and so on
I have a form with several input fields, i would like to go through and check to make sure they are all present before continuing.
This is the code i am using
if(isset($_POST['url'])){ $url = $_POST['url']; } else { echo "<error>no url</error></data></xml>"; exit(); }
if(isset($_POST['username'])){ $username = $_POST['username']; } else { echo "<error>no username</error></data></xml>"; exit(); }
if(isset($_POST['password'])){ $password = $_POST['password']; } else { echo "<error>no password</error></data></xml>"; exit(); }
if(isset($_POST['cachename'])){ $cachename = $_POST['cachename']; } else { echo "<error>no cachename</error></data></xml>"; exit(); }
if(isset($_POST['lat'])){ $lat = $_POST['lat']; } else { echo "<error>no lat</error></data></xml>"; exit(); }
if(isset($_POST['long'])){ $long = $_POST['long']; } else { echo "<error>no long</error></data></xml>"; exit(); }
if(isset($_POST['message'])){ $message = $_POST['message']; } else { echo "<error>no message</error></data></xml>"; exit(); }
if(isset($_POST['notes'])){ $notes = $_POST['notes']; } else { echo "<error>no notes</error></data></xml>"; exit(); }
if(isset($_POST['tags'])){ $tags = $_POST['tags']; } else { echo "<error>no tags</error></data></xml>"; exit(); }
The problem im getting, is even when i JUST enter a URL, it returns "no lat". Even when i fill in everything down to notes, it still returns "no lat"
Any ideas?
Check values in $_POST
echo "<pre>";
print_r($_POST);
echo "</pre>";
Make sure every post variable is set and the names match.
Not that this will fix your problem (see Ólafur's comment), but, here's a more automated way of performing validation on all of your fields:
$required = array('url', 'username', 'password', 'cachename',
'lat', 'long', 'message', 'notes', 'tags');
while (list($i, $require)=each($required)){
if(empty($_POST[$require])){
die('<error>no ' . $require . '</error></data></xml>');
}else{
$$require = $_POST[$require];
}
}
PS: empty() is often better better to use than isset(). An empty string will return true with the isset() function.