htmlspecialchar to multiple variables - php

I was wondering if there's a simpler way of doing this
$admsquarecmail = #$_POST['squarecmail'];
$admsquarecmail = htmlspecialchars($admsquarecmail, ENT_COMPAT);
$admsquarecsubject = #$_POST['squarecsubject'];
$admsquarecsubject = htmlspecialchars($admsquarecsubject, ENT_COMPAT);
$admsquarectymessage = #$_POST['squarectymessage'];
$admsquarectymessage = htmlspecialchars($admsquarectymessage, ENT_COMPAT);
$admsquarecontagain = #$_POST['squarecontagain'];
$admsquarecontagain = htmlspecialchars($admsquarecontagain, ENT_COMPAT);
The idea is not to type
htmlspecialchars($var, ENT_COMPAT);
every time a variable is added.

Method 1:
You may apply htmlspecialchars to all elements of $_POST with array_map:
$arr = array_map("htmlspecialchars", $_POST, array_fill(0, sizeof($_POST), ENT_COMPAT));
Then:
$admsquarecmail = isset($arr['squarecmail']) ? $arr['squarecmail'] : "";
$admsquarecsubject = isset($arr['squarecsubject']) ? $arr['squarecsubject'] : "";
$admsquarectymessage = isset($arr['squarectymessage']) ? $arr['squarectymessage'] : "";
...and so on.
Method 2:
You may apply htmlspecialchars to the elements of $_POST one by one. In this method you don’t need an array apart from $_POST itself:
$admsquarecmail = isset($_POST['squarecmail']) ? htmlspecialchars($_POST['squarecmail'], ENT_COMPAT) : "";
$admsquarecsubject = isset($_POST['squarecsubject']) ? htmlspecialchars($_POST['squarecsubject'], ENT_COMPAT) : "";
$admsquarectymessage = isset($_POST['squarectymessage']) ? htmlspecialchars($_POST['squarectymessage'], ENT_COMPAT) : "";
...and so on.
Method 3:
You may create a small function like the following:
function obtain_POST_value($key){
if(array_key_exists($key, $_POST)) return htmlspecialchars($_POST[$key], ENT_COMPAT);
return "";
}
Then:
$admsquarecmail = obtain_POST_value('squarecmail');
$admsquarecsubject = obtain_POST_value('squarecsubject');
$admsquarectymessage = obtain_POST_value('squarectymessage');
...and so on.

Related

Although I use isset, I get an undefined index error

I know it asks too many time. But the isset function is not solve my problem.
$get = (isset($this->settings[$set['id']])) ? $this->settings[$set['id']] : '';
Notice: Undefined index: id in \public_html\settings.php on line 419
Try to check if the variable is set before using it as an argument.
$get = isset( $set['id']) ? $this->settings[$set['id']] : '';
Maybe, $set['id'] must check, like this:
$set_ = isset($set['id']) ? $set['id'] : '';
$value = isset($this->settings[$set_]) ? $this->settings[$set['id']] : '';
I would simply add it to the isset call
$get = isset( $set['id'],$this->settings[$set['id']]) ? $this->settings[$set['id']] : '';
You can use multiple arguments in isset. This is roughly equivalent to doing this:
$get = isset($set['id']) && isset($this->settings[$set['id']]) ? $this->settings[$set['id']] : '';
This can be easily tested with this code:
$array = ['foo' => 'bar'];
$set = []; //not set
#$set = ['id' => 'foo']; //uncomment to test if set
#using [] to add an element to a string not an array
$get = isset($set['id'],$array[$set['id']]) ? $array[$set['id']] : '';
echo $get;
When $set = ['id' => 'foo'] the output is bar if you leave that commented then the output is an empty string.
Sandbox

Best way to check if lots of variables contain a string and if so change it?

I have lots of variables that I need to check to see if it is equal to "None". If a variable is equal to "None" I would like to change it to = "-";
What's the best practice way of doing this without having a separate IF function for each variable?
//Variables
$profileEthnicity = h($result["profile_ethnicity"]);
$profileHeight = h($result["profile_height"]);
$profileBuild = h($result["profile_build"]);
$profileEyeColor = h($result["profile_eye_color"]);
$profileHairColor = h($result["profile_hair_color"]);
$profileTattoos = h($result["profile_tattoos"]);
$profilePiercings = h($result["profile_piercings"]);
//Example
if($profileEthnicity == "None") { $profileEthnicity = "-"; }
Since the values are in an array you can do this:
foreach($result AS $key => $val) {
('None' == $val) ? $result[$key] = '-' : $result[$key] = $val;
}

How to add string to a PHP variable?

I'm not sure it's even the right way to define this question.
I have string that may be exist, and may not. It happens to be a number: $number
If $number doesn't exist, then I want to use the PHP variable $url.
But if $number does exist, then I want to use the PHP variable which is named $url+the number, i.e, $url2 if $number=2
So I tried this code, but it doesn't work:
$number = "2"; //(Can be either missing, or equal to 1, 2, or 3)
$url = "www.0.com"; // Fallback
$url1 = "www.1.com";
$url2 = "www.2.com";
$url3 = "www.3.com";
$result = $url.=$number ;
// If $number=1, I want $result to be : www.1.com
// If $number=2, I want $result to be : www.2.com
// If $number=3, I want $result to be : www.3.com
// If $number IS NOT SET, I want $result to be : www.0.com
// Now do something with $result
Perhaps there's a completely better way to achieve what I want (will be happy to see example), but anyway I'm curious as well to understand how to achieve it my way.
Okay, so you're talking about a variable variable.
You should define the name of the variable you need to use in a string, and then pass that to a variable variable using $$ syntax:
if( isset($number) && is_numeric($number) )
{
$name = 'url'.$number;
$result = $$name;
}
else
{
$result = $url;
}
That having been said, you may be better off using an array for this:
$urls = [ 'www.0.com', 'www.1.com', 'www.2.com', 'www.3.com' ];
$result = (!isset($number)) ? $urls[0] : $urls[ intval($number) ];
You can use ternary with in_array and empty.
$number = "2"; //(Can be either missing, or equal to 1, 2, or 3)
$url = "www.0.com"; // Fallback
$url1 = "www.1.com";
$url2 = "www.2.com";
$url3 = "www.3.com";
$result = (!empty($number) && in_array($number, array(1,2,3))) ? ${'url' . $number} : $url;
echo $result;
Demo: https://eval.in/821737
In php you can have things like dynamic variable names:
$variableName = "url".$number;
$result = $$variableName;
However, you should make sure, that $variableName refers to an existing variable:
$result = "www.fallbackURL.com";
if(isset($$variableName)) $result = $$variableName;
Or Try this code:
$number = 5;
$url[0] = "www.0.com"; // Fallback
$url[1] = "www.1.com";
$url[2] = "www.2.com";
$url[3] = "www.3.com";
if (!isset($number)) $number=0;
if (!isset($url[$number])) $number=0;
$result = $url[$number];
If you add $ front of string, it define variable, so you can use following code:
<?php
$number = "2"; //(Can be either missing, or equal to 1/2/3)
$url = "www.0.com"; // Fallback
$url1 = "www.1.com";
$url2 = "www.2.com";
$url3 = "www.3.com";
if(isset($number) && is_numeric($number) && $number <= 3) {
$variable_name = 'url' . $number; //string like url2
} else {
$variable_name = 'url';
}
$result = $$variable_name ; //define $url2 from url2 string
echo $result;
// Now do something with $result
Example for define variable with string variable:
$string = 'hello';
$$string = 'new variable'; //define $hello variable
echo $hello; //Output: "new variable"
if the url need just a number, you can do this easy way
($number)?$number:0;
$url = "www.".$number.".com";
if there are specific real url, you can use array
$array[0] = "www.google.com";
$array[1] = "www.facebook.com";
($number)?$number:0;
url = $array[$number];
Updated code:
$number = "2";
if(isset($number)){
$res = "url".$number;
$result=$$res;
}else{
$result=$url;
}
echo $result;

$_POST better writing quality

I have this code :
if(isset($_POST['prenom2'])){
$t['prenom2'] = $_POST['prenom2'];
}else{
$t['prenom2'] = '';
}
if(isset($_POST['nom2'])){
$t['nom2'] = $_POST['nom2'];
}else{
$t['nom2'] = '';
}
if(isset($_POST['prenom3'])){
$t['prenom3'] = $_POST['prenom3'];
}else{
$t['prenom3'] = '';
}
etc (there are 5 or 6 fields I need to test).
There must be a better way of doing this, like if a given index of POST isn't set, that index is...
Thanks
You can use foreach.
$indexes = array('prenom2', 'nom2', ...);
$t = array();
foreach ($indexes as $i) {
$t[$i] = isset($_POST[$i]) ? $_POST[$i] : '';
}
print_r($t);
If you don't want to use if..else.. condition then you can use ternary : operator as
$t['prenom2'] = (isset($_POST['prenom2'])) ? $_POST['prenom2'] : '';
$t['nom2'] = (isset($_POST['nom2'])) ? $_POST['nom2'] : '';
Basically the same as the answer from Matei but moved in a function to reduce duplicate code.
Parameter $t is your final array and $key is a string representing the array index. The final $t array is also returned so there is no need for passing a reference.
function setT($t, $key)
{
$t[$key] = isset($_POST[$key]) ? $_POST[$key] : '';
return $t;
}
$t = setT($t, 'prenom1');
$t = setT($t, 'prenom2');
$t = setT($t, 'prenom3');
Based on your real problem, you may choose one of these:
for($i=1; $i<6; $i++){
$t['prenom'.$i] = (isset($_POST['prenom'.$i])) ? $_POST['prenom'.$i] : '';
$t['nom'.$i] = (isset($_POST['nom'.$i])) ? $_POST['nom'.$i] : '';
}
or
$indexes = array('prenom2'=>'', 'nom2'=>'', ...);
$t = array_merge($indexes,$_POST);

methods of declaring multiple variables

I have the following blocks of code:
$ship = $this->get_address($this->dealer_num);
$bill = $this->get_address($this->bill_to_num);
$this->ship_name = $ship['CMNAME'];
$this->ship_address1 = $ship['CMLNE1'];
$this->ship_address2 = $ship['CMLNE2']!='' ? $ship['CMLNE2'] : NULL;
$this->ship_address3 = $ship['CMLNE2']!='' ? $ship['CMLNE3'] : NULL;
$this->ship_city = $ship['CMCITY'];
$this->ship_state = $ship['CMST'];
$this->ship_zip = $ship['CMZIP'];
$this->ship_country = $ship['CMCTRY'];
$this->bill_name = $bill['CMNAME'];
$this->bill_address1 = $bill['CMLNE1'];
$this->bill_address2 = $bill['CMLNE2']!='' ? $bill['CMLNE2'] : NULL;
$this->bill_address3 = $bill['CMLNE3']!='' ? $bill['CMLNE3'] : NULL;
$this->bill_city = $bill['CMCITY'];
$this->bill_state = $bill['CMST'];
$this->bill_zip = $bill['CMZIP'];
$this->bill_country = $bill['CMCTRY'];
Here is the definition of get_address:
private function get_address($key) {
$result = db_query('SELECT CMNAME, CMLNE1, CMLNE2,
CMLNE3, CMCITY, CMST, CMZIP, CMCTRY
FROM myTable
WHERE C1STKY = :key;',
array(':key' => $key));
$info = $result->fetch(PDO::FETCH_ASSOC);
return $info;
}
What are my alternatives for declaring these variables? I hate the big long lists of just variable declarations. Is there a more elegant way to declare these?
The way I ultimately fixed this problem was changing my class definition. Rather than having class properties for each address component, I simply changed my class definition to store the address as an associative array. It felt much cleaner that way.
Thus, the above code became
$this->shipping_address = $this->get_address($this->dealer_num);
$this->billing_address = $this->get_address($this->bill_to_num);

Categories