rivitzs
rivitzs

Reputation: 499

Define Array Values with Variables with php

I am using $_POST to post data to a php file. In that php file, I have the following.

$params = array(
        'name' => "$fname",
        'email' => "$email",
        'ad_tracking' => 'test',
        'ip_address' => '$_SERVER["REMOTE_ADDR"]',
    );
    $subscribers = $list->subscribers;
    $new_subscriber = $subscribers->create($params);

What is the best way to use the $_POST data to define the vales of each keys in the array? The use of $_SERVER["REMOTE_ADDR"] is also not working as hoped.

Upvotes: 0

Views: 4751

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

POST variables are passed via the super global array $_POST in PHP. So in your case, this would technically work:

$params = array(
    'name' => $_POST['fname'],
    'email' => $_POST['email'],
    'ad_tracking' => 'test',
    'ip_address' => $_SERVER['REMOTE_ADDR'],
);

Your code for $_SERVER["REMOTE_ADDR"] was enclosed in single quotes, which in PHP means a verbatim string (i.e. without variable interpolation).

Btw, you should think of input filtering too - http://www.php.net/filter

To give you an example, this would perform input filtering in your current case:

$filtered = filter_input_array(INPUT_POST, array(
    'fname' => FILTER_SANITIZE_STRING,
    'email' => FILTER_VALIDATE_EMAIL,
);

Each value inside $filtered will either have a value (valid), be NULL (not present) or false (invalid).

Upvotes: 1

Kep
Kep

Reputation: 5857

Regarding "the use of $_SERVER["REMOTE_ADDR"] is also not working as hoped.": Single-Quotes don't evaluate php variables

$params = array(
    'name' => $_POST["fname"],
    'email' => $_POST["email"],
    'ad_tracking' => 'test',
    'ip_address' => $_SERVER["REMOTE_ADDR"],
);
$subscribers = $list->subscribers;
$new_subscriber = $subscribers->create($params);

Upvotes: 0

Related Questions