I have several folders within my web server.
Each folder contains php / html files. In total there is around 40 files.
Using php I can determine the identity of the user who is currently logged in.
Is it possible to allow users to only access specific pages, based on who they are logged in as ?
I was wondering if .htaccess would allow this ? Or if there is a better way ?
I don't really want to start having to create a user / password authentication script.
Thanks
Using sessions, you can create user levels and restrict access to various areas by assigning user levels to SESSION variables. Presumably, since, quote Using php I can determine the identity of the user who is currently logged in., you have the ability to set up session variables. I believe this is known as role based access control - In it's very simplest form
if ($_SESSION['user_level'] == "Administrator") {
# do something
}
This article may help further
You could do something like this in your .htaccess:
RewriteEngine On
RewriteBase /
RewriteRule ^(.+?\.php)$ index.php?p=$1 [L,QSA,NC]
This will redirect all users trying to view a PHP page to index.php?p=someurl.php
Then in your index.php you can determine if the user has permission to view to file and if they do serve it, if not deny it.
if ( authorized() ) {
// show file
} else {
die("Not Authorized to Access this File.");
}
You can't directly access SESSIONs from .htaccess rules, but you can try a workaround if you're not willing to code.
Inside your authorizing code section, in the last lines after creating session, add a touch() to create a file name of current user session id:
touch("./folder/logged/PHPSESSID_".session_id());
Then within your .htaccess file try to validate if current PHPSESSID related file is created before:
RewriteCond %{HTTP_COOKIE} PHPSESSID=(\w+)
RewriteCond %{DOCUMENT_ROOT}/folder/logged/PHPSESSID_%1 -f
RewriteRule ^(.*)$ $1
RewriteRule .* /users/login [L]
* Also note that you should create a simple script to check if created files are valid anymore, if not then remove them.
* It's just an idea!
Related
I have php files that i do not want users to be directly access by typing in the URL, therefore I have hidden these using .htaccess. However I want the user to be passed on (referred) to the next php file once they have logged in.
e.g. 123.456.789:8080/one.php is the login page and the user will then be sent to 123.456.789:8080/two.php.
Below is an example of some code that i found on here, but have not been able to make it work for my variables, and the fact I have the IP address and port no. Thanks
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site\.com/ [NC]
RewriteRule (^|/)B\.php(/|$) - [F,NC]
If you are using php for the logon can you not use something like this?
if( $logged_in){
header("Location: http://somesite/two.php");
}
I have a userprofile system in which a dynamic page (profile.php) changes as the id of user changes..
For eg. profile.php?id=2 displays the profile of user having id=2.. But i want the address to be as user/user_name.php. So providing each user a unique profile-page address..
Is it possible without creating a seperate page for each user?
Thnx
Ok, let´s talk about apache´s mod_rewrite. Basically what people usually do is that they setup one php page eg. index.php and redirect all the requests there (except those that request existent files and directories) and index.php then routes these requests to proper files/presenters/controllers, etc.
I´m gonna show you a very simple example how can this be done, it´s just to give you the idea how it works in basics and ofc there are better ways to do this (for example take a look at some framework).
So here is the very simple .htaccess file, placed in the same directory as index.php:
<IfModule mod_rewrite.c>
RewriteEngine On
# prevents files starting with dot to be viewed by browser
RewriteRule /\.|^\. - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?query=$1 [L]
</IfModule>
And here is the index.php:
<?php
$request = explode("/", $_GET["query"]);
// now you have your request in an array and you can do something with it
// like include proper files, passing it to your application class, whatever.
// for the sake of simplicity let me just show you the example of including a file
// based on the first query item
// first check it´s some file we want to be included
$pages = array("page1", "page2", "page3");
if(!in_array($request[0], $pages)) $request[0] = $pages[0];
include "pages/".$request[0];
But I highly recommend you not to reinvent the wheel and take a look at some existing php framework. You´ll find out that it saves you a lot of work, once you learn how to use it ofc. To mention some - Zend Framework, Symfony and the one I´m using - Nette Framework. There are many more, so choose whatever suits your needs.
Ok, so I have set the .htaccess like so:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ index.php
so as you can see I'm parsing everything to index except files because I need to "include" the php files and also displaying of images.
If users will type for example www.site.com/login.php that will show the login php page.
How do I prevent access to the php pages but also allow to "include" them?
Move them outside of your document root. They can be safely included from there but not accessed over the web.
If I understand the question do you want to not allow the user to go to other files if not logged in ? If so you can use php sessions to set a variable that they are logged in otherwise redirect to index
(If I understand the question)
If you wanna go that route (the outside webroot advise is the correct one!) then you could use a rule like that (see regex negative lookahead):
RewriteRule ^(?!index).+\.php$ - [F]
That's sloppy in that would allow index2.php or indexdir/xyz.php still; it just pevents anything that's not index*.php from being accessed. Make sure to also disallow .cgi or .phtml or .tpl if need be.
i was given 3 static pages e.g
proposal.test.com/seo
proposal.test.com/ppc
proposal.test.com/design
I checked those directories in the server and there's no dynamic about their indexes, all plain htm file.
the instruction given to me was, hide those url from anyone that doesn't match a random url from database..meaning e.g
if user typed proposal.test.com/seo ,it shouldn't display the page, if the user
typed something like e.g proposal.test.com/seo/a13sdfa and a13sdfa matched a key from a databased, that's the only time the proposal.test.com/seo page will be displayed
so how am I gonna do this in PHP ? because all 3 directories are made up of pure static pages..
i have done the creating of keys already, i just wanna know how to hide these pages by appending a given random key and checking if it does or don't exists in database.
Since the pages are never considered PHP, you can not block the access using PHP.
You can block access by configuring your web server, for example by using a .htaccess file.
If you blocked access the normal way, you can use PHP to allow access to the files on certain conditions..
You should use mod_rewrite (in case of Apache web-server) and setup a rewriting of /a13sdfa into something like ?key=a13sdfa. Also you should include some PHP code in all static files in order to check the key validity.
How about this: move the static files outside the public folder, so they cannot be accessed directly; redirect all requests to a php file (you can use rewrite engine with apache) which will look in the database for the accessed url/key and return the file_get_contents of the corresponding file.
Here's an example of how the .htaccess file could look like:
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What this does is the following: if the requested file doesn't exist on the disk (as a file or a directory), it will redirect to /index.php. There you should have the logic to render what page you want.
If you don't know in which variable the server will put the slug, just do a print_r($_SERVER) from inside index.php to find it.
There are 2 ways you could solve this problem.
1) (my prefered) Use .htaccess to only display the page if it matches the regex givin in the .htaccess.
2) In PHP (your actual question) 'Get the slug from the URL, query it to the database and if you get a result display it. Otherwise, send a 404 header from php.
Assuming the following: You have an Apache webserver with mod_rewrite enabled (check php info if you arent sure). Your virtual host allows overriding (AllowOveride All).
.htacces
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+) index.php?check=$1 [QSA,L,t]
If the file or directory exsists on the server it will display the page. So it would display seo, design etc. Otherwise it redirects to index.php and gives its slug as a parameter named $check. With this variable, query to the database, check te result and redirect to the desired page.
I am running into the following issue:
Our members have a desire for personalized sites directly from our primary domain in the form of http://www.example.com/membername. I am looking at possibly solutions in two ways but neither are ideal (will be explained below).
Method 1 - ?Member=
In this method, I simply create a custom URL and store the information in the member's database profile. For example: if I want my "custom" URL to be jm4, for a consumer to visit my site, they must type in http://www.example.com?Member=jm4.
The site, of course, does a $_GET['Member'] to lookup the member information, stores the primary data in Session from the index page, then redirects to a homepage. The consumer no longer sees the membername in the URL but instead sees all the page names for www.example.com as if they simply visited the parent domain to start (each member's page has custom information however).
While this method works it presents the following problems:
The URL is not nearly as easy as /jm4
and any errors typing out the
wildcard ?Members= will result in
page error. Also, This method keeps
that particular member's information
in session (which is necessary
browing from page to page on that
particular member domain) and
prevents somebody from simply typing
http://www.example.com?Member=name2 to
visit another site without clearing
their session or closing the browser.
Method 2 - /membername
While the preferred method, currently the only way we know how to create is to manually generate an index file in a subfolder, redirect to the primary index then allow the consumer to view the member's personal site.
For example, if I visit www.example.com/jm4, I am hitting the /jm4 folder which contains index.php. Within this file simply contains:
<?php
session_start();
ob_start();
$_SESSION['AgentNumber'] = "779562";
header("Location: ../index.php");
exit;
?>
the primary index recognizes this with:
<?php
session_start();
ob_start();
if ($_SESSION['MemberNumber'] == NULL) {
header("Location:ac/");
exit;
}
$conn = mysql_connect("localhost", "USER", "PW");
mysql_select_db("DB",$conn);
$sql = "SELECT * FROM table WHERE MemberNumber = $_SESSION[MemberNumber]";
$result = mysql_query($sql, $conn) or die(mysql_error());
while ($newArray = mysql_fetch_array($result)) {
$_SESSION['MemberName'] = $newArray['MemberName'];
$_SESSION['MemberPhone'] = $newArray['MemberPhone'];
$_SESSION['MemberMobile'] = $newArray['MemberMobile'];
$_SESSION['MemberFax'] = $newArray['MemberFax'];
$_SESSION['MemberEmail'] = $newArray['MemberEmail'];
$_SESSION['MemberAddress'] = $newArray['MemberAddress'];
$_SESSION['MemberCity'] = $newArray['MemberCity'];
$_SESSION['MemberState'] = $newArray['MemberState'];
$_SESSION['MemberZip'] = $newArray['MemberZip'];
$_SESSION['MemberAltName'] = $newArray['MemberAltName'];
}
mysql_close($conn);
header("Location: home/");
exit;
?>
We would certainly prefer to use the second method in terms of 'ease' for the member but keep running into the following issues:
We are forced to manually create a
sub-folder and unique index.php file
for each new member we onboard
While the above probably could be
automated (when new member creates
profile, automatically generate php
file and folder) but this is more
complicated and we don't want to
have 3000 subfolders on the primary
domain.
Has anybody run into similar issues? If so, how did you go about solving it? What would you recommend based on my details above? Any advice is appreciated.
Also - using as subdomain (membername.example.com) is not preferred because our current SSL does not allow for wildcards.
EDIT 1 - EXISTING .HTACCESS FILE
My existing .htaccess file on the site looks like this for reference:
ErrorDocument 404 /404.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.*)$ /?Member=$1 [L]
You can do your prefered method by just adding some lines to the .htaccess in your root directory:
This site should get you started
Or this one
If you are using apache, then you could use mod_rewrite to change urls like http://host/membername to http://host/memberpage.php?name=membername.
You could use this in a .htaccess file for your second method. It will rewrite http://yoursite.com/membername to http://yoursite.com/?Member=membername
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /?Member=$1 [L]
</IfModule>