I am just trying to check if a form variable is empty. The code sets the variables $getsubject and $getsubject to the $_POST of the form, then I am checking if they are, empty and if they are I want to set them to "No Message" or "No Subject". I tried with isset as well and it didn't work. I even tried setting an else statement that does the same thing and it doesn't change it.
$getsubject = $_POST['subject'];
$getmessage = $_POST['message'];
if(empty($getsubject)) {
$getsubject = "<No Subject>";
}
if(empty($getmessage)){
$getmessage = "<No Message>";
}
I found the problem .. the code is working - however the since there were brackets "<" and ">" ... when I retrieved the data from the SQL table, it was not appearing. Not sure why, but when I removed the brackets it worked.
If you are not sure id the data from the form exist you must use !isset to check it before you declare the variables, so:
if(!isset($getsubject)) {
$getsubject = "<No Subject>";
}
else{
$getsubject = $_POST['subject'];
}
if(!isset($getmessage)){
$getmessage = "<No Message>";
}
else{
$getmessage = $_POST['message'];
}
The data from $_POST['subject'];, for example, might not exist, and if you declare it php will give you an error
I suggest that you use a full if conditional to display the results you are looking for combined with html.
IF subject has content
then echo Great subject
ELSE
then echo No Subject
END IF
IF message has content
then echo Thank You for the message
ELSE
then echo No Messgae was entered
END IF
^this is the basic logic not the code
Also look into the trim php code which will trim blank space off of the submission. This helps eliminate blank responses or spaces counting as characters (will not remove space between characters)
Related
I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}
is it possible to do this , im trying to validate a form then, it will redirect using header() if TRUE.. but it seems not to be working? or my method is completely wrong ?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["clientEmail"];
if ($email != $sentEmailClients) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.myurl.com";
header('Location: ' . $newURL);
}
}
Give us more details about what actually happens when you run your code. You're likely facing one of the following problems:
You're using header() after you've already sent output to the browser. Headers must be sent before any other output. Check out the docs. If you change that line with die('redirecting') and that text shows up, then this is your problem.
Request method is not POST. Add die($_SERVER['REQUEST_METHOD']). If something other than POST is printed, then this is your problem.
$_POST['clientEmail'] is not set, or is not equal to $email
$email is not what you expect (where does it come from?)
$sentEmailClients is not what you expect (where does it come from?)
Basically, "why doesn't it work?" is not a good question because it doesn't give us much info with which to help you. Be more specific about what is happening.
Show enough of your code that we understand the origin of the variables you use.
Hi It seems that Your outermost if condition is not working thats why your header function is not working i just tried this and it woks fine. That means either your first if condition is false or either second if condition becomes true every time just try to echo your values before checking them.
<?php
if (1) {
$email = $_POST["clientEmail"];
if (0) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.google.com";
header('Location: ' . $newURL);
}
}
check this print_r($_SERVER["REQUEST_METHOD"]); is POST or not and
$email != $sentEmailClients true or false
The code below simple checks if the user enters in a valid JSON data as denoted in the if statement below. The if statement works just fine for me, it's just getting the page to redirect is not. Could anyone explain why this might be? Thanks
<?php
//Retrives name var from form on previous page
$name = $_REQUEST['name'];
//Changes the title tag based on the users name
$pageTitle = "Thanks ".$name."!";
//
$section = "contact";
//Retrives the product ID based on what the user requested
$productId = $_REQUEST['productId'];
//Retrives the email var from form on previous page
$email = $_REQUEST['email'];
?>
<?php
//Acts as a place holder var for the url containing the productID the user specfied.
$url = 'xxx.xxx.xxx';
//Fetchs the contents of the of the url var address, and returns them into a JSON var
$JSON = file_get_contents($url);
//Puts the JSON var into a parameter that actually does the decoding into JSON
$data = json_decode($JSON,true);
if (empty($data)){
header('Location: http://www.google.com');
exit;
} else {
echo "it's valid";
//References the header file for CSS
include("inc/header.php");
}
You send a few whitespaces before the redirect, when you close and reopen php around your line 14.
And Headers cannot be sent after the body of response is already started. (There should be a warning somewhere unless it is turned off.)
There is a whitespace / enter between
?>
<?php
Once you send any char, a redirect is no longer working. Put everything into a single
<?php ... ?>
and it should work.
Just a hunch but try removing the
?>
<?php
in the middle as this might be sending some information to the client before your asking to send the header. This could cause the header redirect to fail.
In your else statement you don't have a header location specified, all you're doing is echoing that it's valid and you're including a file but not redirecting to a different page.
What you have is this:
else {
echo "it's valid";
//References the header file for CSS
include("inc/header.php");
}
Shouldn't you have a header in there?
When I test to see if the textarea in my form is empty to do a redirect so it doesn't submit it in php, it doesn't work.
The textarea is named $_POST['message'], I know the variable exists because if I do this statement;
if (isset($_POST['message'])) {
header('Location:/');
exit();
}
Then it always redirects back to the index page so the variable must exist, although if I do this;
if (empty($_POST['message'])) {
header('Location:/');
exit();
}
It does not work, also tried with all three combos of =/==/===
if ($_POST['message'] === '') {
header('Location:/');
exit();
}
And also...
if (empty(trim($_POST['message']))) {
header('Location:/');
exit();
}
Any ideas why this is happening? And how I can prevent it, I really need to stop it as I do not want empty values in my mysql table.
I did some research and it seems some other people have had this problem, but I have seen no answer as of yet.
You probably have some whitespaces in the string, which isn't stripped by trim().
Do a strlen() on it to see what's up, and then log it byte by byte (http://stackoverflow.com/questions/591446/how-do-i-get-the-byte-values-of-a-string-in-php).
One thing you could think about is to make sure your textarea doesn't have any content in the markup (spaces, linkebreaks, whatever), like this:
<textarea></textarea>
I'm pretty sure your last try would work if you'd do it correctly, this:
if (empty(trim($_POST['message']))) {
// ...
}
...is a syntax error. empty is a language construct and does not accept expressions. Try:
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
if (empty($message)) {
// $_POST['message'] is empty
}
This will ignore all input lengths below 3 chars:
if (isset($_POST['message']) && strlen(trim($_POST['message'])) < 3) {
header('Location:/');
exit();
}
However, if you just want to check, if a form was submitted, ask for the submit-button:
<input type="submit" name="submit" value="send" />
the php code would be
if (!array_key_exists('submit', $_POST)) {
header('Location:/');
exit();
}
I have a pattern match here that looks like it should work fine. However any input I give makes the conditional fail. I will handle the '99999-9999' case after I get the '99999' case working.
$ZipCode is a textfield that is being submitted on POST.
$ZipCode = $_POST["ZipCode"];
if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{$error_str .= "The zip code you enter must be in the form of: '99999' or '99999-9999'\n";}
if(isset($_POST['submit']))
{?><script>var error = <?= json_encode($error_str);?>;
alert(error);
</script>
<?}
'11111' fails and '111111' also fails
Your code should work correctly. Example:
$ZipCode = "111111";
if(!preg_match("/^[0-9]{5}$/", $ZipCode))
{
echo "Incorrect format";
}
Result:
Incorrect format
Try entering some invalid input to see if the error message is displayed.
To handle both cases at once you can use this regular expression:
/^[0-9]{5}(?:-[0-9]{4})?$/