Define Array Values with Variables with php - 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.

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).

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);

Related

Sanitize JSON with php

I always use filter_var($var, FILTER, FLAG); when I get data from $_GET, $_POST and so on, but now this data is a JSON string but I didn't find any filter to sanitize JSON. Anyone know how to implement this filter?
PHP filter_var(): http://php.net/manual/en/function.filter-var.php
PHP FILTER CONST: http://php.net/manual/en/filter.filters.sanitize.php
Parse the JSON first into a PHP array and then filter each value in the array as you do with regular request content, you could map the JSON keys to schematic filters and flags/options e.g.
$filters = array(
'email'=>FILTER_VALIDATE_EMAIL,
'url'=>FILTER_VALIDATE_URL,
'name'=>FILTER_SANITIZE_STRING,
'address'=>FILTER_SANITIZE_STRING
);
$options = array(
'email'=>array(
'flags'=>FILTER_NULL_ON_FAILURE
),
'url'=>array(
'flags'=>FILTER_NULL_ON_FAILURE
),
//... and so on
);
$inputs = json_decode($your_json_data);
$filtered = array();
foreach($inputs as $key=>$value) {
$filtered[$key] = filter_var($value, $filters[$key], $options[$key]);
}
You use filter_var_array for this:
$inputs = filter_var_array( json_decode( $your_json_data, true ), [
'email' => [ 'filter' => FILTER_VALIDATE_EMAIL,
'flags' => FILTER_NULL_ON_FAILURE ],
'url' => [ 'filter' => FILTER_VALIDATE_URL,
'flags' => FILTER_NULL_ON_FAILURE ],
'name' => FILTER_VALIDATE_NAME,
'address' => FILTER_SANITIZE_STRING
] );

How to insert data from a single form to multiple tables in codeigniter framework ? - below method is not working

Anyone know how to insert data from a single form to multi tables in codeigniter
i tried below method but it is not working
Model
function add_models(){
$data1 = array(
'companykeyid' => $this->input->post('ckeyid'),
'name' => $this->input->post('name'),
'age' => $this->input->post('age'),
);
$data2 = array(
'companykeyid' => $this->input->post('ckeyid'),
'phrase' => $this->input->post('phrase'),
'medialength' => $this->input->post('medialength'),
);
$data3 = array(
'companykeyid' => $this->input->post('ckeyid'),
'phrase' => $this->input->post('phrase')
'medialength' => $this->input->post('medialength'),
);
$this->db->insert('girls', $data1);
$this->db->insert('movies',$data2);
$this->db->insert('keywords',$data3);
}
Method you made is, actually working, i think that your problem is syntax error you have (missing comma in data3 array).
So, this should work:
function add_models(){
$data1 = array(
'companykeyid' => $this->input->post('ckeyid'),
'name' => $this->input->post('name'),
'age' => $this->input->post('age')
);
$data2 = array(
'companykeyid' => $this->input->post('ckeyid'),
'phrase' => $this->input->post('phrase'),
'medialength' => $this->input->post('medialength')
);
$data3 = array(
'companykeyid' => $this->input->post('ckeyid'),
'phrase' => $this->input->post('phrase'),
'medialength' => $this->input->post('medialength')
);
$this->db->insert('girls', $data1);
$this->db->insert('movies',$data2);
$this->db->insert('keywords',$data3);
}
Important - you have to be sure that field names in tables are right... If this doesn't work, your problem is somewhere else in code (check your controller, view...)
In the array, you call the last value don't have "," get read of it and your model working correctly.
$data1 = array(
'companykeyid' => $this->input->post('ckeyid'),
'name' => $this->input->post('name'),
'age' => $this->input->post('age') <-----
);
In sinisake's answer shouldn't:
function add_models()
be chaged to:
function add_models($data)
Seems like there will be data to pass from the controller.

Converting undefined indexes to null in PHP

I'm not sure if the title of this question is necessarily the accurate description of what I need to do, but I'll go ahead and ask my question and see what everyone thinks...
Basically, I am receiving data from a source that I have no control over, and I need to transpose it into a suitable format for inserting into my database using CakePHP. So, here's how I'm doing it:
public function submitApp($data) {
$array = array(
'Student' => array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'address' => $data['address'],
'dob' => $data['dob'],
'gender' => $data['gender']
),
'Application' => array(
'course_id' => $data['course_id'],
'question1' => $data['question1'],
'question2' => $data['question2'],
'question3' => $data['question3'],
'question4' => $data['question4'],
),
'ApplicationQualification' => $data['Qualifications']
);
// Logic to save $array goes here
}
The problem is that sometimes not all of the keys in $data will be submitted to my app but I still want my app to work with what it gets.
I know that I can wrap each key in a conditional like this:
if (!isset($data['name'])) { $data['name'] = null; }
...and then building the array, but this seems like a pretty clumsy way of doing it. Is there a more efficient way to do this?
You could use a simple ternary statement
'name' => array_key_exists('name', $data) ? $data['name'] : null
Alternatively, you can set up a default array and then merge the given values in
$defaults = [
'name' => null,
'email' => null,
// etc
];
$data = array_merge($defaults, $data);

Dynamically add fields to http_build_query

I have built an API that I want to test. By that reason I'm building a simple client to try out the different features (CRUD). Below is the function for updating a producer, which works fine. However, I also want to be able to update parts of a producer, e.g. address (/producers/8?method=put&address=milkyway).
The array producer always contains the same elements (name, address, zipcode etc) but I only want to update the producer with the elements in the array which contains of anything. What I mean with that is that if for example the name element in the array is empty then name shouldn't be included in *http_build_query*. If only the name element contains of anything then only name should be updated.
So, let's say that the array (except for id that of course is mandatory) contains of address. How can I dynamically add only that to *http_build_query* ?
Thanks in advance!
public function UpdateProducer($producer) {
$url = 'http://localhost/webbteknik2/Labb2/api/v1/producers/ . $producer['id'] . '?method=put';
$data = http_build_query(array(
'name' => $producer['name'],
'address' => $producer['address'],
'zipcode' => $producer['zipcode'],
'town' => $producer['town'],
'url' => $producer['url'],
'imgurl' => $producer['imgurl'],
'latitude' => $producer['latitude'],
'longitude' => $producer['longitude'],
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
...
the rest of the curl code
}
Note: I know this is bad coding in many ways, but as I said I only, asap want to be able to test the CRUD functionality through the client.
use array_filter to remove the empty elements....
$params = array(
'name' => $producer['name'],
'address' => $producer['address'],
'zipcode' => $producer['zipcode'],
'town' => $producer['town'],
'url' => $producer['url'],
'imgurl' => $producer['imgurl'],
'latitude' => $producer['latitude'],
'longitude' => $producer['longitude'],
);
$data = http_build_query(array_filter($params, 'is_null'));

Codeigniter Escaping Data

I am using the following code to allow me to add data to my db but it seems the $this->db->escape();is not working as I can add html tags and they will run in the view :(
Code:
$this->form_validation->set_rules('aPartyLocation','A Party Location', 'required|trim|prep_for_form|max_length[35]|xss_clean');
$this->form_validation->set_rules('aPartyPhone','A Party Phone', 'required|trim|numeric|max_length[35]|xss_clean');
if($this->form_validation->run() === TRUE)
{
$userData = array(
'location' => $this->input->post('aPartyLocation', TRUE),
'phone' => $this->input->post('aPartyPhone', TRUE));
$this->db->escape($userData);
$this->party_model->addAParty($userData);
Update:
Controller:
$userData = array(
'id' => $id,
'location' => html_escape($this->input->post('aPartyLocation', TRUE)),
'phone' => html_escape($this->input->post('aPartyPhone', TRUE))
);
Model:
function addAParty($userData = NULL)
{
$this->db->insert('aParty',$userData);
return TRUE;
}
I would recommend you use CodeIgniter's Active Record class. This automatically escapes data for you.
For example, an insert statement would look like:
$this->db->insert('yourTable',array(
'location' => $this->input->post('aPartyLocation',TRUE),
'phone' => $this->input->post('aPartyPhone')
));
The second argument, is an array where the keys correspond to the columns in your database.
Edit
I believe Active Record only sanitizes data for SQL injection attacks. Passing the second parameter to $this->input->post() as TRUE protects your from XSS attacks. However, neither of those escape HTML tags. For that, you can use the htmlspecialchars function.
$this->db->insert('yourTable',array(
'location' => htmlspecialchars($this->input->post('aPartyLocation',TRUE)),
'phone' => htmlspecialchars($this->input->post('aPartyPhone'))
));
$location = $this->input->post('aPartyLocation',TRUE);
$phone = $this->input->post('aPartyPhone');
$this->db->insert('yourTable',array(
'location' => htmlspecialchars($location),
'phone' => htmlspecialchars($phone)
));

Categories