PHP Dynamic URL Folder Paths - php

I am trying to create a login and admin section to my project, however, I do not want to actually have the folders (ROOT/login/) and (ROOT/admin/) on the server. Instead, when someone navigates to http://localhost/admin/, it instead includes another file to the existing index.php.
I know how to check for _GET and _POST, but that doesn't seem like the route I am looking for as I do not index.php?SOME_VALUE. Instead, I am looking for an actual folder (in the URL) that doesn't really exist on the server.
I hope I am making sense. Here is an example:
$conf_site_url = http://localhost/
if
$conf_site_url + $_SERVER['REQUEST_URI'] === 'http://localhost/admin/'
then
include(/driver/views/admin/page.php);
else if
$conf_site_url + $_SERVER['REQUEST_URI'] === 'http://localhost/login/'
then
include(/driver/views/login.php);
else
include(driver/view/site.php);
Basically, if admin/ or login/ are appended to the URL, then include a different file from a nested folder, however, if nothing, then include the standard site.php file.

I made some changes to the codes.
$conf_site_url = "http://localhost";
if($conf_site_url."".$_SERVER['REQUEST_URI'] === 'http://localhost/admin/' )
{
include("/driver/views/admin/page.php");
}else if($conf_site_url."".$_SERVER['REQUEST_URI'] === 'http://localhost/login/' ){
include("/driver/views/login.php");
}else{
include("driver/view/site.php");
}
You should not forget the htaccess file.

Based on the information provided by ahmetarpaci's response, adding a .htaccess file with:
RewriteRule ^(.*) index.php [PT,L]
does the trick.

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..

Redirect direct access to files in subfolder to script

I have a subfolder that holds user uploaded files. I want to redirect all direct file requests to this folder to another .php script...so i can check if the user is logged in before i send/show the file to him.
For example:
/mainsite/uploads/user/2324/file.pdf
needs to be forwarded to
/mainsite/uploads/permissions.php
But i need inside the permissions.php to be able to do:
$url = $_SERVER['REQUEST_URI'];
and see what was the initial request...in order to readfile() the file after all the 'checking'.
I've tried this:
RewriteEngine On
RewriteRule ^/uploads/user/?$ /uploads/permissions.php [R=301,L]
but this is just a simple forwarding...i got no idea what file or folder the user requested.
I know i can do this by creating an individual htaccess file inside every folder that is created under 'user/{userid}' but i wanted a simpler function. I dont want to have 10000 htaccess files, if i can do this with just one.
Thanks
try with this syntax: (i added the R=301 part, which wasn't necessary in my version, so it is not fully tested, works without the R option)
RewriteRule "^/uploads/user/(.+)$" "/uploads/permissions.php?file=$1" [R=301,QSA,L]
You can the get your file var in the $_GET array in permissions.php. However, i wouldn't recommend to use directly this value because it can be unsecure. The best way is to only allow fixed values, with a switch for example, having filtered the var as a string before.

User friendly URLs without htaccess

I want to create friendly urls for my website script only using PHP, right now im using the query style (Ex: index.php?location=register) and i would like to convert them to something like this:
https://www.sitename.com/index.php/Register
Right now im using a $_GET based function to parse and include the php script based on the $_GET value.
$includeDir = ".".DIRECTORY_SEPARATOR."assets/controllers".DIRECTORY_SEPARATOR;
$includeDefault = $includeDir."Home.php";
if(isset($_GET['ajaxpage']) && !empty($_GET['ajaxpage'])){
$_GET['ajaxpage'] = str_replace("\0", '', $_GET['ajaxpage']);
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath)) {
include($includePath);
}
else{
include($includeDefault);
}
exit();
}
if(isset($_GET['location']) && !empty($_GET['location']))
{
$_GET['location'] = str_replace("\0", '', $_GET['location']);
$includeFile=basename(realpath($includeDir.$_GET['location'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath))
{
include($includePath);
}
else
{
include($includeDefault);
}
}
else
{
include($includeDefault);
}
Kind regards!
Okay, my comment keeps growing...so I guess I'll just provide an answer...
1) This still requires server configuration. In the case of Apache, I believe it's called MultiView. This is what allows Apache to look up a directory when the first path /file.php/somepage is not found...if you don't have the right configuration, it will just give a 404 error even though file.php exists. So, if your intention is to avoid the need for server configuration, it won't work.
2) What you are doing is dangerous:
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage'].".php"));
All I have to do is know where some of your files are and I can potentially cause one of your PHP files to run...e.g. run your nightly cron every 5 minutes and overwhelm your server or some other page that might do some damage...you need some way of forcing only files with a certain name can be included...e.g.
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage']."Controller.php"));
By forcing a suffix of Controller to the filename, you just have to make sure not to use the name Controller at the end of the file name for any file you don't want to be include-able.
3) There are so many MV* style frameworks out there...and there are so many security considerations, etc., that it is not always wise to create your own until you understand many or most of them. Even if you don't like them, using those frameworks will also help you learn some best practices for creating your own.
4) Finally, what in the world is the reason to avoid using URL Rewriting. URL Rewriting is the STANDARD for both Apache and Windows to create clean URLs. There is a reason that "everybody's doing it." If it's performance, your way will actually, probably, be slower because apache first has to look to see if the path exists, then go up a directory and see if that file exists, then go up another directory and see if that file exists until it hits a match...then open that file.
Why do you need to show index.php in the URL?
I would create my URL to look like this https://www.sitename.com/register if you truly want clean URL's but you would need to use something like the rewrite.
But you would need to use .htaccess or Apache config rules such as this.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?location=$1 [L]
Then in your PHP code you can do a get on location var $_GET["location"] and then load the page from the value sent.
The result of $_GET["location"] would be register from this URL and then you will display that page.
I don't suggest using MultiViews as it can cause issues if you have file and folders with the same name. e.g. /admin and admin.php.

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.

what is the best way to do that name?get=

ok assume i have php page
has this name name.php?get= and has get varible named get
ok
how i can make it appear like that name?get=
If you are using apache, mod_rewrite is one way to go. There is a whole bunch of mod_rewrite tricks here.
I'd seriously reconsider before using (or overusing) mod_rewrite.
In almost all of my projects I use a simple mod rewrite in the .htaccess:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./
AddHandler php5-script .php
This tells the server to forward all pages to / (index.php) unless a file otherwise exists.
In the root directory I have a folder called "views" with all of the pages that I use. E.g. the file used for /home would actually be /views/home.php. However, in the index.php I have a script that parses the user's url, checks for the file, and includes that.
$page = substr($_SERVER['REQUEST_URI'], 1);
if(!$page) :
header("Location: /home");
if(file_exists("views/$page.php")) :
include "views/$page.php";
else :
include "views/$page.php";
endif;
This creates a variable called $page that stores the value of everything in the URL after the domain name. I use a substr() function on the Request URI to get rid of the trailing forward slash (/) on the URL.
If the variable is empty, for example if the user is simply at http://example.com or http://example.com/ then it forwards them to /home, where the script then checks for the home.php file inside of the views folder. If that file exists, it includes it, and displays it to the user.
Else, the script will simply include the 404 page telling the user that the file doesn't exist.
Hopefully this helps you, and if you need any further explanation I'd be happy to help!
I think you're wanting to re-write the URL client-side, which would include mod_rewrite.
In the route of your website, create a file called .htaccess and place the following code in it:
RewriteEngine on
RewriteRule ^name?get=(.*) /name.php?get=$1
Now when you type http://www.example.com/name?get=something, it will actually map to http://www.example.com/name.php?get=something transparently for you.
As far as i could understand your question, you can not strip the file extension because otherwise it will not run. In other words, you can not change:
name.php?get=
into
name?get=
But if you mean to create links with query string values that you can put them in hyperlinks in this way:
Click here !!
If you're looking to create links using a variable '$get', then you can create the link like this:
<a href="name.php?get=$get>Link</a>
Or if you want to get the value of the query string variable, you can use this:
$get = $_GET['get']

Categories