Restrict content access only to Logged In users - php

I have a folder named cache. It has sub-folders and files. I need to make cache content accessible only when isset($_SESSION["logged"]).
I have routed all requests to cache folder via index.php by placing the following .htaccess file in cache folder :
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^ index.php [L]
</IfModule>
In index.php following check is written :
<?php session_start();
if (!isset($_SESSION["logged"])) {
die();
} else {
header('Location: ' . $_SERVER['REQUEST_URI']);
die;
}
But I am geting error ::
This web page has a redirect loop
ERR_TOO_MANY_REDIRECTS
Could you please debug where I am wrong.

The reason why you get this error simply is that you explicitly implemented an endless loop. Your header() call redirects back to the same URL originally requested, so the rewriting rule applies again, things start all over again.
Instead you should output the contents of the requested cache file:
<?php
session_start();
$pathToCachedLocation = '/some/path' . $_SERVER['REQUEST_URI'];
if (isset($_SESSION["logged"]) && file_exists($pathToCacheLocation)) {
readfile($pathToCacheLocation);
}
You will still have to add some additional validation and error handling to make sure the request targets a file actually inside the physical cache location (see realpath()) and read permission exists (see is_readable()). Also some http headers probably make sense sending. The above example is kept simple to demonstrate the approach.

Related

Do not create an error page when a page does not exist

I have a domain which I want every attempted url after https://www.example.com/someFolder/ to not give an error but instead give a php page.
For example, I do not have a somefolder/abc.php file but going there will run a process.php file instead and display it there.
I have attempted to modify the 404 page as the process.php but that also modifies the example.com/ error page which I do not want.
It would be great if I do not need to modify/add a file at the root directory
PS. adding a .htaccess to the somefolder folder does work somewhat but then the url shows somefolder/404.php and not somefolder/abc.php
Modify your 404 page as you did putting php script there but check in php if the url that was requested was directory or not. Depending on that make an appropriate action
<?php
$url = $_SERVER[REQUEST_URI];
// check if requested url was ending with slash
$pattern = '#\/$#';
$result = preg_match($pattern, $url);
if ($result === 1) {
//request was to directory suffixed with slash
//do your php code for custom 404
die; //end the page generation
}
?>
request was not to directory ending with slash
put html of regular 404 page here or leave it blank
I have learned that I could turn somefolder into somefolder.php and use the $_SERVER['PATH_INFO'] to make all pages exist.
This is something that can only be done, in the general case, by using the .htaccess file, and redirecting every request like this...
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,NC,L]
After that, you can use $_SERVER, $_SESSION, and other global variables in index.php to decide how to handle a 404 error (i.e., you can implement here how to define what a 404 is, etc.).
For instance, $_SERVER['PATH_INFO'] will be able to tell you what URL was requested, and you can use a combination of file_exists() and other calls, to determine if you want to display a full 404, search results, a redirect, or simply to display the results of another script.
This works for example.com/somefolder/, example.com/some/other/folder/, and example.com/a/b/c/d/e/f/g/, etc..

Is there a way using php or htaccess to prevent access to a certain part of an url

For example a user can not access http://example.com/here but can access anything with more added. An example would be http://example.com/her?action=blah blah.
The point of this is to prevent access to an file by visiting the page directly, however allow the file to be use with more actions/links added.
I would just like to thank everyone for the quick response.
Based off the answers I got, I went with php and it worked.
I used the following:
function access_granted(){
global $pagenow;
if(!isset($_GET['action']) && 'wp-login.php' == $pagenow ) {
wp_redirect('http://example.com/');
exit();
}
}
I do have one question however.
I changed the wp-login.php url to http://example.com/here instead of http://example.com/wp-login.php.
My problem is that now, the function access_granted does not work anymore.
my guess is the $pagenow.
Any suggestions, such as how to check the url/here instead of wp-login.php?
If you want to go .htaccess way do this. Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^here/?$ - [NC,L,F]
This will throw forbidden error for /here or /here/ but will allow /here?bar=foo type of URIs.
Yes, there is.
You don't really need to deal with htaccess, you can do it with php.
First you need to check if required options are set. For example if you have a GET property with name action you can check whether or not it's set using isset function. You also need to specify a custom HTTP 403 page and redirect the user to that page. Here's an example for showing forbidden error if action is undefined:
<?php
if (!isset($_GET['action'])) {
header('HTTP/1.0 403 Forbidden',403);
header('Location: 403.html');
exit;
}
?>
You might also find the following link useful:
How to display Apache's default 404 page in PHP
Is example.com/here handled by a PHP script? If so, do your input validation at the start of the script, and if it doesn't meet the requirements, either give an error page or redirect (http://php.net/manual/en/function.http-redirect.php) to another page.
As you want it to work if anything is appended to the URL, you can use this if /here is handled by PHP:
<?php
if(!$_GET){
die('You are not allowed to access this URL.');
}
else {
... PHP code that will execute in case the user is allowed to access the URL(you can also use HTML by just having ?> here instead and add <?php } ?> at the end of the document) ...
}
?>
Hope it helped.
Sure, you can use PHP for this. on here.php you need a line (in your example) at the top of your code that looks like this:
if(!isset($_GET['action']){
header('location:/notallowed.php');
exit;
}
Where notallowed.php is whatever you want to show when they don't have the full link.

PHP not being parsed after redirect

I am trying to create a login page for some sites that I manage. So far it worked easy enough by having a login page which connects to a database which told the page where to redirect them.
I also have an .htaccess that rewrites the URL to pass through an authorisation page that just checks if a session has been started then pushes them through.
The problem I have is that when an admin logs in to the admin page it isn't parsing the php and when I go 'view source' I can see all the code... how do I get it to parse the php?
.htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)$ ../authorise.php?file=$1 [NC]
authorise.php
session_name('TSiteStats');
session_start();
if (isset($_SESSION['user_id'])) readfile ($_SESSION['redirect'] . '/' . $_REQUEST['file']);
else header("Location: ../login.php");
Just to be sure.
Does you file use the <?php and ?> tags. These tag will tell Apache to load the PHP code to be executed.
Also, does the script can be executed (has the authorization to be executed by Apache).
Last thing, your code is using readfile which output the content of the file and not execute this one. Are you sure you want to readfile and not include it?

PHP redirect when directly approaching?

I'm working on this PHP page wich includes different pages like header.php .
What I want is when you go to header.php, it redirects you to the homepage. I tried using header but when I include it, it keeps redirecting me.
I think it's possible with an if statement with $_SERVER, but I don't know how.
Anyone can help me out? Thanks in advance!
The best way to do this is to create a constant on your main landing page, so let say index.php is one of your main landing pages.
You would create a constant within there, and then do a check in all your sub templates that should only ever be included by a main page.
Example:
<?php
define("IN_VIEW",true);
require_once "header.php";
And then within header.php you can just to make sure that IN_VIEW is defined
<?php
if(!defined("IN_VIEW"))
{
die("Direct Access Forbidden");
}
//Header Here
If its not defined, then obviously the page has been loaded directly and not from index.php.
And then for every other "in-direct" page that should be secured you just place the three lines at the head of the file, and make sure the constant has been defined in your main pages (index,login,logout) etc.
if($_SERVER["PHP_SELF"] == "header.php") {
header("Location: index.php");
}
Although this isn't best practice. You shouldn't allow users to be able to access the PHP files in the first place. The simplest method of disallowing users access to this type of file is by moving the file above the document root, meaning it is impossible to request the header.php file via HTTP.
Another solution is to simply redirect everything to index.php so that direct access to any other script is prevented. On apache for example you can do this using .htaccess as follows:
RewriteEngine On
# redirect everything to index.php except exceptions
RewriteCond %{REQUEST_URI} !/robots\.txt$
RewriteCond %{REQUEST_URI} !/favicon\.ico$
RewriteCond %{REQUEST_URI} !/static/
RewriteRule ^(.*)$ index.php [L]
You can specify some exceptions such as your robots.txt file, and images directory.

How can I quickly set up a RESTful site using PHP without a Framework?

I would like to quickly set up a RESTful site using PHP without learning a PHP Framework. I would like to use a single .htaccess-file in Apache or a single rule using Nginx, so I easyli can change web server without changing my code.
So I want to direct all requests to a single PHP-file, and that file takes care of the RESTful-handling and call the right PHP-file.
In example:
The user request http://mysite.com/test
The server sends all requests to rest.php
The rest.php call test.php (maybe with a querystring).
If this can be done, is there a free PHP-script that works like my rest.php? or how can I do this PHP-script?
Using Apache Mod Rewrite:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^test$ rest.php [nc]
Yes, make a 404 Redirect to a page called rest.php. Use $url = $_SERVER['REQUEST_URI']; to examine the url. In rest.php you can redirect to wherever you want.
This only requires one rule (404 in your .htaccess file).
You have to be careful and make sure that if the page requested (e.g. mysite.com/test1 doesn't have a test1.php) errors out with a 404 you don't get yourself caught in a loop.
Modified slightly from the way that Drupal does it. This redirects everything to rest.php and puts the original requested URL into $_GET['q'] for you do take the appropriate action on. You can put this in the apache config, or in your .htaccess. Make sure mod_rewrite is enabled.
RewriteEngine on
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ rest.php?q=$1 [L,QSA]
If all you then want to do is include the requested file, you can do something like this
<?php
if (!empty($_GET['q'])) {
$source = $_GET['q'] . '.php';
if (is_file($source)) {
include $source;
} else {
echo "Source missing.";
}
}
?>
You really don't want to do that, however; if someone were to request '/../../../etc/passwd', for example, you might end up serving up something you don't want to.
Something more like this is safer, I suppose.
<?php
if (!empty($_GET['q'])) {
$request = $_GET['q'];
switch ($request) {
case 'test1':
include 'test1.php';
break;
default:
echo 'Unrecognised request.';
break;
}
}
?>

Categories