Search code examples
php.htaccesshttp-status-code-404

404 function is working but not showing properly


So i had .htaccsess file with the following code

.htaccess

<IfModule mod_rewrite.c>
RewriteEngine on
# Allowed the url has access to the php file without the .php extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php  [NC,L]
RewriteRule ^folder/?$ - [F,L]

# Force remove .php extension, if manually changed in url
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]
</IfModule>

Options All -Indexes
ErrorDocument 403 /AllProject/layouts/403-page.php
ErrorDocument 404 /AllProject/layouts/404-page.php
ErrorDocument 500 /AllProject/layouts/500-page.php

So I want to create a restriction for users who don't have access to a certain url. When the user tries to access a certain url via the url address, the user will be redirected to a 404 page.

The function works but the 404 page doesn't display correctly, instead of using the error page from .htacess, but the standard 404 error from apache, the following code is

header function

<?php
// Check role
if ($_SESSION['role'] != 'ADMIN') {
    header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found", true, 404);
    die;
    if (!isset($_SESSION['username']) && !isset($_SESSION['role'])) {
        $containUrl = urlencode((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

        header("Location: index?destination=" . $containUrl . "");
    }
}

Then I tried using the require function, but that's also a problem because on the 404-page.php page I'm using require function too. Which make the file become to contradict. The file code is

404-page.php

<?php require '../koneksi/koneksi.php'; ?>
<?php require 'resources.php'; ?>

<body>

    <!-- Page Container -->
    <div class="page-container">
        <div class="error-404">
            <div class="error-bg"></div>
            <div class="error-info">
                <div class="error-text">
                    <div class="error-header">
                        <h3>404</h3>
                    </div>
                    <div class="error-body">
                        <p>Halaman yang anda cari tidak ditemukan.<br>Klik <a href="<?= $hostToRoot ?>"> disini</a> untuk kembali.
                    </div>
                    <div class="error-footer">
                        <p><?= date('Y') ?> &copy; ReD | Projects <?= $version ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div><!-- /Page Container -->

    <?php require 'footer.php'; ?>

So where is the problem?


Solution

  • So, i've just figured it out to solve my problem. Thanks to @CBroe at the comment to suggest me using DIR It's actually working fine for me now.

    So now in the 404-page.php now i am using

    <?php require_once __DIR__ . '/../koneksi/koneksi.php' ?>
    

    To require the file outside properly.