Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP | Get input name through $_POST[]

HTML example:

  <form method="post" id="form" action="form_action.php">
    <input name="email" type="text" />
  </form> 

User fills input field with: [email protected]

echo $_POST['email']; //output: [email protected]

The name and value of each input within the form is send to the server. Is there a way to get the name property? So something like..

echo $_POST['email'].name; //output: email

EDIT: To clarify some confusion about my question;

The idea was to validate each input dynamically using a switch. I use a separate validation class to keep everything clean. This is a short example of my end result:

//Main php page
if (is_validForm()) {
    //All input is valid, do something..
}

//Separate validation class    
function is_validForm () {
    foreach ($_POST as $name => $value) {
        if (!is_validInput($name, $value)) return false;
    }
    return true;
   }

function is_validInput($name, $value) {
    if (!$this->is_input($value)) return false; 

    switch($name) {
        case email: return $this->is_email($value);  
        break;
        case password: return $this->is_password($value);
        break;
//and all other inputs
        }
    }

Thanks to raina77ow and everyone else!

like image 603
user1178560 Avatar asked Nov 14 '12 11:11

user1178560


People also ask

What is $_ POST [] in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

How can get input field value in PHP variable?

Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.

How can you access form data sent to PHP via a POST request?

Code explained $_POST['firstname']: The form data is stored in the $_POST['name as key'] variable array by PHP since it is submitted through the POST method, and the element name attribute value – firstname (name=”firstname”) is used to access its form field data. The same procedure is used for $_POST['lastname'].

Is $_ POST an array?

The PHP built-in variable $_POST is also an array and it holds the data that we provide along with the post method.


2 Answers

You can process $_POST in foreach loop to get both names and their values, like this:

foreach ($_POST as $name => $value) {
   echo $name; // email, for example
   echo $value; // the same as echo $_POST['email'], in this case
}

But you're not able to fetch the name of property from $_POST['email'] value - it's a simple string, and it does not store its "origin".

like image 149
raina77ow Avatar answered Oct 06 '22 00:10

raina77ow


foreach($_POST as $key => $value)
{
 echo 'Key is: '.$key;
 echo 'Value is: '.$value;
}
like image 33
DonCallisto Avatar answered Oct 05 '22 22:10

DonCallisto