From 13c07d97e19d74ef36805788a15c3da12184ecc8 Mon Sep 17 00:00:00 2001 From: Adrian Date: Sat, 30 Jan 2021 20:15:04 -0500 Subject: [PATCH] refactored readBySlug() example Better to teach people to not use user input to access their filesystem. --- 10-dynamic-pages.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/10-dynamic-pages.md b/10-dynamic-pages.md index 398ba81..a78a11a 100644 --- a/10-dynamic-pages.md +++ b/10-dynamic-pages.md @@ -164,13 +164,14 @@ class InvalidPageException extends Exception Then in the `FilePageReader` file add this code at the end of your `readBySlug` method: ```php -$path = "$this->pageFolder/$slug.md"; - -if (!file_exists($path)) { - throw new InvalidPageException($slug); +foreach (new FilesystemIterator($this->pageFolder) as $page) { + if ($page === "$slug.md") { + $page = $page->openFile(); + return $page->fread($page->getSize()); + } } -return file_get_contents($path); +throw new InvalidPageException($slug); ``` Now if you navigate to a page that does not exist, you should see an `InvalidPageException`. If a file exists, you should see the content.