filter_has_var function - php

I was having trouble trying to make this function work for ages. Before, I was doing
if ( !filter_has_var(INPUT_POST, 'email') ) {
code here etc.
}
and this never worked though is the correct format for how the function should be set up. reference
Then after playing about with it trying to make it function, i changed 'email' to '$email' and this did the trick. So, now I'm confused, is this a glitch or is my code at the top incorrect?

You can use:
if (isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//Your Code here for valid email...
}
else
{
//Your Code here for invalid email...
}

Through this example i think you can better understand
if ( !filter_has_var(INPUT_GET, 'email') ) {
echo "Email Not Found";
} else {
echo "Email Found";
}
Output
localhost/nanhe/test.php?email=1 //Email Found
localhost/nanhe/test.php?email //Email Found
http://localhost/nanhe/test.php //Email Not Found
Consider on second example
http://localhost/nanhe/test.php
$_GET['email']="info#nanhe.in";
if ( !filter_has_var(INPUT_GET, 'email') ) {
echo "Email Not Found";
} else {
echo "Email Found";
}
But output will be Email Not Found

Related

Received Array From one Input Field How Can Validate it?

I want to get ten emails from user.how to check the user provide the correct email or not ? i am try multiple methods but failed to check it please help.
for($i=1;$i<=9;$i++)
{
echo "<input type='text' value='' name='email[]' class='form-control'>"."</br>";
}
// Php Code
// Step One Catch The Values
$email = $_POST['email'];
// Unset the empty values from array
foreach($email =>$key as $emails){
if($emails == ""){
unset($email[$key]);
}
}
Here I am successfully done But when i try to validate it it return me errors which i was never face.
I want to remove html special character from input field and also validate my input using filter_var for email validation. I am trying to do it with loop through method but does not work.
To achieve that look over below code. As you are receiving the array of email as an input from the end user.
if(count($_POST['email']) > 0)
{
$pattern = "/^\[?[0-9\.]+\]?$/";
foreach($_POST['email'] as $email)
{
if (preg_match($pattern, $email) === 1) {
// emailaddress is valid
}
}
}
You are writing foreach wrong way. try below code
foreach($email as $key=>$emails)
{
if($emails == "")
unset($email[$key]);
}
The easiest and safest way to check whether an email address is well-formed is to use the filter_var() function:
if(count($_POST['email']) > 0)
{
$email = $_POST['email'];
foreach($email as $key => $emails)
{
if(!filter_var($emails, FILTER_VALIDATE_EMAIL))
{
//invalid email
unset($email[$key]);
}
else
{
//valid email
}
}
}

Php how to use multiple parameters

there are two parameters in my app, user will fill one of them, but two parameters will get posted into php,php should select non empty field and do some action! something like this.point me right direction. i think 'isset get' should not be used three times like that right?which statement to be used 'and' or 'or' statement.?
i know it's stupid question! i appreciate ur help.
if (isset($_GET['Email']) && !empty($_GET['Fax'])) {
echo "fax is empty and Email = ".$_GET['Email'];
} elseif (isset($_GET['Fax']) && !empty($_GET['Email'])) {
echo "email is empty and Fax = ".$_GET['Fax'];
} elseif (!empty($_GET['Fax']) && !empty($_GET['Email'])) {
echo "Fax and email is empty";
} else {
echo"empty";
}
Simpler version:
$email = isset($_GET['Email']) ? $_GET['Email'] : null;
$fax = isset($_GET['Fax']) ? $_GET['Fax'] : null;
if (empty($email)) {
// email empty
}
if (empty($fax)) {
// fax empty
}

I Have A Registration Form That Is Kicking Back Custom Made Errors Before Submission

I'm working on a registration for my classifieds (via a tutorial) but I'm having problems. For some reason, just visiting this page: http://classifieds.your-adrenaline-fix.com/register.php
will generate the 2 custom errors you'll see in a red box above the registration form BUT the form hasn't even been submitted yet so I don't know why this is happening. If anyone could shed some light on this I'd be most appreciative and I thank you all in advance!!
(I've been staring at it for hours)
Here's the code that validates and submits the form data;
<?php
if(empty($_POST) === false) {
$VisitorsFirstName = $_POST['First_Name'];
$VisitorsLastName = $_POST['Last_Name'];
$VisitorsEmail = $_POST['E_mail'];
$VisitorsPassword = $_POST['Pass'];
$RequiredFlds = array('First_Name', 'Last_Name', 'E_mail', 'Pass', 'PassAgain');
foreach($_POST as $key=>$value) {
if(empty($value) && in_array($key, $RequiredFlds) === true) {
$Err[] = 'All Fields Are Required';
break 1;
}
}
if(empty($Err) === true) {
if(email_exists($VisitorsEmail) === true) {
$Err[] = 'The Email Address \''. $VisitorsEmail. '\' Is Already In Use.';
}
if(strlen($VisitorsPassword) < 4) {
$Err[] = 'Please Select A Password of At Least 4 Characters.';
}
if($_POST['Pass'] !== $_POST['PassAgain']) {
$Err[] = 'Passwords Do Not Match.';
}
if(filter_var($VisitorsEmail, FILTER_VALIDATE_EMAIL) === false) {
$Err[] = 'A Valid Email Address is Required';
}
}
}
if(isset($_GET['success']) && empty($_GET['success'])) {
echo 'You Have Now Been Registered and Can Proceed to Creating Your First Ad<br>(Use the Email and Password That You Registered With to Login)';
} else {
if(empty($_POST) === false && empty($Err) === true) {
$register_data = array (
'VisitorsFirstName' => $_POST['First_Name'],
'VisitorsLastName' => $_POST['Last_Name'],
'VisitorsPassword' => $_POST['Pass'],
'VisitorsEmail' => $_POST['E_mail'],
'Notify' => $_POST['Notify']
);
register_func($register_data);
header('Location: register.php?success');
exit();
} else if(empty($Err) === false) {
echo output_error($Err);
}
}
?>
Upon putting just the code you provided on my own server by itself, it works as designed. It isn't running the top block of code, because the $_POST variable is empty. Try outputting the contents of $_POST at the top of the file so you can figure out why it isn't empty.
print_r($_POST);
Try this:
if(!empty($_POST['First_Name']) && !empty($_POST['Last_Name']) && !empty($_POST['E_mail']) && !empty($_POST['Pass'])){
....
}
OR
try isset($_POST['First_Name'])......
This works fine for me!
You could instead check if the submit button was pressed. Like this:
if (isset($_POST['submit']) {
// get the post values
}
This way you could eliminate the script launching before the form was actually submitted. Right now it seems to run as soon as I visit the page.

how to restrict the value entered in a textbox based on the value entered in the previous one in php

I have 2 textboxes one is for maximum marks and the other for the obtained marks..
The value to be entered in the second box must be restricted in such a way that it is less than or equal to the maximum marks.. Only numbers must be entered into those boxes..
Maximum Marks<input type=text name=maxmarks maxlength='2' >
Obtained marks<input type='text' maxlength='2' name='obtmarks'>
Please help me with this.. Thank you in advance..
Well if you want to do it client side, you will have to use Javascript. If you want to do it server-side, why don't you send them back the page with an error message if the second number exceeds the first. You might also might want to look into HTML5 input options if that is an available option for you. Those will automatically do the number validation.
You could try something like this...
$response_array = array();
if($obtained > $max){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained to big</div>';
}
if(!is_numeric($obtained){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained not a number</div>';
}
echo json_encode($response_array);
This is pseudo code, obviously you will need to tweak it for your purpose.
First you have to make checks in your php script that you submit the form, you can use javascript after to make it more user friendly but if someone change the source code or just turn javascript off he will be able to submit anyting.
In your process_form.php:
session_start();
$errors = array();
if (!isset($_POST['maxmarks']) || empty($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field is required.';
}
else {
if (!is_int($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field must be an integer.';
}
else {
$maxmarks= (int) trim($_POST['maxmarks']);
}
}
if (!isset($_POST['obtmarks']) || empty($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field is required.';
}
else {
if (!is_int($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field must be an integer.';
}
else {
$obtmarks= (int) trim($_POST['obtmarks']);
}
}
if (!empty($errors)) {
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else if ($obtmarks > $maxmarks){
$errors[] = 'The Obtained Marks must be less or equal to Maximum Marks.';
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else {
//process data
}
In your_form.php now:
session_start();
if (isset($_SESSION['form_errors']) && !empty($_SESSION['form_errors'])) {
$errors = $_SESSION['form_errors'];
unset($_SESSION['form_errors']);
}
echo '<ul>';
if (isset($errors)) {
foreach($errors as $error) {
echo '<li>' . $error . '</li>';
}
}
echo '</ul>';
//your form here

Remove specific definitions from a variable in PHP

I have a PHP mail script that validates name, email address, and phone number before sending the mail. This then means that the Name, Email address, and Phone fields are Required Fields.
I want to have it so that the Name and EITHER Email or Phone are required. Such that if a name and phone are inputted, it sends the mail, or if a name and an email are inputted, it also sends the email.
The way the script works right now is it has several IF statements that check for (1) name, (2) email and (3) phone. Here's an example of an if statement of the code:
if ( ($email == "") ) {
$errors .= $emailError; // no email address entered
$email_error = true;
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
$email_error = true;
}
And here's how it sends the mail:
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
echo "<p id='correct'>";
echo "ההודעה נשלחה בהצלחה!";
echo "</p>";
} else {
if (($email_error == true)) {
$errors != $phoneError;
/*echo "<p id='errors'>";
echo $errors;
echo "</p>";*/
}
if (($phone_error == true)) {
$errors != $emailError;
$errors != $invalidEmailError;
/*echo "<p id='errors'>";
echo $errors;
echo "</p>";*/
}
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
This doesn't work though. Basically this is what I want to do: If no email address was entered or if it was entered incorrectly, set a variable called $email_error to be true. Then check for that variable, and if it's true, then remove the $phoneError part of the $errors variable.
Man I hope I'm making some sense here. Does anyone know why this doesn't work? It reports all errors if all fields are left empty :(
Thanks!
Amit
You need at first to build up an array of errors, i.e.:
$errors = array();
if (!$phone) { // add more validation as required
$errors['phone'] = $phoneError;
}
if (!$email) {
$errors['email'] = 'No email provided';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email provided';
}
Then you send, or display the errors:
if (!isset($errors['phone']) || !isset($errors['email'])) {
// send mail here, only if either the phone or the email error is missing
} else {
// display errors
echo '<p id="errors">';
foreach ($errors as $error) {
echo $error;
}
echo '</p>';
}
so...
$sent=false;
if(!$name){
$errors[]='No Name was supplied.';
return($errors);
}
if($phone && validatePhone($phone)){
//send the phone message however...
$sent=true;
}
if($email && validateEmail($email)){
//send the email here...
$sent=true;
}
if(!$sent){
$errors[]='Neither an email or a phone was supplied';
return($errors);
}
classed:
class Communication {
var $sent=false;
var $errors=false;
public function __construct(){
$this->phone=$_POST['phone'];
$this->email=$_POST['email'];
$this->name=$_POST['name'];
if($this->validateName()){
$this->validateEmail();
$this->validatePhone();
}
}
public function validateEmail(){
//do your regex here and eval either false or true to $status
if(!$status){
$this->errors['ErrorInvalidEmail']=ErrorInvalidEmail;
}else{
$this->sendEmail();
}
}
public function validatePhone(){
//do your regex here and eval either false or true to $status
if(!$status){
$this->errors['ErrorInvalidPhone']=ErrorInvalidPhone;
}else{
$this->sendText();
}
}
public function validateName(){
//do your regex here and eval either false or true to $status
if(!$status){
$this->errors['ErrorInvalidName']=ErrorInvalidName;
return(false);
}else{
return(true);
}
}
public function sendEmail(){
$this->sent=true;
//do your sending by email HERE
}
public function sendText(){
$this->sent=true;
// do your sending by text/phone here
}
}
$c=new Communication();
print_r($c->errors);
I believe
if ( !($errors) )
should be
if ( !$errors )
//or
if( !isset( $errors ) )
While there is no benefit over doing it Selsaek's way (above), one way to do it is with a bit mask (a set of constants which are powers of 2, and one storage variable). You OR the storage variable with the constant, and then when you AND the two together later, a nonzero result means the flag was tripped. No reason you can't use an array to store the flag and the text:
$WARNING_MASK = array('name' => 1, 'email' => 2, 'phone' => 4);
$warningflag = 0;
to set a flag an error (you OR the storage variable with a constant):
$warningflag = $warningflag | $WARNING_MASK['name'];
to test for an error (you AND the storage value with the constant):
if ($warningflag & $WARNING_MASK['name']) {}

Categories