I have decided to build a web application using clean urls. However its seems to be quite hard for at first. I have experienced many problems during testing and I couldn't figure out how is it recommended to build Clean URLs basically.
I have finally decided to redirect everything to the index.php and process the URI from there.
This is my .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php?url=$0 [QSA]
In the PHP end I have created this, so only the URLs in the array will be passed:
$root_path = '/';
$uri = $_SERVER['REQUEST_URI'];
$url = array(
$root_path . 'login' => 'login'
);
$url_basic = array_keys($url);
$url_slash = array_keys($url);
array_walk($url_slash, function(&$value, $key) { $value .= '/'; return $value;});
if (in_array($uri, $url_basic) || in_array($uri, $url_slash)) {
$uri = rtrim($uri,'/');
require $url[$uri] . '.php';
exit();
} else {
echo 'Bad';
}
So basically if someone types: /login or /login/ they'll have the login.php required, otherwise they'll stay on the index.php page (as APACHE redirects everything else).
Question:
Let's say that the user has received an error while trying to log in. In this case I guess the best way (or if its not the best way, please tell me) to pass a $_GET variable with the name of 'error' for example. So the user would get: /login/?error=1
How is it possible to achieve that result? Because if I type that I get redirected to the index.php page. Can anyone please help me?
You can look at $_SERVER['QUERY_STRING'] at cut the query string out of $_SERVER['REQUEST_URI']:
if ($_SERVER['QUERY_STRING'])
echo substr($_SERVER['REQUEST_URI'], 0, -strlen($_SERVER['QUERY_STRING']) - 1);
The -1 is there to remove the question mark as well.
But setting the error in GET is not necessary. You can use a flash message and store the error in the session. You can find a simple way to use them here.
Maybe you should consider using a routing system as that of
Symfony: http://symfony.com/doc/current/book/routing.html
or its slimmer counterpart
Silex: http://silex.sensiolabs.org/doc/usage.html#routing
Related
In Node we can get an url address with a structure like this /example/:page/:id and we can take the page and id params. Is there a possibility to do something similar using PHP? Or is it only possible using the "?" with all the wanted params after the interrogation point?
I searched for a while and I tried some configurations in the htaccess file. All of them gave some kind of error like 403, 404 or in one of the configurations the intentioned page was loaded but it didn't find the css, js and images files.
Thanks
Edit:
I will put the solution I found here because maybe it can be useful for someone someday. After looking for some routers packages, I saw them instructing to put these lines in the htaccess file:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
I've tried something like this before and it was the one that I mentioned in the question that loaded the page but it didn't find the files like css, js, etc.
So I've decide to check the base url and I saw this was the point where the error was coming. After I changed it, the page loaded as the expected and now it's possible to get the value where the users can put a number and redirect to the page that they want (it's something like a magazine).
You can achieve it many ways.
In Laravel (see Documentation). I think every framework now has routing implemented.
Route::get('example/{page}/{id}', function ($page, $id) {
//
})->where(['page' => '[0-9]+', 'id' => '[a-z]+']);
With Mod-rewrite and then with access through $_GET parameters.
RewriteEngine on
RewriteRule ^example/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?page=$1&id=$2 [NC]
You can also redirect everything to index.php and there implement your own router. See: Redirect all to index.php using htaccess
RewriteEngine on
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
Something like this could work
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode( '/', $uri );
// all of our endpoints start with /person
// everything else results in a 404 Not Found
if ($uri[1] !== 'page') {
header("HTTP/1.1 404 Not Found");
exit();
}
For more reference visit this url
https://developer.okta.com/blog/2019/03/08/simple-rest-api-php
have you tried parse_url()?
it will return and associative array which has all the components in your URL
I know that similar questions were already asked, but i could not find any information for my specific "problem".
What i want to do is the following in a very dynamic way, which means that a "SuperUser" should be able to define new routes in a admin interface:
If a user enters http://www.example.com/nice-url/
he should get redirected to http://www.example.com/category.php?id=123 without changing the url.
Now there are a few ways i can achieve this. Either i use .htaccess like this:
RewriteEngine on
RewriteRule ^nice-url category.php?id=123 [L]
This works, but is not very dynamic. I would need to let a php script append new rules at the bottom which is not something i would like to do.
Or this:
.htaccess
FallbackResource /process.php
process.php
$path = ltrim($_SERVER['REQUEST_URI'], '/');
$elements = explode('/', $path);
if(count($elements) == 0) {
header("Location: http://www.example.com");
exit;
}
$sql = sprintf("SELECT Target FROM urlrewrites WHERE Source = '%s' LIMIT 1", array_shift($elements));
$result = execQuery($sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$target = $row['Target'];
header("Location: ".$target);
exit;
This also works, but sadly the url in the address bar gets changed. Is there a way in the middle of both? Having the flexibilty of PHP and the "silentness" of RewriteEngine? How do great CMS like joomla do it? Do they generate a htaccess file for each new page you create?
Thanks!
You can have this code in root .htaccess:
RewriteEngine on
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ category.php?uri=$1 [L,QSA]
PS: Note this will route /nice-url to /category.php?uri=nice-url. Then inside category.php you can dip into your database and translate $_GET['uri'] to id.
It would be more dynamic if you use regular expressions. That's how it works in CMS systems like Joomla. Good idea is to install Joomla with 'nice' URLs on and look over .htacces file to get to know how does it work.
You can start here:
http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/
I am currently working on a blog where I would like to create links to my individual articles in the following form:
http://www.mysite.com/health/2013/08/25/some-random-title
------ -----------------
| |
category title
However I have no idea how to achieve this.
I have found something that would give me the URI.
$uri = $_SERVER["REQUEST_URI"];
I would then go ahead and extract the needed parts and make requests against the database.
This may seem a very very dumb question, but I do not know how to look this up on google (I tried...) but how exactly am I going to handle the link ?
I try to explain it step-by-step:
User clicks on article title -> the page reloads with new uri --> Where am I supposed to handle this new uri and how ? If the request path looked like this:
index.php?title=some-random-article-title
I would do it in the index.php and read the $_GET array and process it accordingly. But how do I do it with the proposed structure at the beginning of this question ?
You will need a few things:
Setup an .htaccess to redirect all request to your main file which will handle all that, something like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
The above will redirect all request of non-existent files and folder to your index.php
Now you want to handle the URL Path so you can use the PHP variable $_SERVER['REQUEST_URI'] as you have mentioned.
From there is pretty much parse the result of it to extract the information you want, you could use one of the functions parse_url or pathinfo or explode, to do so.
Using parse_url which is probably the most indicated way of doing this:
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "https" : "http";
$url = $s . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
var_dump(parse_url($url));
Output:
["scheme"] => string(4) "http"
["host"] => string(10) "domain.com"
["path"] => string(36) "/health/2013/08/25/some-random-title"
["query"] => string(17) "with=query-string"
So parse_url can easily break down the current URL as you can see.
For example using pathinfo:
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$path_parts['dirname'] would return /health/2013/08/25/
$path_parts['basename'] would return some-random-title and if it had an extension it would return some-random-title.html
$path_parts['extension'] would return empty and if it had an extension it would return .html
$path_parts['filename'] would return some-random-title and if it had an extension it would return some-random-title.html
Using explode something like this:
$parts = explode('/', $path);
foreach ($parts as $part)
echo $part, "\n";
Output:
health
2013
08
25
some-random-title.php
Of course these are just examples of how you could read it.
You could also use .htaccess to make specific rules instead of handling everything from one file, for example:
RewriteRule ^([^/]+)/([0-9]+)/([0-9]+)/([0-9]+)/([^/]+)/?$ blog.php?category=$1&date=$2-$3-$4&title=$5 [L]
Basically the above would break down the URL path and internally redirect it to your file blog.php with the proper parameters, so using your URL sample it would redirect to:
http://www.mysite.com/blog.php?category=health&date=2013-08-25&title=some-random-title
However on the client browser the URL would remain the same:
http://www.mysite.com/health/2013/08/25/some-random-title
There are also other functions that might come handy into this for example parse_url, pathinfo like I have mentioned early, server variables, etc...
This is called Semantic URLs, they're also referred to as slugified URLs.
You can do this with the .htaccess command RewriteURL
Ex:
RewriteURL ^(.*)$ handler.php?path=$1
Now handler.php gets /health/2013/08/25/some-random-title and this is your entry point.
What i want to be able to do is if someone writes in the url bar
www.somesite.com/test
test is like the Username name so it will be www.somesite.com/Username
then page navigate to another and display data from the data where the username is the same
The page will navigate to another page and display data from he database
is this possible first of?
And this is what i have write now it not much, and i am also new to PHP
$url = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url2 = "http://www.somesite.com/"$databaseVar1=mysql_result($result,$i,"username");
if ($url) == ($url2)
{
header("location: http://somesite.com/viewcontent.php");
}
else
{
//not found
}
Am i Able to do something like this? Any help will be great-full thanks
In PHP this is not exactly possible, however, you can do the following:
www.somesite.com/index.php/test
Apache will open index.php and you can use something like $_SERVER['REQUEST_URI'] to navigate from there
You will either need to use a rewrite rule in .htaccess to redirect all requests to index.php. Index.php can then use
Or you can put a ? before the username. Then index.php will automatically get all requests. The $_SERVER['querystring'] will then receive the username.
Taken some assumptions (due to lack of complete source code in your question):
mysql connection is estabilished
proper query has been sent to mysql server
variable $i is set to meaningful value
www server is configured to rewrite requests to index.php
You only have to compare REQUEST_URI with "username" column value taken from database.
Header "Location: ..." must have capital letter "L".
And avoid usage of "==" operator when comparing strings in PHP, strcmp() function is more reliable - "==" operator tests identity not equality - it's useful to compare numeric values.
You can define the index.php as the application dispatcher and create an .htaccess file that will redirect the requests to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
index.php:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
if ($page == '/some/page/') include('file_that_handles_this_request.php');
Or you could use this to create instances of classes and call methods:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
list($class, $method) = explode($page);
$object = new $class();
$object->{$method}();
you should use mvc architecture to get perfect as you want.
the url in mvc is like same as you want. You can call the method with the parameter from url directly. Here is a url pattern in mvc architecture -
www.yoursitename.com/controller/methodname/parameter
I am using MVC framework in my website.In my webpage URL file extension is not showing.I need to specify the file extension like
www.legacy.com/women/tops.php
but its showing only
www.legacy.com/women/tops/
for seo purpose I want to change the url with extension. But I can't change the folder or file name.
One more doubt I have that.My webpage is showing
www.legacy.com/women/tops/
like this I want to change this as www.legacy.com/women_tops.php/
Is it possible?
Thank you
Here is the code I use to associate a URL with a controller:
$arrCommands = array (
'home' => "contents",
'members' => "",
);
if ( $arrCommands[$command1] == "*" )
{
$includeFile = CONTROLLER_PATH . "/" . $command1 . "/" . $command2 . ".php";
if ( !file_exists($includeFile) )
$includeFile = CONTROLLER_PATH . "/" . $command1 . "/default.php";
}
elseif ( !array_key_exists($command1, $arrCommands) )
{
$includeFile = CONTROLLER_PATH . "/contents/" . $command1 . ".php";
if ( !file_exists($includeFile))
Header( "Location: http://metroplots.ragedev/404_error/" );
}
else
{
$includeFile = CONTROLLER_PATH . "/". $arrCommands[$command1] . "/" . $command1 . ".php";
if ( !file_exists($includeFile) )
$includeFile = CONTROLLER_PATH . "/contents/home.php";
}
include_once($includeFile);
.htaccess can do magic. Can rewrite anything to whatever you want, can get messy...
http://httpd.apache.org/docs/2.0/misc/rewriteguide.html
You should also be able to do this in the application itself. In most good frameworks you can use customize routes, here is zend example.
the technology your looking for is called url rewriting
the idea is taking a give url and rewriting it on the server side. lots of software use this method to not expose logic via get parameters...
e.g.
http://domain.com/blog/2
according to the server, this url is actually:
http://domain.com/index.php?cat=blog&page=2
on linux/apache servers is is achieved via modrewrite:
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
using .htaccess files on the server that explain the rewrite rules and route urls.
microsoft iis servers have their own flavor (and syntax) called url rewrite:
http://www.iis.net/downloads/microsoft/url-rewrite
there are some tools out there to do this for you (here's an overview of 6 of them)
http://webm.ag/2009/12/15/6-of-the-best-mod-rewrite-generators/
but i feel like most times your best best is to manually create your own.
here's an example of the one i use on my site:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
basically this ruleset will redirect all traffic to index.php
in my MVC i have a generic controller called "url_logic" that runs first and looks at what the url is. and based upon it's logic it creates the necessary controllers to create the site (even if it's a 404 error controller).
hope that helps get you started!
also, if your using windows .htaccess files are tough to work with. i suggest naming them
htaccess.txt and when you upload them to the server rename them there.
You have to add below 2 line in htaccess
RewriteEngine On
RewriteRule ^women/tops /women_tops.php
create a index.php file, which will be read as default file for display and redirect it to your file.
What you are looking is mod_rewrite
mod_rewrite:
HIDING EXTENSION IN URL:
mod_rewrite Rewrite Rule generator will take a dynamic url given to it, and generate the correct syntax to place in a .htaccess file to allow the url to be rewritten in a spiderable format. The apache module mod_rewrite converts urls in a certain format to another format, and can be very useful in helping a site with dynamic content to be indexed.
NOTE : Before mod_rewrite put in action you should enable it in apache server.
Syntax: RewriteRule url-pattern url-new [[flag,...]]
Example: RewriteRule ^/foo/(.*)$ /bar/$1 [R,L]
Some useful links-
URL : http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
URL : http://tomclegg.net/rewriterule
have a look at this web page. i think it may have answers for you.
Thank you for every one who replayed to this question.
$xepWords = explode('_',$command1);
if($xepWords[0] == 'women')
{
$includeFile = CONTROLLER_PATH .'/women/tops.php';
}
I added this code in controller action Now its working fine