php isset() is_string() not working - php

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 .

Related

Form submission results in a blank page in PHP

I am trying to make a login system and i want to create a conditional statement that checks whether the global variable $_POST['submit-form'] is set.
If the global variable $_POST['submit-form'] is set then i want to echo out the fields of the submitted forms. This works fine..
The problem comes when i want to check whether the global variable $_POST['submit-form'] is empty, i get a blank page when i submit the form with nothing. It is supposed to echo out something like "You have entered nothing, please try again'.
I don't know what is wrong.
This is the code for the form.
<form action="test-form2.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" name="submit-form" value="submit">
</form>
..and this is the code for the form handler.
<?php
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
// header('refresh=3;url = /test-form1.php');
}
?>
Your $_POST always have submit-form (and it's always not empty), so if statement always returns true. Try to check (for example) only that $_POST['name'] and $_POST['email'] are not empty.
The problem with your code is that checking if it's set isn't enough .. Because it may be set and be empty -- Realistically what you want is to check both isset and whether it's empty IE:
if (isset($_POST['submit-form'] && $_POST['submit-form'] != '' && $_POST['submit-form'] != null)
If the above if statement fails your value for $_POST['submit-form'] is most likely not being submitted.
UPDATE
Check for blank fields
if ($_POST['name'] != '' && $_POST['email'] != ''){
// Do stuff
}else{
if ($_POST['name'] == ''){
echo "name is empty";
}
if ($_POST['email'] == ''){
echo "email is empty";
}
}
That's because isset($_POST['submit-form']) returns true even if you don't input anything in Name and E-mail fields, it's value would be submit string when hit submit button to submit the form. This is the reason else part of below block is not getting executed.
if(isset($_POST['submit-form'])) {
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
Use var_dump($_POST); to see the complete array structure. having said these, you can use the following snippet to achieve the desired result,
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}else{
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
}
Validation and scrutinization of user inputs should be your next action items in the list.

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.

&& isset and number of fields in 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'])){
//...
}

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.

Categories