404 Response
Perch gives control over most things. So a lot of the times when you want something to behave in a certain way, you would be responsible for that; not Perch. So there are cases where you need to manually send a 404 response and serve your 404 page (e.g. incorrect slug on a dynamic page).
While you perform this differently on standard Perch and Perch Runway, on both you need to perform this before outputting anything on the page (not even whitespace). This means you need to perform this at the top of your PHP page.
Perch Runway
On Perch Runway you can respond with a 404 status and serve your 404 page like so:
<?php
if(condition) {
// respond with 404 and use the 404 error page
PerchSystem::use_error_page(404);
// stop executing this page
exit;
}
Standard Perch
On standard Perch, there is a bit more work involved. You need to manually handle sending the response code and serving the 404 page with standard PHP:
<?php
include_once('perch/runtime.php');
if(condition) {
// response with a 404 code
http_response_code(404);
// include your 404 page
include('/path/to/404.php');
// stop executing this page
exit;
}
In your 404 page you need to do 2 things:
- Use
include_once()
instead ofinclude()
when including the Perch runtime (you already included it; see above) - If you are using editabe content from Perch (e.g. a content region), you also need to tell Perch what page you are on (Perch doesn’t know you served the 404 page from within another page)
<?php
include_once('perch/runtime.php');
PerchSystem::set_page('/404.php');
perch_layout('global/top');
perch_content('Error Description');
perch_layout('global/bottom');