From 4d01642a8969312525b73338b17f6c96178c4b2b Mon Sep 17 00:00:00 2001 From: Don MacAskill Date: Mon, 5 Jan 2015 11:09:42 -0800 Subject: [PATCH 1/2] Fix comment error around UTF-8 and PDO --- _posts/05-05-01-PHP-and-UTF8.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_posts/05-05-01-PHP-and-UTF8.md b/_posts/05-05-01-PHP-and-UTF8.md index 0066fba..467e0df 100644 --- a/_posts/05-05-01-PHP-and-UTF8.md +++ b/_posts/05-05-01-PHP-and-UTF8.md @@ -86,7 +86,7 @@ $string = mb_substr($string, 0, 15); // Connect to a database to store the transformed string // See the PDO example in this document for more information -// Note the `set names utf8mb4` commmand! +// Note the `charset=utf8mb4` in the Data Source Name (DSN) $link = new PDO( 'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4', 'your-username', From 3b393c2c4b67c02d0e69a45a69924102b57ec537 Mon Sep 17 00:00:00 2001 From: Don MacAskill Date: Mon, 5 Jan 2015 11:43:35 -0800 Subject: [PATCH 2/2] Fix PDO not using input filtering in example Somehow, this pull request (https://github.com/codeguy/php-the-right-way/pull/26) went missing in the move to `gh-pages`. But it's fairly critical, since the example has `$_GET` being passed straight into a `PDO` statement. On a write (`INSERT` or `UPDATE`), this can still result in dangerous data (to the app, not to SQL) being written accidentally by a new PHP developer. Data should always be filtered prior to use. --- _posts/07-03-01-Databases_PDO.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/_posts/07-03-01-Databases_PDO.md b/_posts/07-03-01-Databases_PDO.md index 60a960f..d49e57d 100644 --- a/_posts/07-03-01-Databases_PDO.md +++ b/_posts/07-03-01-Databases_PDO.md @@ -50,13 +50,16 @@ FROM users` which will delete all of your users! Instead, you should sanitize th prepare('SELECT name FROM users WHERE id = :id'); -$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); // <-- Automatically sanitized by PDO +$id = filter_input(FILTER_GET, 'id', FILTER_SANITIZE_NUMBER_INT); // <-- filter your data first (see [Data Filtering](#data_filtering)), especially important for INSERT, UPDATE, etc. +$stmt->bindParam(':id', $id, PDO::PARAM_INT); // <-- Automatically sanitized for SQL by PDO $stmt->execute(); {% endhighlight %} This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the database preventing potential SQL injection attacks. +For writes, such as INSERT or UPDATE, it's especially critical to still [filter your data](#data_filtering) first and sanitize it for other things (removal of HTML tags, JavaScript, etc). PDO will only sanitize it for SQL, not for your application. + * [Learn about PDO] You should also be aware that database connections use up resources and it was not unheard-of to have resources