The following code is developed around a mysql database where the posts table has 3 columns: post_ID, date and title.
config.php holds the values for $dsn
, $username
, $password
, $options
.
The content for each post is held in a directory format:
year/month/day/(database column)title/content.txt
By querying the database, I retrieve the date, which lets me order the posts (newest first).
$new_date_dir
formats the date to serve as the directory for the include link $link
.
$new_date_vis
formats the date to serve as the date for the post.
The file is called using include within another page which uses exterior formatting.
<?php include $_SERVER['DOCUMENT_ROOT']."/resources/config.php";
try {
$dbh = new PDO($dsn, $username, $password, $options);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
function orderBlogPost($dbh) {
$statement = $dbh->prepare("
SELECT date, title
FROM post
ORDER BY UNIX_TIMESTAMP(date) DESC
LIMIT 0,5
");
$statement->execute();
$statement->bindColumn('date', $date);
$statement->bindColumn('title', $title);
while ($row = $statement->fetch(PDO::FETCH_BOUND)) {
$new_date_dir = date("Y-m-d",strtotime($date));
$new_date_vis = date("d-m-Y",strtotime($date));
$new_row = preg_replace("[-]", "/", $new_date_dir);
$link = $_SERVER['DOCUMENT_ROOT']."/content/".$new_row."/".$title."/content.txt";
echo "<h1>".$title."<sup>".$new_date_vis."</sup></h1><br />";
include "$link";
}
}
orderBlogPost($dbh);
$dbh = null
?>
Whilst, this is outputting my desired result, I would like to know the following:
- Is this procedural code basically secure/usable?
- Can you suggest further reading on refactoring?
- How would I benefit from using OOP in this scenario?
$title
could be used for an XSS attack; it also looks like it should be possible to use it in an lfi attack, but I did not get that to work). \$\endgroup\$