I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.
Related
I am creating a Guestbook in PHP, each IP will only be able to post once.
Except for that it will require name and message before sending, and also CAPTCH validation. Somehow my code does ignore the Captcha validation as long as something is written in the input, regardless of what.
I have tried to save the captch in session, and validate the input for the captcha but it doesnt help.
Code to generate the captcha:
function generateCaptchaString($length = 5) {
$captchaString = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
$_SESSION["captchaString"] = $captchaString;
return $captchaString;
}
Code to input name, message and captcha:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"
id="guestform">
<fieldset>
<legend>Skriv i gästboken</legend>
<label>Från: </label>
<input type="text" placeholder="Skriv ditt namn"
name="name">
<br>
<label for="text">Inlägg</label>
<textarea id="text" name="message"
rows="10" cols="50"
placeholder="Skriva meddelande här"></textarea>
<br>
<label>Captcha: <span class="red" id="captchastring"><?php
echo generateCaptchaString(); ?></span></label>
<input type="text" placeholder="Skriva captcha här"
name="captcha" id="captchainput" required>
<button type="submit" id="submit">Skicka</button>
</fieldset>
</form>
Code in the POST-function that will check for validation.
if( ! isset($_POST['captcha']) || empty($_POST['captcha']) ||
$_POST['captcha'] != $_SESSION['captcha']) {
$error .= "<p class=\"message-error\">" . $messages['math_invalid'] . "
</p>";
}
In your generateCaptchaString() function, you store the captcha string in $_SESSION["captchaString"].
But in the POST-validation code, you read it as: $_SESSION['captcha']
Change that into $_SESSION["captchaString"] as well.
Also, are you sure the URL to go to when submitting the form is $_SERVER['PHP_SELF'] (which may be another .php script that includes or requires this one) rather than $_SERVER['REQUEST_URI'] which is the same URL you're currently visiting.
Also, if the POST check code is in (or included by) the same file that also contains or includes the form, is it possible that generateCaptchaString() gets called again (to create the form again) thus overwriting any previous captchaString stored there?
It doesn't exactly have to be a div, it can be anything, a article section a ...
I'm making a website for a university project, the website is similar to DropBox (file hosting website). NON COMMERCIAL!
I'm on the registration page at the moment and what I want to do is after the user presses the submit button I want to change the content of a div tag which is next to the field which is wrongly entered.
For example, if the user types in a password that is less than 3 characters long an "X" will appear in the div tag next to the password field and under the submit button a message will appear saying "Password must be more than 3 characters."
This is part of the code, not posting all of it because it's too long.
<form action="register.php" method="post" >
<section>
<article>Password*</article>
<input type="text" name="password" id="password" required="required"/>
<div id="right_or_wrong"></div> <!-- tick - ✓ , wrong - X -->
</section>
<input type="submit" name="register" value="Register" />
<div id="error_msg"></div>
</form>
I have tried to search on how to do this but I can't find anything and I just can't figure it out.
I know I can put the PHP code in the div tag and assess it from there but I want to put the code at the bottom of the form to make it neater.
So in register.php when you validated the form and see that the password was too short, you can set a variable like $password_error = "Password must be more than 3 characters.".
Then you can just re-render the form and
<div id="right_or_wrong"><?php echo $password_error; ?></div>
You can validate before sending the form to the server, with simple onsubmit function:
<script>
function validate(){
// here, check the password and other answers
if( /* check password here */ ){
document.getElementById("right_or_wrong_password").innerHTML="X";
document.getElementById("error_msg").innerHTML="Password must be more than 3 characters.";
return false; // prevent from submitting form
}else if( /* check field1 here */ ){
document.getElementById("right_or_wrong_field1").innerHTML="X";
document.getElementById("error_msg").innerHTML="Error in the field......";
return false; // prevent from submitting form
}else{
return true; // the form can be submitted
}
}
</script>
<form action="register.php" method="post" >
<section>
<article>Password*</article>
<input type="password" name="password" id="password" required="required"/>
<div id="right_or_wrong_password"></div> <!-- tick - ✓ , wrong - X -->
</section>
<input type="submit" name="register" value="Register" onsubmit="validate()" />
<div id="error_msg"></div>
</form>
In this way, you can verify each field of the form (answers structure only). Then a server validation is always necessary.
PHP can't do that alone. PHP is server-scripting - it can't run on user's machine and handle live events.
Instead, use Javascript's AJAX and call a php file which would return the text. And, then use Javascript to append that text to div or whatever you want.
I am trying to send a email using forms and PHP. When I click on the send button I get t the error Error occurred: 404 - not found. submit.php file is in same dir as the webpage. Why can't it find the submit.php. My html code.
<form action="submit.php" id="form1" method="post">
<fieldset>
<label class="input">Date:<span><span><input type="text" id="datepicker" value=""/></span></span></label>
<label class="input">Enter Your Name:<span><span><input name="name"/></span></span></label>
<label class="input">Enter Your Email:<span><span><input name="email"/></span></span></label>
<label class="input">Subject:<span><span><input name="subject"/></span></span></label>
<label class="text">Enter Your Message:<span><span><textarea name="comment" cols="0" rows="0"></textarea></span></span></label>
<label class="input">Enter Code:<img src="php/captcha.php"><span><span><input type="text" name="vercode" /></span></span></label>
<label class="butt"><strong><b>clear</b></strong>
<strong><b>send</b></strong></label>
</fieldset>
When using <a>'s to use as form submit buttons, I would suggest using a JavaScript function and put it in the onclick of the anchor. Like this:
function doSubmit(form_name) {
// check if the object exists
if (document.getElementById(form_name)) {
// submit the form
document.getElementById(form_name).submit();
}
// prevent the link from clicking
return false;
}
<strong><b>send</b></strong>
The same can be done for the reset button.
In this way, you never navigate your browser to a "javascript:...etc.." location (that does not exist). I'm not sure if this is the case here, but just as a best practice advise then. :)
I'm trying to create a page with a form using ci.
When i submit the form, the controller says that I have no data that's been submitted.
I can't see where my error lies.
Here's the view:
<?php echo validation_errors(); ?>
<?php echo form_open('widgets/search/'.$hardwaremodel.'/'.$objectid.'/'.$name.'/'.$fd); ?>
<div class="form-group">
<label for="search">Last 4 characters of address:</label>
<input type="text" class="form-control" id="searchstring" placeholder="last 4 characters" size="4">
</div>
<button type="submit" class="btn btn-default">Search</button>
<button type="cancel" class="btn btn-default">Cancel</button>
</form>
Once the page renders, the form tag ends up looking like this:
<form action="http://myserver/myciapp/index.php/widgets/search/205406zl/5461/SW-1/SW1net" method="post" accept-charset="utf-8">
The controller:
public function search()
{
$searchstring = $this->input->post(); // form data
var_dump($searchstring);
exit;
}
The results of the var_dump shows:
bool(false)
Thanks
EDIT 1
I haven't posted the entire HTML page that includes the form... but I display some of the fields passed in the URI as headings on the page - just before I create the form. Hope that clarifies...
Would this impact the POST data? Why is that relevant?
Thanks
A few things I'd suggest doing. First is, if you are going to include other variables in the form_open tag, I would add those variables to your controller, and put them in the form_open tag as URI strings. This will allow the form validation to work if you are going to echo out validation errors.
Also, you should be calling a name on the input->post() to get the specific item, (but you don't need to to get all POST data).
Controller:
public function search($hardwaremodel, $objectid, $name, $fd) {
$searchstring = $this->input->post('search_string'); // form data
var_dump($searchstring);
exit;
}
View:
<?php echo form_open('widgets/search/'.$this->uri->segment(3).'/'.$this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6)); ?>
<div class="form-group">
<label for="search">Last 4 characters of address:</label>
<input type="text" class="form-control" id="search string" name="search_string" placeholder="last 4 characters" size="4">
</div>
Form elements are referenced by name attribute which is missiong on input field searchstring.
Add:
name="searchstring"
on your input field.
in this code you have not used name attribute.You use id.
try this one
<input type="text" name="searchstring" value="xyz">
I am new to web designing. Now, I have created a form, and if the user input doesn't meet the requirements I display error message, and if it does I do some mysql commands to enter the info to the database. Now one way to do this is to code the php file into the html and use this command,<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> like described [here][1]
But I don't want to put the script in the same file. How do I do that in another php file such that if user input is invalid, it will return to the homepage with the error message updated?
Here is my code
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<h1>Register as A new user</h1>
<div id="signup">
<form id="registration_form" action="registration.php" method="post">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
<span class="errorMessage"></span>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
</div>
What should be in the registration.php? Like the link, I do everything, I set a flag to the error, Now if the flag is true I return the user to the homepage with the error messages, and if false, I show a message saying registration successful. How do I do the part,"return to homepage with the appended error message"?
All your validation and bulletproofing should be in the registration.php
stuff like this:
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['name'])) {
die('Must pass \'name\');
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['email'])) {
die('Must pass \'email\');
}
if(!isset($_GET['passwd'])) {
die('Must pass \'password\');
} else {
//do cool stuff here
}
Don't forget your JS validation as well for the front end. I really hope this helps and gives you a bit of direction.
put your validation codes in "validate.php" or any file name you like
then change the action to validate.php to
then in validate.php if validation matches the requirements.
header("Location: registration.php");
if not match
header("Location: back to the httml with form.php");
You can learn form validation here : http://allitstuff.com/registration-form-in-php-with-validation/