$_POST checking empty - php

I need a function which can check my $_POST array, for example see this code, there is nothing common in the $_POST array. But i want to check if the array is returning null value from the user.
<?php
switch ($_GET['action']) {
case "one":
$a=$_POST['a'];
echo "your value is". $a;
break;
case "two":
$b=$_POST['b'];
$c=$_POST['c'];
echo "your value is". $b."--".$c;
break;
case "three":
$x=$_POST['x'];
$y=$_POST['y'];
$z=$_POST['z'];
echo "your value is". $x."--".$y."--".$z;
break;
}
?>

Check like this:
$x = (isset($_POST['x']) && $_POST['x'] != "") ? $_POST['x'] : "" ;
echo "your value is". $x.";
As per your comment my updates:
function check_empty($item, $key)
{
$item[$key] = (isset($item) && $item != "") ? $item : "" ;
}
array_walk($_POST, 'check_empty');

You can check if the $_POST array is empty using
empty($_POST)
And if you want to check for individual value is null,
empty($_POST['x'])
Something like:
$x = !empty($_POST['x']) ? $_POST['x'] : '';

You are looking for isset()
$a = null;
if ( isset($_POST['a']) ) {
$a = $_POST['a'];
}

Related

Using empty() to adjust output with multiple variables

I have two primary variables that are composed of strings and other variables. I want the two primary variables only to be echo'ed if all the variables that they are comprised of have data.
The two primary variables are $introduction and colortxt.
$introduction is comprised of $finalvehicle3, $bodystyle, $mileage, and $hi.
$colortxt is comprised of $model, $exterior, and $interiorspec.
If any of the secondary variables are empty, I don't want the primary variable to be displayed.
Below is the code I have created that doesn't seem to be working. I have been using empty().
My PHP:
<?php
$finalvehicle3 = "Toyota Camry";
$bodystyle = "sedan";
$mileage = "30,000";
$hi = null;
$model = "Camry";
$exterior = "red";
$interiorspec = "black cloth";
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
echo "<textarea name='' id='' style='width: 565px;' rows='8' cols='60'>";
echo $introduction." ".$colortxt;
echo "</textarea>";
echo "<br><br>";
?>
In this case $introduction should not be displayed as $hi = null
I can't get empty([$finalvehicle3, $bodystyle, $mileage, $hi]) to work.
I was able to use:
if (empty($hi)
|| empty($finalvehicle3)
|| empty($bodystyle)
|| empty($mileage)){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle."
with ".$mileage." miles.";
}
Will that not work?
Check if both variables are not empty echo them out:
if (!empty($introduction) && !empty($colortxt)) {
echo $introduction." ".$colortxt;
}
As a side, while coding style has personal preference, where you set these variables seems awkward as you set them to empty based on a condition, but logically (my logical at least) is to instead preset them to empty and add data if the data exists.
INSTEAD of your code here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Do this:
$introduction = "";
$colortxt = "";
if (!empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true) {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (!empty([$model, $exterior, $interiorspec]) == true) {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Just looks cleaner to me :)
I'd also not create a new array to check multiple variables, and would do:
if (
!empty($finalvehicle3)
&& !empty($bodystyle)
&& !empty($mileage
&& !empty($hi)
) {
To clarify (not intended to take away from the other answers); only isset() can accept multiple comma-separated values, and not empty().
The manuals state:
on empty():
bool empty ( mixed $var )
on isset()
bool isset ( mixed $var [, mixed $... ] )
Therefore you need to separate and check if each value is empty.
I.e.:
if(empty($var1)) && empty($var2)){}
Or using the || (OR) logical operator depending on what you want to check for; if any or all are empty.
http://php.net/manual/en/language.operators.logical.php
Note:
What you used here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true)
theoretically would be a "false positive".
If anything, you will need to use the == true in a separate statement.
I.e.:
if(empty($var1)) && empty($var2) && $x_var == true){}
However, the first 2 would need the ! negation operator since you're checking if something is true.
I.e.:
if(!empty($var1)) && !empty($var2) && $x_var == true){}

How to display an array $key with this pattern promote-1 for which 1 can be any whole number?

function name( $key, $value ) {
switch( $key ) {
case 'name':
break;
// this is where I would determine the key with this pattern 1-100
case 'promote-'.count++ :
break;
}
}
When I echo the $key sample outputs would be contact_number, card_name and the pattern I would like to determine promote-1, promote-2 and so on. The second option "case 'promote-'.count++" is the pattern I need to determine. That any 'promote-1' to 'promote-100' will fall on that option
Use of switch case is very restricted. Here is a working solution for you.
function name( $key, $value ) {
if(strpos($key,'-') > 0){
$key_arry = explode('-' , $key);
if($key_arry[0] == 'promote' && ($key_arry[1] > 0 || $key_arry[1] <= 100)){
echo 'Patern is promote-1, promote-2......promote-100';
}else{
echo 'anything else';
}
}
}
name('promote-2' , 1);
try with regex
case (preg_match('/promote-\d/', $key) ? true : false) :
// do stuff for people whose name is John, Johnny, ...
break;
'/promote-\d/'this will check for patterns - promote-<any digit>

Using if and else statements error

I have created two links where I would like the page contents to change. The problem is the URL changes but not the page content.
<h3>Filter Results</h3>
<p><a href="index.php?filter='Action'>Action</a></p>
<p>Comedy</p>
if (isset($_GET['filter']) == 'Action') {
echo 'Action';
}
else if (isset($_GET['filter']) =='Comedy') {
echo 'Comedy';
}
It always outputs the first link information "Action".
Your links are faulty:
<p>Action</p>
<p>Comedy</p>
<!-- ^ ^ No single quotes (' ') -->
Yogesh Suthar pointed it out first
Also, isset() will return a boolean (true or false; based on whether or not the variable is set). You're comparing a boolean to a string, a string will always be converted into TRUE (unless the string is "false" or similar), so basically, if the variable is set, the first condition will always match.
You want
if (isset($_GET["filter"]) && $_GET["filter"] === "Action")
Note the use of ===, this will make sure that the variable is exactly what you think it is, and not some sort of other type variable.
Few more points (Shamelessly stolen taken from other answers)
If there are multiple possible filters, check for the variable existance once, and use a switch/case block to determine which of them it is:
if(isset($_GET['filter'])) {
switch($_GET['filter']) {
case 'Action':
echo 'Action';
break;
case 'Comedy':
echo 'Comedy';
break;
}
}
The function isset will only check if the variable is existing! It will not return its value! Try this instead:
<h3>Filter Results</h3>
<p>Action</p>
<p>Comedy</p>
if(isset($_GET['filter']) && $_GET['filter'] == 'Action'){
echo 'Action';
}
else if(isset($_GET['filter']) && $_GET['filter'] == 'Comedy') {
echo 'Comedy';
}
Also, using switch might make things easier in the future:
<h3>Filter Results</h3>
<p>Action</p>
<p>Comedy</p>
if(isset($_GET['filter'])) {
switch($_GET['filter']) {
case 'Action':
echo 'Action';
break;
case 'Comedy':
echo 'Comedy';
break;
}
}
As #MadaraUchiha said about isset and,
if(isset($_GET['filter']) == 'Action')
should be
if(isset($_GET['filter']) && $_GET['filter'] == 'Action')
Also
<a href="index.php?filter='Action'>Action</a>
^ ^ ^ // here you started " but not ended and remove the single quotes around Action
should be
Action
Make sure that you insert an opening and a closing php tag: <?php and ?> To simplify it a bit you could just echo the value you get via $_GET
<h3>Filter Results</h3>
<p><a href="index.php?filter='Action'>Action</a></p>
<p><a href="index.php?filter='Comedy'>Comedy</a></p>
<?php
if(isset($_GET['filter'])){
echo $_GET['filter'];
}
?>
The function isset will return true or false (it checks whether the variable is set or not). Change your code:
if(isset($_GET['filter']) && $_GET['filter'] == 'Action') {
Your if condition is not correct do it:
if(isset($_GET['filter']) && $_GET['filter'] == 'Action'){
echo 'Action';
}
Similarly with else if:
else if(isset($_GET['filter']) && $_GET['filter'] =='Comedy') {
As you are comparing the isset($_GET['filter']) with the value although isset returns true of false so you need to compare the value of $_GET['filter'].
you dont have to use isset() and then compare.
$filter = $_GET['filter'];
if(isset($filter)){
if($filter == 'Action'){
echo 'Action';
}else if($filter == 'Comedy'){
echo 'Comedy';
}
}
isset returns true and since 'Action' is not null, it evaluates to true.
if ((isset($_GET['filter'])) && ($_GET['filter'] == 'Action')) {
// ...
} else if ((isset($_GET['filter'])) && ($_GET['filter'] == 'Comedy')) {
// ...
}
BTW such code would sooner or later become a nightmare to maintain.
You could instead, for example
function preventDirectoryTraversal($requestParam) {
return preg_replace("/\//", "", $requestParam);
}
// ...
if (isset($_GET['filter'])) {
$filterName = preventDirectoryTraversal($_GET['filter']);
include(FILTERS_DIR . "/" . $filterName . ".php");
}
or something alike. Of course this can be further improved, but I hope you get the point.
Wrong use of isset, check documentation, return a boolean.
if (isset($_GET['filter']))
{
switch ($_GET['filter'])
{
case 'Action':
//TODO
break;
case 'Comedy':
// TODO
break;
default:
// TODO
break;
}
}
//isset will always return true or false
if(isset($_GET['filter'])){
if($_GET['filter']=='Action')
{
echo 'Action';
}elseif($_GET['filter']=='Comedy'){
echo 'Comedy';
}
}

Unable to set session under switch/case condition

I am unable to set session for $_SESSION['next'] under switch/case condition, while $_SESSION['user_id'] works perfectly before the condition. The script run into each condition of switch/case condition and redirect without setting $_SESSION['next']. Is there any specific reason why it fails to work? How to solve this?
require_once ('../src/facebook.php');
require_once ('../src/fbconfig.php');
//Facebook Authentication part
$user_id = $facebook->getUser();
if ($user_id <> '0' && $user_id <> '') {
session_start();
$_SESSION['user_id'] = $user_id;
switch((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc';{
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'def';{
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'ghi';{
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
default;{
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
}
} else {
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;
}
Your switch is all wrong. Read the manual and try this:
<?php
switch ((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc':
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'def':
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'ghi':
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
default:
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
}
You're using exit in your switch, which (unless you want your script to end at the switch) is a no-no. Instead, you have to use the break keyword.
You also use semicolons and curly braces for each case.
case 'ghi';{ ... }
NO! Proper usage is
case 'ghi':
.
.
.
break;
Update: I just noticed you use this line:
if ($user_id <> '0' && $user_id <> '') { ... }
What is <> doing in PHP code? The "standard" operator for "not equals" is != in PHP. Use it correctly or no one will want to use your code.
Second update: You never set $_SESSION['next'] in your default case. It's very likely that your switch is always going to the default case. This would cause the behavior you're experiencing.
I suggest:
if (($user_id != '0') && ($user_id != ''))
(parentheses, and the != operator)
and also a DRYer switch:
$page = array_key_exists('page', $_GET) ? $_GET['page'] : '';
switch ($page) {
case 'abc':
$next = 'AAA';
$loc = 'https://www.example.com/xxx/';
break;
case 'def':
$next = 'BBB';
$loc = 'https://www.example.com/yyy/';
break;
... // and so on
}
if (isset($next)) {
$_SESSION['next'] = $next;
// If it does not work, you have problems with your session ID, maybe?
}
// I find this syntax easier
print <<<SCRIPT
<script type="text/javascript">
top.location.href = '$loc';
</script>
SCRIPT;
exit();

Displaying error instead of null values in PHP

I am building up a site in PHP which takes input of more than 20 fields from user. Hardly 3-4 field values are compulsory, rest can be left blank. I want to display a custom error message instead of blank or zero or null while displaying these values. How can this be done? I am using MySQL as backend.
I assume you use the $_POST array.
In that case you could just do:
$errors = array();
foreach($_POST AS $key => $value) {
if(empty($value)) {
$_POST[$key] = "Custom error message"; // Or place it in an apart array like:
$errors[$key] = "Custom error message";
}
}
You can also choose to print the message to the screen immediately. That's up to you.
Besides, did you ever consider a Validation library like:
http://kohanaframework.org/guide/security.validation
Good luck!
<?php
$var1 = 'Foo';
$var2 = '';
$var3 = NULL;
echo ( ! empty($var1)) ? $var1 : 'Not set!'; // Foo
echo ( ! empty($var2)) ? $var2 : 'Not set!'; // Not set!
echo ( ! empty($var3)) ? $var3 : 'Not set!'; // Not set!
/**
* Alternative function solution based on OP's comment:
*/
function output($str)
{
echo ( ! empty($str)) ? $str : 'Not set!';
return TRUE;
}
output($var1); // Foo
output($var2); // Not set!
output($var3); // Not set!

Categories