سؤال

I have the following code in my index.php page:

 <?php include("/includes/widgets.php") ?>

And in my widgets.php page:

<?php
     header("Location: /");
?>

What I want to achieve with this is to redirect it if the user visits it, but allow it for including.

But I get the following error:

The webpage has a redirect loop

How can I fix/prevent the redirect loop, but still redirect the user and not the server.

هل كانت مفيدة؟

المحلول

Place the widgets.php file in a folder not accessible to HTTP clients. I.e on apache webserver, either put it above your document root (into it's parent) or use .htaccess file to block users from it.

e.g.

deny from all

نصائح أخرى

I think I know what you need :)

Change code index file to next

define("IS_INDEX", true);
include("/includes/widgets.php"

Change code for widgets.php to next

if (!defined("IS_INDEX")) {
    header("Location: /");
    exit();
}

The issue is you are redirecting back to the same page, which then redirect again, and again, and again.

An easy fix would be to wrap the redirect in an if, and only redirect if they aren't already on the index page; but this is just patching what looks like an architectural problem.

Something like:

if (ltrim($_SERVER['REQUEST_URI'], '/') != 'index.php')
    header('Location: index.php');

One way is to check if __FILE__, which is the file loaded, regardless of included or not matches up with the file requested which is in $_SERVER['REQUEST_URI'] (or $_SERVER['PHP_SELF']).

I use this on our development site in a page that is usually included to get the output as debugging.

if(basename($_SERVER['PHP_SELF'])===basename(__FILE__)){
    //do some debugging
}

Typically you wouldn't use basename, but this is on a non-public facing development site and the file has a pretty unique name so I'm not worried about the file being included with another file with the same name or anything.

One possible way is to add a parameter to the redirection, e.g.

if (!$_REQUEST['redirect'])
    header("Location: /ìndex.php?redirect=1");

That way redirection can happen only once.

Another way is to stop redirection if the user already is on the /. I´d suggest to combine both.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top