Easy way to control all inputs? - php

I have in mysql table 98 fields, and I am trying to make all inputs $_POST and control it if they are numeric etc.
Is there any easy way to type that or I need make all inputs like this one:
$age = $db->real_escape_string(trim($_POST['age']));
Thanks

You can use array_map.
$_POST = array_map(function($item){
return $db->real_escape_string(trim($item));
},$_POST)

please provide perfect scenario what you want to do?
if u try to escape all $_POST field than simplay loop $_POST and store back it's value in $_POST appropriate key than you got filter value.
eg.
foreach($_POST as &$key => $post){
$key = $db->real_escape_string(trim($post));
}

Related

How to put textbox value into array only if it has value?

I have created many textboxes and I want to put all of the values into array only if they have themselves filled. I need them to work as how checkbox works in HTML (only the checked ones will then put into array). I use PHP language here. How to do that?
This is my simple HTML textbox:
<input name="array[]">
Would really appreciate for any help you give to me. Much thanks!
Firstly, I'd recommend you change your name to something more readable:
<input name="name[]">
Next, you want to get your data, I am assuming your form is using POST. We're going to store the form data into a $names array variable.
$names = $_POST['name'];
Next, we're going to create a new array variable which will store input values that have data.
$namesWithData = [];
We're now going to loop through the $names array. This loop will add any fields with data to the $namesWithData array.
foreach($names as $name) {
if(!empty($name) {
array_push($namesWithData, $name);
}
}
The $namesWithData array has the data ready to use.

Use $_POST values by number

i'm not sure how to explain it correctly, but i would like to use $_POST values like this $_POST[0] and not like this $_POST['form_field_name'].
Let's say i have 3 form fields so if i'd like to get data from post like this:
echo $_POST[0];
echo $_POST[1];
echo $_POST[2];
I hope you guys understand what i wanna do here.
Try it like this:
$values = array_values($_POST);
No idea why you would do such a thing though.
I would not recommend ever to refer to your $_POST values with indexes, as it is generally a bad idea.
You can access them by indexes if you do this:
$items = array_values($_POST);
$foo = $items[0];
$bar = $items[1]
You can also run through your values with a foreach loop, like this (which is better, but still bad!)
foreach($_POST as $item)
{
// do your thing here
}
$_POSTs variables depends on the name attribute of the form element as you can read in this link.
On the other hand the attribute name of the form elements according to W3C always must begin with a letter.
But I think you can prepare the $_POST variable before all your code (at the begining of your php script) with:
$arrPostVariables = array_values($_POST);
And then call them in the way as you want, but I think you will previously must detect the order of the array in order to avoid errors by not having the text of each variable.
This should work:
<input name="0" value="val0" />
<input name="1" value="val1" />

getting all the keys for a map such as $_POST

For example, say I post some data to a php file, but I don't know what the names of those values are. Where I would normally perform $_POST["username"] or something similar. How would I go about getting a list of all the key/value pairs within $_POST
array_keys($_POST) will give you the array keys.
You can also do this to get values with key names:
foreach ($_POST as $key => $value)
{
//do stuff;
}
However!!! Why wouldn't you know what keys are in the post? You don't want hackers putting random stuff into a post, sending it to you, and processing away. There is nothing preventing them from putting in 1000s of entries.
Use array_keys to obtain all keys in $_POST super global array:
array_keys($_POST)
Simple example:
foreach (array_keys($_POST) as $key)
{
print $_POST[$key];
}

PHP Variables made with foreach

I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.
For example if i have
$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];
I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:
$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';
NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.
Is this possible?
You don't need a loop, you want extract:
extract($_POST); // But use caution, see below
Cautions and best practices
As noted in the comments this forces all parameters in the $_POST array into the current symbol space.
In global space
<?php
extract($_GET);
var_dump($_SERVER); // Can be overwritten by the GET param
?>
The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.
Inside a function
function myFunc() {
// (Mostly) empty symbol space! (excluding super globals)
extract($_POST);
}
Inside a function, as the first line, no harm done.
Important note: You might think since $_SERVER is a super global, that this exploit could happen inside a function as well. However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither $_SERVER, $_POST, $_GET, $_SESSION, or presumably other superglobals, could be overwritten.
With options
You can also use extract with extract_type options that do not overwrite.
The best option to use, in my opinion, is simply to prefix all variables from extract:
// $_GET = test=1&name=Joe
extract($_GET, EXTR_PREFIX_ALL, "request_get");
echo $request_get_test; // 1
echo $request_get_name; // Joe
That way you don't have the overwrite problem, but you also know you got everything from the array.
Alternate - looping w/ conditional
If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:
foreach ($_POST as $key => $value) {
if (isset($$key)) continue;
$$key = $value;
}
(The example condition I've used is an overwrite prevention.)
Try not to use extract() when using $_POST. You may overwrite variables you want which will result in unpredictable behaviour. It is a bad habit to get into and while is dynamic may not be the best solution.
You can do something like this:
foreach($_POST as $key => $value)
{
switch($key)
{
case "name":
$name = $value;
break;
case "last":
$last = $value;
break;
}
}
You can actually use the built-in function called extract
Why not use a foreach?
foreach($_POST as $key=>$val){
${$key} = $val;
}
I just want to mention that you can improve foreach technique because we have in HTML the ability to name one of our form fields using square bracket notation, and if we do that, what HTML will do is it will submit a series of values as an array.
<input name="user[name]">
<input name="user[last]">
<input name="user[age]">
<input name="user[sex]">
Than use just one line of code to assign all values from input fields into local array $args.
$args = $_POST['user'];
So what that means is when we go to process the form, we're looking at an array of values instead of a bunch of single values that we have to go retrieve.
So we can just simply go to the post super global and ask for one item: that is user. And what we get back is an associative array. So instead of having to build up that array by going and retrieving all those values one at a time, we're instantly given an array, just because we named our form fields differently.

Using extract

I'm new to OOP and want to revamp this function to get rid of using globals.
function CatchListing() {
$parseform = array('itemnum','msrp','edprice','itemtype','box','box2','box25','box3','box4','box5','box6','box7','itemcolor','link');
foreach ($parseform as $globalName) {
$GLOBALS[$globalName] = mysql_real_escape_string($_POST[$globalName]);
}
}
I was told to use array_map & then extact, but I am not sure of how to structure this.
function CatchListing() {
$_POST['listing'] = array_map('mysql_real_escape_string', $_POST);
$nst = extract($_POST['listing']);
}
(listing is the form name btw)
Thanks
Be VERY careful about using extract with externally inputted values as from $_GET and $_POST.
you're much better off extracting the values manually to known values.
It's far too easy for an extract from _GET or _POST to clobber existing variables.
There are so many things to say and Jonathan makes a very good start. Every time the user has the opportunity to play with your internal data and you don't check them, there is a huge "opportunity" (depends on the view..) that something goes wrong. Here is another approach on how to "maybe" get where you want to go:
<?php
function Sanitize($string){
return mysql_real_escape_string(trim($string));
}
function CatchListing(){
foreach($_POST as $key => $value) {
$key = Sanitize($key);
$value = Sanitize($value);
if($key && $value && !$GLOBALS[$key]){ /* prevent overwriting existing globals*/
$GLOBALS[$key] = $value;
}
}
}
global $nice;
$nice = "working";
CatchListing();
print_r($GLOBALS);
?>
To be honest, it still has not really anything to do with OOP and furthermore should be seen as a procedural approach. Personally I would use an additional and reusable function to "sanitize" the input, because you never know, if someday you want to change your database or the "escape" function and then you exactly know where to look for possible changes. Ah one more thing: Are you certain that you don't know all the possible names of all the variables you have to expect? Maybe you can predetermine them and put them in another array and check each user supplied argument with in_array.
To completely get rid of the usage of globals in your code, and also to make it much better overall, you can do something along these lines:
stop using $_POST, as it's a superglobal. When code needs values from superglobals, pass them as parameters
don't store values into $GLOBALS. If you need to return more than one value, consider returning an object or an array
Here's how I think I would modify your code to improve it:
function CatchListings($listings) {
$filteredListings = array_map('mysql_real_escape_string', $listings);
//I assume you only need the values in the array in the original snippet,
//so we need to grab them from the parameter array and return only that
$requiredListings = array();
$requiredKeys = array('itemnum','msrp','edprice','itemtype','box','box2','box25','box3','box4','box5','box6','box7','itemcolor','link');
foreach($requiredKeys as $key) {
$requiredListings[$key] = $filteredListings[$key];
}
return $requiredListings;
}
To use this function, you simply do $result = CatchListings($_POST);. Same result, no globals used.
There is one thing to consider, though. It may not be best possible form to just pass a randomly filled array (ie. $_POST) to the function, and expect it to contain specific keys (ie. $requiredKeys array). You might want to either add logic to check for missing keys, or process the post array before passing it.

Categories