I'm trying to declare variables and arrays from a form (post) but it seems the arrays are not being processed:
// is this a better practise than directly pass the entire $_POST?
$list = array('use', 'type', 'status', 'bhk', 'baths', 'size', 'location', 'price', 'description');
foreach($list as $name) {
if ($name != 'description')
$var = "\$" . $name . "=filter_input(INPUT_POST, '" . $name . "', FILTER_SANITIZE_NUMBER_INT);";
else if ($name == 'description')
$var = "\$" . $name . "=filter_input(INPUT_POST, '" . $name . "', FILTER_SANITIZE_STRING);";
}
$area_1 = $size['area1'] != '' ? $size['area1'] : 0;
$area_2 = $size['area2'] != '' ? $size['area2'] : 0;
$city = $location['city'];
$zone = $location['zone'];
$sale = $price['sale'] != '' ? $price['sale'] : 0;
$rent = $price['rent'] != '' ? $price['rent'] : 0;
Could be that some of those inputs are long numbers? Like $price['sale'] (up to 999999) or $size['area1'] (up to 999). Since they don't need any unit type I prefer storing them as integers rather than strings. But tell me if the length is a problem.
EDIT: (FIX by #swidmann in comments)
$$name = filter_input(INPUT_POST, $name, FILTER_SANITIZE_NUMBER_INT);
Solution: (by #swidmann in comments)
$$name = filter_input(INPUT_POST, $name, FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)
To create variables from your array you should use $$ instead of concatenating a string an run eval(), because eval() is evil.
You can make variables like this:
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT ); with $$name you can define a variable with the name of the string content $name
If your input can be an array, please take a look at filter_input_array() or filter_input() with the option FILTER_REQUIRE_ARRAY, depends on what you need.
Here is an approach:
// is this a better practise than directly pass the entire $_POST?
$list = array( 'use', 'type', 'status', 'bhk', 'baths', 'size', 'location', 'price', 'description' );
foreach ( $list as $name ) {
if ( $name != 'description' ) {
if( is_array( $_POST[$name] ) ) {
// I think you should also check for other types if needed (i.e. string)
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT , FILTER_REQUIRE_ARRAY );
} else {
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_NUMBER_INT );
}
} else if ( $name == 'description' ) {
$$name = filter_input( INPUT_POST , $name, FILTER_SANITIZE_STRING );
}
}
$area_1 = $size['area1'] != '' ? $size['area1'] : 0;
$area_2 = $size['area2'] != '' ? $size['area2'] : 0;
$city = $location['city'];
$zone = $location['zone'];
$sale = $price['sale'] != '' ? $price['sale'] : 0;
$rent = $price['rent'] != '' ? $price['rent'] : 0;
if you are not sure about the input, you can try the option FILTER_DEFAULT:
$$name = filter_input(INPUT_POST, $name, FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)
Related
PHP Warning: Attempt to read property "SONGTITLE" on bool in
PHP Deprecated: addslashes(): Passing null to parameter #1 ($string) of type string is deprecated in /home2/radiosound/public_html/80s/assets/php/config.php on line 31
`function Streaming(){
global $radio;
$shoutcast = #simplexml_load_file("http://live.radiosoundfm.com.br:8398/stats?sid=1");
$music = htmlspecialchars(addslashes($shoutcast->SONGTITLE));
$singer = ''; $name = $music;
if(strpos($music, '-') !== false && substr_count($music, '-') == 1){
$data = explode('-', $music);
$singer = trim($data[0]) != '' ? trim($data[0]) : '';
$name = trim($data[1]) != '' ? trim($data[1]) : '';
}
$data = array(
'music' => $music,
'name' => $name,
'singer' => $singer
);
return $data;
}`
I have a filter for the CPT and I need to manually type all custom taxonomy names inside the array():
sc_render_filter(
'test',
'All Categories',
array( 'Category One', 'Category two', 'Category three'),
''
. ($current_sub_brand ? ( 'sub_brand=' . $current_sub_brand . '&' ) : '' )
. ($current_varietal ? ( 'varietal=' . $current_varietal . '&' ) : '' )
. ($current_publication ? ( 'publication=' . $current_publication . '&' ) : '' )
. ($current_vintage ? ( 'vintage=' . $current_vintage . '&' ) : '' )
);
Is it possible somehow to use the variable or foreach loop inside array() to automatically generate terms or names? Or maybe I need another approach?
This is what I have in foreach:
$source = '';
foreach ($termslist as $term) {
$source .= "'". $term->name. "'". ',';
}
echo rtrim($source, ',');
Unfortuntely for your project, it is appropriate to use variable variables (which I do not typically endorse). Using variable variables is a symptom that array data is not properly stored as such. The fact that you have individual $current_ variables looks to be an earlier problem to address.
In the meantime, you can loop through the know keys and dynamically access these variables. When finished, call http_build_query() to cleanly, reliably generate a url querystring string.
Code: (Demo)
$keys = ['sub_brand', 'varietal', 'publication', 'vintage'];
$data = [];
foreach ($keys as $key) {
$data[$key] = ${'current_' . $key};
}
$queryString = http_build_query($data);
sc_render_filter(
'test',
'All Categories',
['Category One', 'Category two', 'Category three'],
$queryString
);
The querystring string looks like this:
sub_brand=foo&varietal=bar&publication=boo&vintage=far
I am working on codeigniter and i am trying to use dynamic meta tag but meta tags not working for me, Here is my code in controller
$id = $this->uri->segment(2);
$data['id'] = $id;
$data['metas'] = array(
array('name'=>'description', 'content'=>'A short but sweet DEFAULT description of this fine site'),
array('name' =>'keywords', 'content'=>'some awesome DEFAULT keywords for those rascally web crawlers')
);
Here is my view
<?php
foreach($metas as $meta)
{?>
<meta name="<?=$meta['name']?>" content="<?=$meta['content']?>" />
<?php }?>
Just go inside codeigniter 3 system/helpers/html_helper.php and copy the function and put it in your own libraries
function meta($name = '', $content = '', $type = 'name', $newline = "\n")
{
// Since we allow the data to be passes as a string, a simple array
// or a multidimensional one, we need to do a little prepping.
if ( ! is_array($name))
{
$name = array(array('name' => $name, 'content' => $content, 'type' => $type, 'newline' => $newline));
}
elseif (isset($name['name']))
{
// Turn single array into multidimensional
$name = array($name);
}
$str = '';
foreach ($name as $meta)
{
$type = (isset($meta['type']) && $meta['type'] !== 'name') ? 'http-equiv' : 'name';
$name = isset($meta['name']) ? $meta['name'] : '';
$content = isset($meta['content']) ? $meta['content'] : '';
$newline = isset($meta['newline']) ? $meta['newline'] : "\n";
$str .= '<meta '.$type.'="'.$name.'" content="'.$content.'" />'.$newline;
}
return $str;
}
I made this Class with the function query():
This function makes it really easy to use prepared statements.
But
It is secure?
Make it even sense to use it like that?
I already tested it with sqlmap and it looks good.
The function basicly split the normal SELECT string into multiple smaller string to dedect the input values.
It save the input values and the string itself.
The string itself will be replaced by ?.
Than the normal prepare function replaces the ? again with the input values.
class dbcon
{
public $con;
public function __construct()
{
$this->con = new mysqli( $host, $username, $password, $dbname );
}
public function query( $query )
{
//selcet
if( strpos( $query, "SELECT" ) !== false )
{
$types = ""; $to_replace = []; $values = [];
$query = explode( "WHERE", $query );
$query_where = explode( "ORDER BY", $query[ '1' ] );
$query_where[ '0' ];
if( isset( $query_where[ '1' ] ) )
{
$ORDERBY = explode("LIMIT", $query_where[ '1' ]);
}
if( isset( $ORDERBY[ '1' ] ) )
{
$LIMIT = $ORDERBY[ '1' ];
}
$SELECT = $query[ '0' ];
$where = str_replace( array( "(", ")", "[", "]" ), "", $query_where[ '0' ] );
$where = str_replace( array( "AND", "OR", "and", "or" ), "-|-", $where );
$where = explode( "-|-", $where );
for ($i=0; $i < count($where); $i++) {
$for_where = str_replace( array( "!=", "<=", ">=", "=", "<>", ">", "<", "IS", "NOT LIKE", "LIKE" ), "#|#", $where[ $i ] );
$for_where = explode( "#|#", $for_where );
$value = trim( $for_where[ '1' ] );
if( substr_count($value, "AND") <= 0 AND substr_count($value, "OR") <= 0 )
{
$value = "'?'";
}
$to_replace[] = $value;
$value_num = "values".$i;
$$value_num = $value;
$values[] = &$$value_num;
$types .= "s";
}
$WHERE = str_replace( $to_replace , " ? ", $query_where[ '0' ] );
$prepare = $SELECT . " WHERE " . $WHERE;
if ( isset( $ORDERBY ) )
{
$prepare .= " ORDER BY " . $ORDERBY[ '0' ];
}
if ( isset( $LIMIT ) ){
$prepare .= " LIMIT " . $LIMIT;
}
$stmt = $this->con->prepare( $prepare );
//$stmt->bind_param($types, $values['0'],$values['1']);
call_user_func_array( array( $stmt, "bind_param" ), array_merge( array( $types ), $values ) );
$stmt->execute();
return $stmt->get_result();
$stmt->close();
}
}
}
$db = new dbcon();
Call the function:
$id = $_GET[ 'id' ];
$my_query = $db->query("SELECT * FROM Users WHERE ID = '$id' ORDER BY created DESC");
while($row = $my_query->fetch_array()){
echo $row['NAME']."<br>";
}
UPDATE:
The old function makes not a lot of sense and is not secure at all. This should be still a easy way but better.
public function query( $query, $types, $query_values )
{
$values = [];
for ($i=0; $i < count($query_values); $i++) {
$value_num = "values".$i;
$$value_num = $query_values[ $i ];
$values[] = &$$value_num;
}
$stmt = $this->con->prepare( $query );
call_user_func_array( array( $stmt, "bind_param" ), array_merge( array( $types ), $values ) );
$stmt->execute();
return $stmt->get_result();
$stmt->close();
}
call the function
$query = "SELECT * FROM _Users WHERE ID = ? ORDER BY created ASC";
$my_query = $db->query( $query, "s", array( $id ) );
while($row = $my_query->fetch_array()){
echo $row['title']."<br>";
}
You cannot by definition "prepare"/"sanitise"/understand a query after you have already interpolated values into it.
$my_query = $db->query("SELECT * FROM Users WHERE ID = '$id' ORDER BY created DESC");
So what happens here if someone attempts some SQL injection? E.g.: $id = "foo' OR '1' = '1":
SELECT * FROM Users WHERE ID = 'foo' OR '1' = '1' ORDER BY created DESC
How could any code following this possibly understand the difference between what this query was supposed to do and what it is actually doing now? It cannot. The meaning has already been altered through value injection. There's no way to fix this after the fact.
I'm trying to use str_replace to replace '' values to 'phone', I've used the code below but it isn't replacing anything:
<?php
$start_up = str_replace('','phone','start_up');
$sales = str_replace('','phone','');
$resourcing = str_replace('','phone','resourcing');
$management = str_replace('','phone','');
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
?>
I want this to come up with:
(start_up OR phone OR resourcing OR phone)
But instead it is doing this:
(start_up OR OR resourcing OR )
I know I can use a !isset($var) type query but this seems clunky and long winded. Is there a way to include blank strings in a str_replace query?
You can use preg_replace instead of str_replace:
$start_up = preg_replace('/^$/','phone','start_up');
$sales = preg_replace('/^$/', 'phone', '');
$resourcing = preg_replace('/^$/','phone','resourcing');
$management = preg_replace('/^$/','phone','');
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
Output:
(start_up OR phone OR resourcing OR phone)
and it will replace, an empty string with phone.
Edit: OR you can use empty() and ternary operator:
$start_up = empty('start_up') ? 'phone' : 'start_up';
$sales = empty('') ? 'phone' : '';
$resourcing = empty('resourcing') ?'phone' : 'resourcing';
$management = empty('') ? 'phone' : '';
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
Output same as above.