rapidash
rapidash

Reputation: 278

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

Upvotes: 1

Views: 2225

Answers (7)

JohnP
JohnP

Reputation: 50019

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.

Upvotes: 0

F.P
F.P

Reputation: 17831

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

Upvotes: 0

tereško
tereško

Reputation: 58444

Stop using $_REQUEST, because it is a combination of $_COOKIE , $_POST and $_GET. It becomes a security risk.

Upvotes: 1

Arjen
Arjen

Reputation: 1321

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

Upvotes: 1

kempsam
kempsam

Reputation: 56

Magic quotes? http://php.net/manual/en/security.magicquotes.php

Upvotes: 0

hsz
hsz

Reputation: 152216

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
  }
}

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86406

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.

Upvotes: 1

Related Questions