Url routing regex help - php

I'm trying to create a url routing script for my new CMS but must confess that regex isn't my strong side. So far i keep running into errors or no results.
What i'm trying to accomplish is using certain tags like :id :year :slug etc...
Can anybody help me out or guide me to the right direction with this, that is how to use preg_match or similar functions to find the right "url pattern"? Google has not been doing it job for once :S
ADDED
Example url http://www.mysite.com/post/2011/08/15/title-of-a-blogg-post/
If i have a route database and one pattern is for example post/:year/:month/:day/:slug i want it to match this pattern and call a certain controller, action and in this example a certain article.
The regex array i created looks like
$patterns = array(
":id" => "/^[0-9]*$/",
":year" => "/^([0-9]{4})*$/",
":year_short" => "/^([0-9]{2})*$/",
":month" => "/^([0-9]{2})*$/",
":day" => "/^([0-9]{2})*$/",
":slug" => "/^[a-zA-Z0-9 -]*$"
);
I reckon i need to replace :id to /^[0-9]*$/ and afterwards run a preg_match to find if the url pattern exists in my routes table. However i don't know if i'm using the right regex patterns or just completely lost.
My .htaccess file is (because i need to use $_GET as well)
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
I use this basically to fetch the url and leave out $_GET variables.
$route_orginal = trim($_SERVER["REQUEST_URI"]);
if(strpos($route_orginal, "?")!=FALSE) {
list($route_orginal, $get_orginal) = explode("?", trim($_SERVER["REQUEST_URI"]));
}
if( substr($route_orginal,(strlen($route_orginal)-1),strlen($route_orginal)) == "/") {
$this->routes = substr($route_orginal,1,(strlen($route_orginal)-2));
} else {
$this->routes = substr($route_orginal,1,strlen($route_orginal));
}

I'm not sure what you are trying to accomplish.
But if you want a URL like www.mysite.com/tags/id-year-slug
where every tag is seperated by a hyphen, you could do like this:
First, you need a .htaccess file in your root to create pretty urls.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/tags/([A-Za-z-]+)$ index.php?tags=$1 [L,QSA]
Then in your index, you explode the tags by the - delimiter:
$tags = explode('-',$_GET['tags']);
Now you have an array of tags, which you can use for your sql and the url is pretty - high five!

Related

htaccess call php script then continue processing

I have this specific problem where I have to check URL if its part is 8 chars long hash code that is saved in my database or its just normal URL where you want to navigate.
For example if i write url :
- www.example.com/A4s8Gga3
i want to process it with my script in php file
And if i write url :
-www.example.com/my-books
-www.example.com/about
i want to navigate on those pages.
I know i have to use htaccess (so much I managed myself) and so far it looks like this :
#part1
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} (\/\w+)$ [NC]
RewriteRule ^(.*)$ mobile_redirect.php [L]
#part2
RewriteCond %{REQUEST_URI} (/|\.htm|\.php|\.html|/[^.]*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php
My mobile_redirect.php looks like this:
ob_start();
require_once('connect.php');
$request = $_SERVER['REQUEST_URI'];
$request_hotovy = str_replace('/', '', $request);
$request_hotovy = mysql_real_escape_string($request_hotovy);
$select = "SELECT HASH_ID,OFFER FROM kasko_send_form WHERE MOBILE_HASH_ID = '".$request_hotovy."'";
$query = mysql_query($select);
if(mysql_num_rows($query) > 0){
// request is mobile hash id
$result = mysql_fetch_array($query);
$hash_id = $result['HASH_ID'];
header("Location: some_link?def=".$hash_id);
} else {
// request is normal url
header("Location: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
I know that it will end up redirecting in loop. I tried to put part1 after part2 and still have the same problem. I am using joomla and it have many urls (which im not able to write down) that are not real directories or files that is why i cant just use in my php file this solution :
ob_start();
require_once('connect.php');
$request = $_SERVER['REQUEST_URI'];
$request_hotovy = str_replace('/', '', $request);
$request_hotovy = mysql_real_escape_string($request_hotovy);
$select = "SELECT HASH_ID,OFFER FROM kasko_send_form WHERE MOBILE_HASH_ID = '".$request_hotovy."'";
$query = mysql_query($select);
if(mysql_num_rows($query) > 0){
// request is mobile hash id
$result = mysql_fetch_array($query);
$hash_id = $result['HASH_ID'];
header("Location: some_link?def=".$hash_id);
} else {
// request is normal url
header("Location: page_not_found.php");
}
Because there is clearly more url processing done in joomla after it ends reading my htaccess (i dont know much about joomla either).
Can you guys give me a hint how to process the url (then maybe alter it so it wont end up in loop and then alter it again after the part1 back to normal so it can continue processing as it would normally)?
Also if you guys have any good tutorials where I could learn such things it would be really helpfull, because i understand only basics of regex and how htaccess works ...
If you use Joomla for most of your URLs exact the one that should have this eight character string there is a simple solution for this.
Just use the regular Joomla .htaccess file and add two lines before RewriteBase /
RewriteCond %{REQUEST_URI} ^/[A-Za-z0-9]{8}$
RewriteRule .* mobile_redirect.php [L]
But the Problem here is that if you have regular URLs in Joomla with 8 character than they would be redirected es well e.g. http://example.com/lastnews
So for this URL's you have to add a exception, and the hole thing would lock like this:
RewriteCond %{REQUEST_URI} !^/latesnews$ [NC]
RewriteCond %{REQUEST_URI} !^/youandme$ [NC]
RewriteCond %{REQUEST_URI} ^/[A-Za-z0-9]{8}$
RewriteRule .* mobile_redirectt.php [L]
There is no way to redirect back to Joomla with the same URL if your script do not find a record in your DB. Either your script is handling the URL or Joomla dose it. So you have to provide a 404, or find a way to include the index.php file from Joomla in your script.

Clean URL using .htaccess in PHP pages

Hi i have a site called finittra.com all menu's are dynamically linked with the page. I tried to make the site as like as a CMS. If i click on the about menu the url shows that http://www.finittra.com/?page=about & if i click on the contact page the url shows site url /?page=contact but i want that i would like to show everything within the finittra.com/finittra/ as like as a folder or canonical link type which is search engine optimization url friendly. Please anybody here to help me?
You might want to rewrite your URLs using .htaccess. You can use this mod-rewrite generator: http://www.generateit.net/mod-rewrite
Example:
RewriteEngine On
RewriteRule ^([^/]*)$ /?page=$1 [L]
But a proper & organized way would be using a Router, try Aura.Router
Example usage:
$routes = [
[
"name" => "My_route",
"pattern" => "/{page}",
],
[
"name" => "Another_route",
"pattern" => "/pages/{page}",
]
];
This is your routes array, the router will go through all routes and check if the given request url matches any of them.
$factory = new RouterFactory;
$router = $factory->newInstance();
foreach ($routes as $route) {
$router->add($route['name'], $route['pattern']);
}
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$match = $router->match($path, $_SERVER);
if ($match) {
$params = $match->params;
echo $params['page'];
}
URL to echo the page param: http://www.finittra.com/about
You will need to do the same as get for POST requests, but instead u'll need to add them manually to the url path. Atleast how I do it.
I'd try something like
RewriteEngine On
RewriteRule ^([a-zA-Z]+)/?$ index.php?page=$1 [L,NC,QSA]
This rewrites every finittra.com/xyz/ (which will be visible) to finittra.com/?page=xyz.
If you want your pages to have different names, you'll have to do that manually, I guess.
RewriteEngine On
RewriteRule ^finittra/?$ index.php?page=contact [L,NC,QSA]
Also, you have to adjust the links on your website
you must use .htaccess file in your project ,like :
.htaccess :
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^user/(\d+)*$ ./page.php?id=$1
If url request equl : http://www.finittra.com/user/123
Load :page.php?id=123

php router - variable url

Hello I was trying to come up with the solution to my problem, but I just was not able to. So here is my problem:
What I used was a .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.+(.*)/(.*)$ ./index.php?mesto=$1&den=$2 [QSA,NC,L]
It will display the url well. as www.site.com/CITY/DAY for example ../Prague/30.3.2014 but i need it to be more complex.
What I need is to have additional parameters, such as Bar or Restaurant in the url for example www-site.com/Prague/30.3.2014/p/bar/restaurant and other time I might have www-site.com/Prague/30.3.2014/p/pizza/bar
That part I have no idea how to do, because I have 5 different parameters
I imagine that the raw url would look this index.php?city=Prague&day=30.3.2014&p1=0&p2=0&p3=0&p4=0&p5=0 where p1 to p5 are the parameters being active (0 not 1 yes).
I don't understand how to detect what parameters are active and how to properly display the pretty url. Could you please help me?
Use
RewriteRule ^(.*)$ ./index.php [QSA,NC,L]
This will redirect all your requests to a single index.php that parses the uri with something like this:
<?php
// Example URI: /florence/30-06-2009
// Remove first slash from REQUEST_URI
$uri = substr($_SERVER['REQUEST_URI'],1);
// Get an array with portions between slashes.
$splittedURI = explode("/", $uri);
// Here you get your city (or anything else that you want)
$city = array_unshift($splittedURI); // In example, $city = "florence"
// Remaining itens in $splittedURI are the arguments/parameters to your page
// Like this:
$date = $splittedURI[0]; // In example, $date = "30-06-2009"
?>
Remember that this is just and example, and you should do additional verifications to avoid PHP exceptions.
If you need complicated routing (and if you sure you want to create your own router instead of using a ready solution as ZF, Symfony etc.) you're better off just passing the whole request uri to a php router object. There you can as complex router logic as you need.
So basically, loose the parsing in the rewrite rule:
RewriteRule ^(.*)$ ./index.php?route=$1 [QSA,NC,L]
Then you can let the index.php create a router object that can parse the route parameter and delegate the job where it needs to.
I'd recommend reading up about existing routing solutions though.

htaccess url alias / clean urls - php

Hello I've bee trying for 1 week now to fix some urls on my custom built site but I can't accomplish what I want 100%. So here is my question:
I have a php landing page that manages events the default url structure is this:
foreach($resultSet as $key => $event)
{
echo 'content';
}
As you can see the url format is like this
/event.php?eid=145&cat=metal&title=Great+gig
What I would like it to be through htaccess is something like this
domain.com/event/metal/Great gig
I've been reading htaccess guides but I cant make it work with more tahn 1 params on the url please advise, Thank you.
Change your php code so that it generates URLs that look like domain.com/event/metal/Great gig:
echo 'content';
(Note that the 'category' is mispelled in your example)
Add these rules in the htaccess file in your document root, preferably above any rules you may have already there:
RewriteEngine On
RewriteRule ^/?event/([^/]+)/([^/]+)/(.+)$ /event.php?eid=$1&cat=$2&title=$3 [L,QSA]
Additionally, if you have links that are out of your control that still have the query string, you can add these rules:
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /event\.php\?eid=([^&]+)&cat=([^&]+)&title=([^\ ]+)
RewriteRule ^ /event/%2/%3/%4? [L,R=301]

Easy mod_rewrite - So I'll never have to think about it again

Not sure how you'll take this question but...
Whenever I try to make my URLs look pretty I always end up messing around for too long and it's simply not worth the trouble. But the end effect is good if it were a simple task.
So what I want to do is create a method which in the end would achive something like...
index.php?do=user&username=MyUsername //This becomes...
/user/MyUsername //...that
index.php?do=page&pagename=customPage //And this becomes...
/page/customPage //...that
index.php?do=lots&where=happens&this=here //This also becomes...
/lots/happens/here //...that
index.php?do=this&and=that&that=this&and=some&more=too //And yes...
/this/that/this/some/more //This becomes this
So then I just make a nice .htacess file that I'll never have to look at again. Everything will be better in the world because we have pretty URLs and my head didn't hurt in the making.
You can use a different approach of throwing the url in a single parameter, and parse it in your application.
So the apache rewrite rule would look like:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
which will convert your urls as follows:
/user/MyUsername => index.php?q=/user/MyUsername
/page/customPage => index.php?q=/page/customPage
...
In your app, you then have a $_GET['q'] variable, which you can split by '/', and have your arguments in order. In PHP it would be something like:
$args = explode('/', $_GET['q']);
$args will be an array with 'user', 'MyUserName', etc.
This way you will not have to touch your .htaccess again, just your app logic.
For /user/MyUsername ==> index.php?do=user&username=MyUsername and /page/customPage ==>
index.php?do=page&pagename=customPage, you can use:
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)$ index.php?do=$1&$1name=$2 [L]
But I don't think you can write a catch-all rule for /lots/happens/here and /this/that/this/some/more because you need to tell mod_rewrite how to translate the two urls.
Remember, mod_rewrite has to translate /lots/happens/here into index.php?do=lots&where=happens&this=here and not the other way around.
The best approach would be to delegate your application to generate the “pretty URLs” as well as parse and interpret them and to use mod_rewrite only to rewrite the requests to your application with a rule like this one:
RewriteRule %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
This rule will rewrite all requests that can not be mapped directly to an existing file to the index.php. The originally requested URL (more exact: the URL path plus query) is then available at $_SERVER['REQUEST_URI'].

Categories