&& isset and number of fields in PHP - php

The following PHP is used to send an email from a contact form. My question is:
Now I have 3 fields, name, email and message and in the PHP there is:
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
If I wanted to add anther field, do I also need to add && isset for it?
What are && isset? are they really needed?
Here is the PHP:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "email here";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
DO I need them if I have a JS validation script?

You could simply make use of the comma operator , with the isset for checking multiple fields !
So you don't need to add the isset keyword again and again.
The code...
if(isset($_POST['name'],$_POST['email'],$_POST['message'],$_POST['token']))
{
echo "All the fields are set and good to go !";
}
else
{
echo "Some fields were not filled !";
}

You need to learn the basics in PHP
isset() is a, lets say little helping "function", you can check, it the field "is set", whether it is "filled" or not.
And && is a logical operator.
If you have another field and don't exactly now, what you are doing, then yes, just add && and isset, but I can only give you an advice: Learn PHP and try to understand it - it not hard.
Actually I know some very good tutorials in German language, but I am sure some fellow "overflowers" can recommend you some.
If the you like the tutorials, then buy a book - I know, they often are very expensive - but it is worth it!
Happy Coding!

&& is a logical operator.
&& isset is not function. only isset is a language construct which checks a session variable or post variable is set.For adding another variable also you need to use && isset($_POST['variable'])
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
this statement means that it is checking whether post variables name,email,message,token were set and loop goes in if all values were set.because && allows only if all conditions return true

If tests the condition, if it is true, the following block (code between { and } ) is executed.
&& is the and operator, isset tests whether the variable is set.
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
In plain english this reads: if variable $_POST['name'] is set and variable $_POST['email'] is set as well and ... (you got it). You can actually replace && with and.
Isset also accepts multiple arguments, so you can indeed do isset($_POST['name'],$_POST['email',...).
A previous answer talks about comma operator, there is a comma operator, but this is not it, this is a function having many arguments.
$_POST['name'] in plain english is the 'name' input field in the form that has been posted.
Note that isset-check of the fields does not make much sense here. They can be set allrigt, but still be empty. If you want to make the fields mandatory you should test both that they are set and not empty.
if(isset($_POST['name']) and !empty($_POST['name'])...
! is the logical not operation, so !empty means not empty.
Whether the new field should be tested like this, depends on whether it is mandatory or not.
Reading a PHP-tutorial might do you very good.

Here, if you want to send the value of a new field by mail, you'll always need to test the existence of it by isset.
Also, I suggest you to test if the variable is not empty, because fields like 'input text' will always exist even if it is empty.
You can use empty function to test if it exists and not empty
if(!empty($_POST['name'])
&& !empty($_POST['email'])
&& !empty($_POST['message'])
&& !empty($_POST['token'])){
//...
}

Related

PHP form validation that includes SUBMIT button

I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.

Basic Form Validation Check Number?

In this script I am checking if fields are not empty and email address is syntactically correct. How to add a text input at the bottom of my form for a basic sum question, e.g. (2+5)= I want to add a validation element to my current script to check if this equals 7.
if (empty($name) || empty($phone) || empty($email) || empty($enquiry))
{
echo " * Sorry all fields are required.";
}
elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email))
{
print "<p>Sorry the email address you entered looks like it's invalid.</p>";
}
else
{
mail($to, $sub, $mes, $headers);
print "<p>Thank you ".$name." for contacting us.<br /><br />We will be in touch shortly.</p>";
}
If you are just wanting to validate a static sum, e.g. you know it is always going to be ( 2 + 5 ) = 7
Then you could just write a simple function to check the posted value.
// this being your posted value;
$validate = 7;
function SumCheck($value){
if ( 2 + 5 == $value ){
return true;
}
else{
return false;
}
}
Then change your initial line to;
if (empty($name) || empty($phone) || empty($email) || empty($enquiry) || !SumCheck($validate))
However, I would suggest using RECAPTCHA as Robert Podwika has suggested.
1 If your session is not started use in the very first line
session_start();
2 Before form is shown. Add this code. Also remember that session start must be also in file where validation is.
$numa = rand(1,5);
$numb = rand(0,4);
$_SESSION['valid_res'] = $numa+$numb;
echo "<p>To submit form please solve this equatation $numa + $numb = ?";
echo '<input type="text name="result_val" />';
3 In validation functions you should check
if(intval($_POST['resul_val']) != $_SESSION['valid_res'])
{
echo "sorry you put wrong result in validation form";
}
However, if I were you I'd use RECAPTCHA

filter_var in php 5.3.8

I am developing a user registration form and want to validate a user's email address.
However,all the php docs I have read suggest the use of filter_var.
My script validates a valid email as invalid.
Please post a working script or perhaps guide me through my script.
Hers is my script :
<?php
if(isset($_POST['email'])== true && empty($_POST['email'])false)
{
$email = $_POST['email'];
}
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
echo"valid email";
}
else
{
echo"invalid email";
}
?>
if(isset($_POST['email'])== true && empty($_POST['email'])false)
this should be
if(isset($_POST['email']) && !empty($_POST['email']) )
or as #jack you can use just
if (!empty($_POST['email']))
the empty() does implicit isset()
$email = isset($_POST['email']) ? $_POST['email'] : "";
echo(filter_var($email,FILTER_VALIDATE_EMAIL) ? "valid email" : "invalid email");
if(isset($_POST['email'])== true && empty($_POST['email'])false)
^^^^^^^--redundant ^^^^^---typo?
In your case you shouldn't use filter_var, but filter_input. This is all the code you would need:
if ($email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)) {
// email was submitted and is a valid email
}
This bug might be related to your problem though.

php isset() is_string() not working

I have a rough php script that sees if a user has filled in the html form input after they have clicked submit. I am having a problem with getting isset() and is_string() to work. If I use isset() the form is emailed even if the form inputs are left blank, is_string() throws an error messages even if the form input are filled in. I have tried !isset() and that still sends blank input. The only thing working is if I use == NULL. At this moment in time I am not going to validate the input as I am trying to understand why this isn't working as I am pretty new to PHP.
$subject = "Feedback from Your Website.";
$email = ($_POST['email']);
$name = ($_POST['name']);
$message = ($_POST['feedback']);
if (isset($_POST["name"]))
{
//send message
mail($subject, $name, $email, $message);
}
else
{
//error message
echo "Please do not miss out any fields";
}
I also tried:
if (isset($_POST["name"], $_POST['email']))
{ }
if (isset($name, $email))
{ }
if (is_string($name || $email))
{ }
But all failed, so far all that's working is:
if ($name == NULL || $email == NULL || $message == NULL)
{ }
Thank you in advance.
Try to use empty(). This function return TRUE if a variabile is empty or non set, FALSE otherwise.
if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["feedback"]))
{
//error message
echo "Please do not miss out any fields";
}
else
{
//send message
mail($subject, $name, $email, $message);
}
is_string($name || $email) is not working because $name || $email is cast to a boolean and a boolean is not a string.
isset() function will return a True value after your form submitting. Actually, your field has been sent to your target file. So your code will send emmial. For what you need, you must use the code below:
if (isset($_POST["name"]) && $_POST["name"] != '') {
// do something
}
isset checks if value is created in the array. It IS going to be there always as the form always have the same fields, empty or not. You need to check their content
isset() returns true because $_POST['email'] has been set. It simply is empty. Since you submit the form all the variables of the form have been set.
You have to write this
if (isset($_POST["email"]) && $_POST["email"] != '')
How about empty( ) you can check the details of the function in te php manual .

PHP: submit form with self and render different page items?

I've never done that before and simply need a little advice how to do so …
I have a index.php file with a simple contact form.
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
The index.php file has the following script on top.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address#something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "\n\n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
I have two questions now:
1.)
How exactly can I render/not-render certain stuff when either the validation went wrong or a success or an error comes back when submitting the mail?
e.g. I know that I can do that!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
However $valid will always be wrong on page-load when not submitting the form and also the email will always return the error message on the first page load. How can I only render or not render specific stuff when the form is submitted?
E.g. When submitting the form and a success comes back I don't want to render the #contactform anymore. I simply want to print "Successfully made contact" into an h1 or so.
How can I make that happen? It's probably rather simple I just can't find a solution for myself.
2.)
When using $_SERVER["SCRIPT_NAME"] or PHP_SELF as action the url after submitting the form will always change to "mydomain.com/index.php". Can I prevent that from happening? I want to submit the index.php file itself however I just don't like it when /index.php is written into the url. Is it possible to stop that from happening?
Thank you for your help!
Matt,
For the first question as to printing to the screen based on success or failure of the email, your checks seem fine, but you probably aren't going to get an email failure in time to display that to the screen. That said, you just need to wrap your second set of code in an if statement. Something like this:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
As for not including the directory in the form action, there are many ways to do this, but here's one:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
And then use $script in the form action.

Categories