Hi colshrapnel,
After your comments, I have been doing some deep research in the last couple of days and learned more about security and prepared statements. I know I still have a long way to go but every small step counts.
I have modified my PHP files and functions and how I handle parameters and SQL queries and I wanted to ask your opinion (if you don’t mind) if I am doing it the right way or need any touches before I continue and apply the concept to other files. My current setup works as intended, just want to know if I am doing it correctly and if I missed anything.
I have the following in my post.php file which displays a post in a certain category. This file receives category and post parameters (via .htaccess rewrite) like:
post.php?c=sample-category&p=sample-post
<?php
if (!(isset($_GET['c']) && isset($_GET['p']))) {
header('HTTP/1.1 404 Not Found');
header('Location: /404.php');
exit;
}
$p = get_post($_GET['c'], $_GET['p']);
?>
The idea is if category and post are not provided, display 404 error, otherwise continue with getting the post.
I have the following as the get_post function:
function get_post($category, $post) {
$stmt = DB::$db->prepare("SELECT * FROM posts LEFT JOIN categories ON category_id = post_category WHERE category_name = ? AND post_name = ?");
$stmt->bind_param('ss', $category, $post);
$stmt->execute();
$result = $stmt->get_result();
$post = $result->fetch_assoc();
if (empty($post)) {
header('HTTP/1.1 404 Not Found');
header('Location: /404.php');
exit;
}
return $post;
}
I saw somewhere the use of filter_var before the prepare. Like
$category = filter_var($category, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$post = filter_var($post, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$stmt = DB::$db->prepare(...)
...
Is such use of filter_var needed? Or, is prepare enough for a safe query.
Anything you would suggest that I modify in my code or approach?
Thank you very much again for all your contribution.