Zendframework - mysql injection how to protect - php

If I use methods e.g. insert, update in ZF Will I be safe(mysql injection)?
for example a part of code:
$data = array(
'autor' => $autor,
'title' => $title,
'text' => $text,
'date' => $date,
);
$news = new News();
$news->insert($data); // safe?

Similar question here:
How to prevent SQL Injection attack in applications programmed in Zend Framework?
Always make sure you sanitize user input values using mysql_real_escape_string

I think it will be fine just the way you have it. I mean one of the advantages of using PDO ext is to prevent SQL injections using PHP instead of MySQL to query the database.
Here is more from devzone.zend.com

It's fine the way you are doing it. But be careful with mysql-expressions. There you should use a Zend_Db_Expr-Object:
$data = array(
'author' => 'John Doe',
'title' => 'Headline goes here',
'text' => 'The content...',
'date' => new Zend_Db_Expr('NOW()') // <--- use this for SQL-Expressions
);
$news = new News();
$news->insert($data);

Related

working with mongoDB and PHP (Laravel)

I'm working with mongoDB and PHP (Laravel) and finding alot of difficulties in executing the complex queries on PHP (Laravel), all queries working smoothly on mongo Booster but when I execute them on PHP (Laravel) it really gives me tough time. Can any one help me out how could I execute them like raw queries on PHP (Laravel).
Raw queries in Laravel
Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Another Example
$result = DB => collection('PMS')->raw(function ($collection){
return $collection->aggregate(array(
array( '$match' => array( "PanelID" => "A00898" ) ),
array( '$project' => array( 'EventTS' => 1, 'MainsPower' => 1 ) ),
array(
'$unwind' => array(
'path' => "$MainsPower",
'includeArrayIndex' => "arrayIndex",
'preserveNullAndEmptyArrays' => true
)
),
array(
'$project' => array(
'_id' => 0,
'MainsPower' => 1,
'timestamp' => array(
"$add" => array(
"$EventTS",
array( "$multiply" => array( 60000, "$arrayIndex" ) )
)
)
)
)
));
});
Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:
$result = DB::select(
DB::raw('your query here')
);
Reference
Yes answers given by other is right but raw queries performing in Laravel is not good practice. Then why you are using Laravel Framework. You should use eloquent because if you change the db like mysql instead of mongo you need not to change quires. That's the power of Eloquent ORM.

How to return a specific output to a variable using raw query in cakephp

I have a variable which needed a value from a specific query
$player_id_owner = $this->Player->fetchAll('Select id from player
where name = ?', array($name));
$player_id_owner = ($this->Player->find('all', array(
'fields' => array('id'),
'conditions' => array('Player.name' => '$name')
)));
i tried both raw query and cakephp find but both of them returns only "array"
have i forgotten something? how can i access the expected result from query? thanks
Well
'Player.name' => '$name'
is not valid PHP code, at least not for what you try to do.
Don't escape variables as strings:
'Player.name' => $name
You could have easily seen that by checking the resulting query in the debug kit or the bottom of the view.
And most likely you would want to use find('first', ...) as documented if you only expect a single entry here.
Last but not least:
You most likely just lack basic debugging skills. Don't echo it, as it is indeed an array. Never do that with unknown variables as they often are everything but a basic string.
Use debug() to see whats inside and then properly echo what you see, e.g. echo $player['Player']['name'];.
Bear in mind that stringish output should be secured by h() on output:
echo h($player['Player']['name']);
try this
$player_id_owner = $this->Player->find('first', array(
'fields' => array('id'),
'conditions' => array('Player.name' => $name)
));
or try (you can also use your variable instead of yourname)
'conditions' => array('Player.name LIKE' => "%yourname%")
after that you can get the id with
$player_id_owner['Player']['id']

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

SQL to MongoDB?

I like to implement
"SELECT * FROM TABLE_NAME
WHERE
name like '$query_string' or
title like '%$query_string%' or
tags like '%$query_string%'"
to mongoDB, and I tried
$condition = array('$or' =>
array('writer'=> array('name'=>"$query_string"),
'title'=> new MongoRegex("/$query_string/"),
'tags' => new MongoRegex("/$query_string/") ));
and this does not work.
What is proper way to implement that SQL to mongoDB?
Here's how I construct a case-insensitive, "contains" term
$containsTerm = new MongoRegex(sprintf('/%s/i', preg_quote($term, '/')));
So your condition might look like
$condition = array('$or' => array(
'writer.name' => $term,
'title' => $containsTerm,
'tags' => $containsTerm
));
Apologies if the condition array is wrong, I typically use the Doctrine ODM

How do I do batch updates?

How can I do batch updates in CodeIgniter instead of firing query each and every time in database?
Mysql can do multiple updates or inserts. Usually in an Active Record pattern you do inserts one by one, but for bulk updates or inserts you can do this.
$sql = "INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12) ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);";
$this->db->query($sql);
CodeIgniter's active record class has an insert_batch() method that does just this and takes care of escaping the data.
$data = array(
array('name' => 'John', 'email' => 'john#email.com'),
array('name' => 'Sue', 'email' => 'sue#email.com')
);
$this->db->insert_batch('my_table', $data);
http://codeigniter.com/user_guide/database/active_record.html
For the sake of other old-fashioned Code Igniter users (like myself):
You’re using an old version? insert_batch and update_batch have been around for over a year [Sep/2010]. If you’re not going to upgrade you would have to run an insert query for each row, or manually construct a batch insert statement.
From: http://codeigniter.com/forums/viewthread/188416/#891199
This question was about updates, but the accepted answer is for inserts.
Here is how you do a batch update:
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
This example is from the CodeIgniter user guide:
http://ellislab.com/codeigniter/user-guide/database/active_record.html#update

Categories