Cycle through $_POST variables and modify undefined with PHP - php

I want to look through my PHP $_POST variables and change anything that is "undefined" (because of how jQuery is sending it) to "" or at least " " so that when the email form is submitted it doesn't say "undefined" wherever the value wasn't filled out (optional fields).
Thanks!

I recommend you consider altering your javascript to handle the undefines better, BUT..
Here is a no loops approach to do it:
$_POST = unserialize(str_replace('s:9:"undefined";', 's:0:"";', serialize($_POST)));
There is also the more typical approach of using a single loop like so:
foreach($_POST as &$p) if($p=='undefined') $p = '';
Note: The serialize + unserialize approach is cool in that is does not use a loop, but the loop approach is probably slightly faster, especially when $_POST is large.

In PHP if you use an & symbol in an foreach loop it will use it as a reference instead of a value. Changing a reference will set the original value.
<?php
$_POST['text1'] = 'undefined';
$_POST['text2'] = 'undefined';
foreach($_POST as &$var)
{
if($var == 'undefined')
$var = '';
}
print_r($_POST);
?>
<!-- Will output -->
array(
text1=>
text2=>
)

if (isset($_POST['var'])) {
// it is set
} else {
// it isnt set
}

foreach ($_POST as &$var) {
if ($var === 'undefined') {
$var = '';
}
}

Related

Create php variable from HTML post name and value

I have a large HTML form posting many fields to a PHP page. I'm assigning all those fields to PHP variables one by one. Is there a way to put to create a function to auto assign the POST value to a PHP variable?
This is my code now:
if (!empty($_POST["x"])) {
$x = clean_post($_POST["x"]); }
if (!empty($_POST["y"])) {
$y = clean_post($_POST["y"]);
}?>
Thanks!
You can do this using the array_keys() function and a foreach-loop like this:
foreach (array_keys($_POST) as $key) {
${$key} = $_POST[$key];
}
But why not use the $_POST array in the first place?
Yes, but it's a rubbish idea. They actually had this in PHP, but removed it. It was called register_globals. So for instance, $_POST['name'] would automatically have $name created.
If you insist on this terrible idea, you should be able to do it like this:
foreach ($_POST as $key => $value) {
$$key = $value;
}
Don't do it though! Read this for more info https://secure.php.net/manual/en/security.globals.php

Put $_GET parameter in php variable

Is it possible to take $_GET parameter from the url and put it in php variable without using foreach?
If I do:
var_dump($_GET);
I will get the result:
array(1) { ["block_simple_clock"]=> string(0) "" }
I need to put that value block_simple_clock in a string variable, and I can do that with a foreach:
foreach($_GET as $key => $value) {
var_dump($key);
}
But I would really like to take that value without a foreach if it is possible. I hate using foreach for such a trivial problem :)
Sorry for confusion, that block_simple_clock is a variable, and it can be a different value, I am sending this value with this code:
foreach ($pluginlist->plugins as $key => $plugin) {
if (empty($plugin->component)) {
continue;
}
if (in_array($plugin->component, $arr)) {
if (!in_array($plugin->component, $contribs)) {
$target_url = new moodle_url('redirect.php');
$mform->addElement('advcheckbox', $plugin->component, "<a href={$target_url}?$plugin->component target='_blank'>" . $plugin->name . "</a>", '', array(0, 1));
}
}
$requestedPluginIdCounter++;
}
As you can see the $plugin->component is the value that I am sending via $_GET.
$variable = $_GET['block_simple_clock'];
OR
$variable = $_REQUEST['block_simple_clock'];
If you know exactly which ones you need, you can use
$var = $_GET['name-in-get'];
You mays want to use the function
extract( $_GET );
Which creates global variables with the name of the key :
//suppose GET = $_GET['name']
extract( $_GET );
echo $name; //will echo $_GET['name']
Remember to ALWAYS filter gets and posts values, since they are user input (obviously it depends what you do with them, but especially if they're used for database purposes, it is extremely important)
For more information, see filter_input function
You can do this :
$t = array_keys($_GET);
echo $t[0];
Thank you guys, I have added a name=$plugin->component, and was able to extract the variable with that $_GET["name"] :)

PHP take string and check if that string exists as a variable

I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>

Any easier way to do $name = $_REQUEST["name"];?

So I'm new to PHP and am trying to create a form. I accept a bunch of parameters and want to process them in the same page. I'm not sure how to do this without a giant if-else containing the entire page as if($_POST). This doesn't seem ideal.
In addition, I'm finding that I do the following a lot. Is there any way to shorten this? The names all remain the same.
$name = $_REQUEST["name"];
$gender = $_REQUEST["gender"];
$age = $_REQUEST["age"];
And I have a lot of lines which are just doing that, and it seems terribly inefficient
You can use the extract() function to do that. But it has a security downside: existing variables can be overwritten if someone would add variables to the POST header.
Edit: hsz's solution is better
What process you are doing with if..else..if you have to post the code so that we can let you know how that can be shorten.
you can avoid the assignment for each variable using extract function.
extract($_POST);
But be aware that can overwrite your existing variable if the are named same as your input controls.
Stop using $_REQUEST, because it is a combination of $_COOKIE , $_POST and $_GET.
It becomes a security risk.
Instead of using $_REQUEST you should use $_POST here.
$keys = array('name', 'gender', 'age');
foreach ( $keys as $key ) {
if ( isset($_POST[$key]) ) {
$$key = $_POST[$key];
}
// optional:
else {
$$key = ''; // default value
}
}
Magic quotes? http://php.net/manual/en/security.magicquotes.php
For the first thing: Turn it around. Don't do
if ($_POST) {
// Your handling code
} else {
echo "No data!";
}
do
if (!$_POST) {
die("No data!");
}
// Your handling code
You can use extract(), however, this means that you're bringing in a lot of variables that you (might not know about) int your current scope.
My suggestion would be to loop through your array and do something with the variables in there (e.g. - validation)
foreach ($_POST as $key => $valu) {
//do something with the variables
}
Also, don't use $_REQUEST unless you really want to check $_GET, $_POST and $_COOKIE. Use the proper array when accessing variables or people can send data you don't expect.

PHP - Convert all POST data into SESSION variables

There's got to be a much more elegant way of doing this.
How do I convert all non-empty post data to session variables, without specifying each one line by line? Basically, I want to perform the function below for all instances of X that exist in the POST array.
if (!empty($_POST['X'])) $_SESSION['X']=$_POST['X'];
I was going to do it one by one, but then I figured there must be a much more elegant solution
I would specify a dictionary of POST names that are acceptable.
$accepted = array('foo', 'bar', 'baz');
foreach ( $_POST as $foo=>$bar ) {
if ( in_array( $foo, $accepted ) && !empty($bar) ) {
$_SESSION[$foo] = $bar;
}
}
Or something to that effect. I would not use empty because it treats 0 as empty.
The syntax error, is just because there is a bracket still open. it should be
$vars = array('name', 'age', 'location');
foreach ($vars as $v) {
if (isset($_POST[$v])) {
$_SESSION[$v] = $_POST[$v];
}
}
It should work like that. If you use
if ($_POST[$v])...
it strips down empty data.
Here you go,
if(isset($_POST) {
foreach ($_POST as $key => $val) {
if($val != "Submit")
$_SESSION["$key"] = $val;
}
}
Well the first thing I would suggest is you don't do this. It's a huge potential security hole. Let's say you rely on a session variable of username and/or usertype (very common). Someone can just post over those details. You should be taking a white list approach by only copying approved values from $_POST to $_SESSION ie:
$vars = array('name', 'age', 'location');
foreach ($vars as $v) {
if (isset($_POST[$v]) {
$_SESSION[$v] = $_POST[$v];
}
}
How you define "empty" determines what kind of check you do. The above code uses isset(). You could also do if ($_POST[$v]) ... if you don't want to write empty strings or the number 0.
This lead me to this bit, which is a simplified version of #meder's answer:
<?php
$accepted = array('foo', 'bar', 'baz');
foreach ( $accepted as $name ) {
if ( isset( $_POST[$name] ) ) {
$_SESSION[$name] = $_POST[$name];
}
}
You might also substitute !empty() for isset() above, though be aware of how much farther-reaching empty() is, as #meder pointed out.
$_SESSION["data"] = $POST;
$var = $_SESSION["data"];
Then just use $var as a post variable. For example:
echo $var["email"];
instead of
echo $_POST["email"];
Cheers

Categories