I have created a PHP page (see code below) that is supposed to validate the information entered into the webform prior to submitting it, to ensure that all fields have been completed. If any fields have been left blank, it is supposed to display an error message; if all fields have been filled in, it is supposed to send the data to a .csv file. The problem is that it is not validating the fields, nor is it sending the data to the .csv. I have tried deleting the .csv and then submitting the webform; it creates a .csv with commas separating the entries, but there are no entries (i.e. no text, only commas).
Does anybody know why this might be?
Any assistance would be appreciated.
Thanks in advance!
Here is the code:
<form action="form_mailer.php" method="post">
<table>
<tr><td>Which is your name?</td>
<td><input type="text" name="formName" maxlength="50" value="<?=$varName;?>"></td></tr>
<tr><td>What is your occupation?</td>
<td><input type="text" name="formOccupation" maxlength="50" value="<?=$varOccupation;?>"></td></tr>
</table>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
if(empty($_POST['formOccupation']))
{
$errorMessage .= "<li>You forgot to enter your occupation!</li>";
}
$varName = $_POST['formName'];
$varOccupation = $_POST['formOccupation'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if($errorMessage != "")
{
echo("<p>There was an error:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
else
{
$fs = fopen("data.csv","a");
fwrite($fs,$varName . ", " . $varOccupation . "\n");
fclose($fs);
}
?>
UPDATE:
Hi,
Many thanks for the responses.
I've realised where I have gone wrong now........I had the form action as 'form_mailer.php', which is not the form page itself but another page that performs further actions with the data provided on the webform.
I have now brought the 'form_mailer' coding into the webform .php and have changed the 'action' of the webform page so that it effectively submits to itself, but now I need to redirect to the form_mailer page following successful submission of the webform or display a thank you message........don't suppose anybody knows how I can do this? If you could provide instructions for how to do both that would be great as I can then choose the one I prefer that would be best for my needs.
Thanks again!
I have checked your code and it's working fine and also store data in csv file.
Probably you should make these vars global:
<?php
global $varName, $varOccupation
...
... probably in both <?php blocks.
Related
I'm sure it's simple but I can't see it :)
I'm trying to add a reCAPTCHA into the code for an existing site with a little contact form.
I have the keys from Google (censored in the examples of course) but I can't even get it to display the CAPTCHA, let alone anything test if the filtering is working.
I've added the reCAPTCHA code into the page:
index.html:
form name="f1" method="post" action="mail2.php" onsubmit="return verify();">
<p><label>Your Name <span>(*)</span></label><input type="text" name="name" /></p>
<p><label>Your Email</label><input type="text" name="email" /></p>
<p><label>Your Phone No: <span>(*)</span></label><input type="text" name="phone" /></p>
<p><label>Other messages</label><textarea name="messages" rows="" cols=""></textarea> </p>
<?php
require_once('recaptchalib.php');
$publickey = "6LdrxxxxxxxxxxxxxxJr"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<p style="padding-right:36px; float:right;"><input name="" type="image" src="images/submit_btn.png" /></p>
</form>
And in the mail2.php
<?php
require_once('recaptchalib.php');
$privatekey = "6LxxxxxxxxxxxxxxxxxxqZYiH";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
require_once 'mailer/class.phpmailer.php';
$mail = new PHPMailer();
----followed by the standard PHPMailer content----
The index page just displays as standard with no CAPTCHA section displayed, trying to send an email results in failure with some PHP code displayed.
I'd really appreciate if someone with a mind larger than mine who eats & breathes reCAPTCHA could cast their eye, laugh & point at where I've gone wrong. :)
Looking to be educated rather than just a fix. My skills lie in content rather than coding I'm afraid.
(And how do I insert a code block in the editor? Surely don't have to indent each line by 4 spaces individually?)
Many Thanks.
I can help because I have it working farther than you, but I need help on this subject too.
To begin, you need this line of code in your html header (before the </head> tag:
<script src="https://www.google.com/recaptcha/api.js?fallback=true" async defer></script>
Then in the body of your html, and somewhere inside of your form (between your <form> ... </form> tags) you need the following code:
<div class="g-recaptcha" data-sitekey="....your site key here...."></div>
Then in your PHP processing file (the file that your form posts to and receives the form variables you need the following code:
$response_string = $_POST['g-recaptcha-response'];
$secret_key = "...put in your secret key here...";
$resp = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret_key&response=$response_string");
if($resp != '{ "success": true }')
{ $problem = "failedreCAPTCHA";
header("Location: http://www.yourwebsite.com/...pagetohandlefailedentry...php?problem=$problem");
die('Sorry, you entered the wrong value in the Human CAPTCHA challenge. Please try again.');
}
This code works great except for the "if($resp != '{ "success": true }')" part of it. Because the variable $resp get filled with from google is "{ "success": true }" which turns out to be a JSON object and I don't know how to test for "true" with PHP and a JSON object.
So... someone, please help.
This appears to be working for me, using Google's new "no Captcha reCaptcha". This largely builds off of Brook's answer, but includes the ip, parses the json, and tests for success.
<?php
$gSecret = "...put in your secret key here...";
$gResponse = $_POST['g-recaptcha-response'];
$gRemoteIp = $_SERVER['REMOTE_ADDR'];
$gResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$gSecret&response=$gResponse&remoteip=$gRemoteIp");
$resp = json_decode($gResponse);
if (!$resp->success) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error-codes . ")");
} else {
// Your code here to handle a successful verification
}
?>
I'm aware that this question has been asked a huge number of times but the answers seem really specific to the script posted and with my current knowledge I can't make the transition from the corrected script to implementing it into my own.
This all works fine - it submits on the same page and provides feedback of any errors, but I want any errors to be echoed beneath the form making it more convenient for the user to just change what they entered incorrectly and re-submit.
From what I can gather from the questions I read before posting this - it may only be possible using jQuery/Ajax?
My script:
<?php
if(isset($_POST['submit'])){
require "connection.php";
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$repeat_password = $_POST["repeat_password"];
$username_query = mysql_query("SELECT id FROM users WHERE username = '$username'");
$email_query = mysql_query("SELECT id FROM users WHERE email = '$email'");
if($username == "" || $password == "" || $repeat_password == "" || $email == ""){
die("All boxes must be filled out!");
}// ^ Checking if all boxes have been filled out
else {
if (!ctype_alnum($username)){
die("Username can only contain letters and numbers");
}// ^ Checking if username is alphanumeric
else {
if (strlen($username) < 6 || strlen($username) > 15){
die("Username must be between 6-15 characters.");
}// ^ Checking if username is between 6-15 characters
else {
if (mysql_num_rows($username_query) != 0){
die("Username is taken, please choose another.");
}// ^ Checking if username exists in database
else {
if (!preg_match("/[0-9]/",$password)){
echo "password doesnt contain a number";
}
else {
if ($password != $repeat_password){
die("Passwords do not match");
}// ^ Checking if password and repeat_password match
else {
if (strlen($password) < 6){
die("Password must be atleast 6 characters long.");
}// ^ Checking if password is longer than 6 characters
else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
die("E-mail address is not vaild.");
}// ^ Checking if e-mail address is valid
else {
if (mysql_num_rows($email_query) != 0){
die("This e-mail address has already been used to create a different account.");
}// ^ Checking if e-mail address has already been used
else {
mysql_query("INSERT INTO users (username, password, email, signup_date) VALUES ('$username', '$password', '$email', CURDATE())") or die(mysql_error());
echo "Account succesfully created, welcome ".$username."!";
}
}
}
}
}
}
}
}
}
exit;
}
//
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>
Username:
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
Repeat password:
</td>
<td>
<input type="password" name="repeat_password">
</td>
</tr>
<tr>
<td>
E-mail:
</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td colspan="2">
<center><input type="submit" name="submit"></center>
</td>
</tr>
</table>
</form>
Answer: Yes, you have to use jQuery there.
You can validate form just after user entered 1st letter. You can validate on key up/down or on submit. I suggest to use jQuery Validation Plugin.
To sumbit form use ajax requests. It is rly simple. You can read about it here. There are some examples at the end page I had given.
Note, that if you will use jQuery Validation Plugin you can send ajax request on valid action. Using this, ajax request with serialized form will be sent on form submit + on form valid. If form has some invalid fields, errors will be shown, if there are no errors, ajax-request will be send.
Advice:
Your arhitecture not very good. Why? If people will write bad name and make 10 more other errors, only 1 error:
Username can only contain letters and numbers
will be shown. Why? Because of you arhitecture. After that he will correct 2nd erorr. 3rd error etc.
I suggest you do to handle errors this way:
$errors = array();
$errorsFlag = false;
if(check_username1()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
if(check_username2()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
if(check_mail()) {
$errors[] = 'Tell about this error';
$errorsFlag = true;
}
And how to output it? Use this:
if($errorsFlag == true) {
foreach($errors as $error) {
echo $error . " <br /> ";;
}
}
yes, you'll need javascript. but not necessarily jQuery or ajax.
but php without the use of ajax always needs you to reload the page cause otherwise the php-code will not be executed.
search for some kind of javascript/jQuery validation scripts if you don't want the page to be reloaded. otherwise (if you don't care about page-reloading), you can put out your error message at the end of the form with php as well.
I always set my errors as a session. This allows you to set multiple errors at once, and print them wherever you want.
The following if statements are just examples of where you would set the errors...
session_start(); //you will need this
if ( username_exists($un) ) {
handleError("Username already exists!");
}
...
if ( !passwordIsStrong($pw) ) {
handleError("Password is not strong enough!");
}
Here's the functions that actually set/print the errors.
function handleError( $err ) {
//get any existing errors
$existing = isset($_SESSION['form-errors']) ? $_SESSION['form-errors'] : '';
//append the new error to the existing ones. Over-write the session with new data.
$_SESSION['form-errors'] = "$existing<li>$err</li>";
}
function getErrors() {
if( isset($_SESSION['form-errors']) )
echo $_SESSION['form-errors'];
}
getErrors(); can be called anywhere in your html. It will print something like this...
<li>Username already exists!</li>
<li>Password is not strong enough!</li>
It's kind of like a log. But it's worked for me on all of my projects!
I am trying to wrap up this contact/quote form which has same page validation but external processing. I have set up a variable to go in the form action and the variable/url changes from the same page to the processing page when the form validates. However, it is taking two clicks on the submit button to process the form after all the required fields have been filled in: All the required fields will be filled in, I click submit, the page reloads with the saved data variables and then when I hit submit agin, it finally goes through, sending the email and loading the thankyou page. I have searched the posts here and tried multiple things but have not found a solution. I am definitely not a php expert, still a newbie so this may not be the best way to accomplish this but I'd appreciate any ideas on how to finish this up. Here is what I have:
<?php
....
if (empty($Name) && empty($Company) && empty($Address1) && empty($City) && empty($State) && empty($Phone))
{
echo '<p class="tan">The fields marked with an * are required.</p>';
$Process = 'samepageurl';
}
/*else if (empty($Name) || is_numeric($Name))
{
echo '<p class="tan"><b>Please enter your name.</b></p>';
}*/
else if (empty($Company) || is_numeric($Company))
{
echo '<p class="tan"><b>Please enter your company name.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Address1) || is_numeric($Address1))
{
echo '<p class="tan"><b>Please enter your address.</b></p>';
$Process = 'samepageurl';
}
else if (empty($City) || is_numeric($City))
{
echo '<p class="tan"><b>Please enter your city.</b></p>';
$Process = 'samepageurl';
}
else if (empty($State) || is_numeric($State))
{
echo '<p class="tan"><b>Please enter your state.</b></p>';
$Process = 'samepageurl';
}
else if (empty($Phone) || ctype_alpha($Phone))
{
echo '<p class="tan"><b>Please enter your phone number.</b></p>';
$Process = 'samepageurl';
}
else if (strlen($Phone) < 10 || strlen($Phone) > 12 || ctype_alpha($Phone) || ctype_space($Phone))
{
echo '<p class="tan"><b>Please enter a phone number with an area code.</b></p>';
$Process = 'samepageurl';
}
else if (isset($Name) && isset($Company) && isset($Address1) && isset($City) && isset($State) && isset($Phone))
{
$Process = 'processingurl';
}
?>
<form action="<?php echo $Process; ?>" method="post" class="print" >
<p><input type="hidden" name="recipient" value="responses#url.com"/>
<input type="hidden" name="subject" value="Web Site Response"/>
<input type="hidden" name="redirect" value="thankyou.html"/></p>
... form fields ...
</form>
Thank you in advance!
First check for missing variables, then extract and validate the variables, then serve content based on them.
<?php
function verifyPostContains(&$req) {
global $_POST;
$missing = array();
foreach($req as $var => $_) {
if(!isset($_POST[$var])) {
$missing[] = $var;
}
}
return $missing;
}
$requirements = array('name'=>'','city'=>'','state'=>'',...);
$missing = verifyPostContains($requirements);
if(count($missing)>0) {
$content = formErrorReport($missing);
sendHeaders();
echo $content;
exit();
}
// extract, making sure to sanitize
$name = sanitize($_POST["name"]);
...
$errorHtml = array();
// validate by reference. Effectively call testName($name).
if(failsValidation($name, "testName")) {
$errorHtml [] = generateError(NAME_ERROR, $name);
} else { $requirements["name"] = $name; }
if(failsValidation($city, "testCity")) {
$errorHtml [] = generateError(CITY_ERROR, $city);
} else { $requirements["city"] = $name; }
...
if(count($errorHTML)>0) {
generateErrorPage($requirements, $missing, $errorHTML);
} else { processForm($requirements); }
?>
this code assumes you have functions to do the various bits that need to be done, and has some string constants for generating error HTML.
As a newcomer you may want to google for some tutorials that explain doing form processing using PHP at the server, and JavaScript at the client. If you find a tutorial that gives you code that echos errors while it's testing the data, such as you code does, move along. It's not a good tutorial. If you find one that stops after it finds one error, move along too. If you find one that tells you to make sure the values are right in JavaScript, and then says "we already validated this at the client so we use the values directly in PHP", move along, too. Look for a tutorial that explains:
ensuring there's data in all the form fields, using JavaScript, so the submit button is disabled until there's data for all the fields.
ensuring the data matches your criteria, in PHP, so that people who just POST to your server without ever using your page don't get away with injecting all manner of fun stuff they weren't supposed to be able to do
you generate a page with all the errors explained, if there are any, and the form repopulated with the wrong data, but highlighted as wrong
you process the post request if there are no errors.
(Bonus points if the tutorial explains that a POST request is not required to actually ever generate page content as a response, other than a header that indicates whether or not the POST call was accepted or rejected.)
Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.
First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.
Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});
you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()
How can I make PHP print an error inline instead of changing the entire page?
I'd like it to target #errors and fill that instead of changing everything.
The code I'm currently using is die ("Incorrect username or password.");
I'm very new to PHP so sorry if this is a pretty easy thing to do.
Put the error in a variable where you do your logic and print its contents in #errors. For example:
if (username_is_incorrect()) $error = 'Incorrect username or password.';
And in the HTML
<?php if (isset($error)):?><div id="errors"><?=$error?></div><?php endif;?>
There are 2 ways of doing it.
A real inline method is not entirely PHP-based, as it cannot be used without JavaScript and AJAX calls.
Note the irritating disadvantage of this method: you will need to re-check every field again upon receiving form data finally.
Another one will reload your page but it will be the same page with all the form fields, entered data and also freshly generated error messages. This is called POST/Redirect/GET pattern
here is a short example
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
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['name'] = $form['comments'] = '';
}
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 ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>