PHP MVC - Database routing? - php

Hi I'm currenly playing around with PHP MVC programming, and was wondering if anyone has made some sort of "routing" with a database?
I have a "page" table that looks like this: http://i.imgur.com/xS1OvjW.png
Currently all routes are hardcoded, and I thought it must be possible to do with a database..
But not only do I want to get the page and show it, I also need to be able to send parameters with it.
Example:
As shown in my page table, I have a "test" url. If i type http://demo.com/test/ I would get "rerouted" to use the "home" controller and "Index" method. But I also need to be able to type http://demo.com/test/id/40 and id/40 will be sent as params to the controller/method.
If this isn't a good thing to do, or if anyone got a better soloution please let me know! :)
Regards,
Frederik

This definitely depends on the server you're using, but since you're a PHP MVC noobie I'll reference apache in this example, and hope it's what you have for the sake of the examples.
First, you'll need your webserver configured to know that it has to send all traffic through your base page (usually index.php). Now that page would do some other stuff (call bootstrap, etc) but for the sake of argument we'll say that all it does right away is look at the request from the page, compare it to the DB, and complete the request if it can.
In that case, it will be helpful to have the request info from the server passed in to the index.php page. To do this, you'll want to configure apache with an .htaccess file similar to:
DirectoryIndex index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ public/?path=$1 [L,QSA]
This tells it to use index.php for all requests that aren't specific files or directories, and to pass the full url path through to index.php as a $_GET var.
Next, in index.php, you'll want to check the path you were passed against DB of paths. Here's a really simple example to show:
<?php
// Obviously use your database and some string parsing here to match correctly
// I generally explode the path on '/' to break it into controller, action, etc.
if ($_GET['path'] == "user/account") {
// Then you call the controller that matches the first part of the route
// The action that matches the second part of your route
// And pass the request along so you can access anything else
call UserController::accountAction($_REQUEST);
} else if ($_GET['path'] == "user/resetpassword") {
call UserController::resetPasswordAction($_REQUEST);
}
From there, you should be in the right place and have everything you need. That Controller/Action URL format is a fairly common one for how easily it lets us do this.
Hope the answer helped!

Related

Generate URL Alias?? in PHP

I just saw this somewhere, and I'm interested on it, and can't seemed to find it anywhere or I just used the wrong words to search for.
Well I saw this link,
http://splur.gy/r/QqVYf/r/2tgNklHgmVK
and when I clicked it, I got redirected to other page which called
https://www.facebook.com/xxx.xxx?sk=app_xxxx
Anyone knows how this thing was made? or just a little hint to start off?
A help would be nice. :)
These are done with RewriteRule, a simple Google search willgive you mroe details.
In short, the URL will be broken down sorta like this: (Line 1, URL part, Line 2, PHP relative.
http://splur.gy
http://splur.gy/index.php
r
$_GET['var_1']
QqVYf
$_GET['var_2']
r
$_GET['var_3']
2tgNklHgmVK
$_GET['var_4']
The RewriteMod will take the URL as setup in the above format, and pass the varialbes to a script. It is another way of posting variables in the URL.
As you see above: stackoverflow.com/posts/15182831, does not actually have a file named posts/15182831, it is simple used as a variable, passed to a script which queries that database, and spits out results based on what the script says.
You will need to have a server that will allow you to rewrite requests so you can redirect all requests to a single script. If you are running Apache, you would create an .htaccess file with something like this in it:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^r$ /redirect.php [L,QSA]
RewriteRule ^r/(.*) /redirect.php?__q=/$1 [L,QSA]
</IfModule>
Then if you go to http://yourdomain.com/r/234243/adsfsd, the request will be sent to the script /redirect.php and '234243/adsfsd' will be passed as the GET paramiter 'q'.
Then you would create a file called redirect.php that would process the request and then redirect the user. It might look somthing like this:
<?php
$redirection = process_to_determine_location_from_query( $_GET['q'] );
header( 'Location: {$redirection}' );
?>
It's called a redirect. You can do it in PHP with this code:
<?php
header('http://example.com');
Another thing that might have happened is that the link you saw was not the actual link you follow when you click. It's as simple as doing this:
example.com
Anyone could do that.
http://www.google.com/
It has nothing to do with PHP.

Why aren't my routes working in CodeIgniter?

I have already read a bunch of the articles on stackoverflow about this topic, such as:
CodeIgniter: SEO friendly URLs
Codeigniter routes not working sometimes
And I swear I have set up everything correctly, but after I put the route in and save my app, and attempt to go to the new URL, or even the old one, they both give me a 404 error.
I have an extension that currently looks like this:
search/map_view/county
that I want to look like this:
map/county
I wrote the following reroute in the routes.php file, which gives me the 404 error:
$route['search/map_view/(:any)'] = 'map/$1';
And just in case I was doing it backwards, I also tried it like this:
$route['map/(:any)'] = 'search/map_view/$1';
That didn't do anything, so I've deduced i did that incorrectly. A thing of note is that I do have apache's mod_rewrite changing my url's to drop the index.php from it. Don't know how that's helpful, but I've noticed it a lot in the other posts.
Am I supposed to change something somewhere else for this? I'm assuming that if I type in the previous address, I should get automatically rerouted to the new one? Or if I type in the new address, it should work automatically? I don't know, it's getting really annoying...
Anyhow, I have a lot of questions about this stuff, but I'm going to start here and then see if I can find the rest of the answers here after I fix this one.
EDIT - I've been asked to include more info. Here it is.
Here's the .htaccess content
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
Currently I don't have any custom routes defined in the routes.php file, just because I can't get it to work correctly.
The current controller is "Search", with the method "map_view" being passed a variable "county". So the url would be
http://www.base_url.com/search/map_view/county
I want to change this to
http://www.base_url.com/map/county
Everything else I've previously written still applies. Thanks again!
You want your url looks like map/country .
In your routes.php
$route['map/(:any)'] = 'search/map_view/$1';
$route['map'] = 'search/map_view';
And be sure your controller name is Search.php.Also class name is Search that extends CI_Controller and method name map_view() (must be public function)
Look CI Controller Guide for detailed information

send each request to appropriate controller

I want to make a small web application, and I'm not sure how to go about this.
What I want to do is send every request to the right controller. Kind of how CodeIgniter does it.
So if user asks for domain.com/video/details
I want my bootstrap (index?) file to send him to the "Video" controller class and call the "details" method in that class.
If the user asks for domain.com/profile/edit I want to send him to the "Profile" controller class and call the "edit" method in that class.
Can someone explain how I should do this? I have some experience using MVC frameworks, but have never "written" something with MVC myself.
Thanks!
Edit: I understand now how the url points to the right Controller, but I don't see where the object instance of the Controller is made, to call the right method?
You need to re-route your requests. Using apache, this can be done using mod_rewrite.
For example, add a .htaccess file to your public base directory and add the following:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]
This will redirect users trying to access
/profile/edit
to
index.php?rt=profile/edit
In index.php, you can access the $_GET['rt'] to determine which controller and action has been requested.
Use mod-rewrite (.htaccess) to
rewrite the url from
www.example.com/taco to
www.example.com/index.php?taco/
in index.php, grab the first URL
parameter key, use that to route to
the correct url. As it will look
like "taco/"
You may want to add / to the front
and back if it doesn't exist. As
this will normalize the urls and
make life easier
If you want to preserve the ability
to have traditional query strings.
Inspect the URL directly and take
the query string portion. break that
on ?, which will leave you with the
routing info in key 0 and the rest
in key 1. split that on &, then
split each of those on = and set the
first to the key and the second to
the value of an array. Replace $_GET
with that array.
Example:
$path = explode("?", $_SERVER["QUERY_STRING"],2);
$url = $path[0];
if(substr($url,0,1) != "/")
{
$url = "/".$url;
}
if(substr($url,-1,1) != "/")
{
$url = $url."/";
}
unset($_GET);
foreach(explode("&", $path[1]) as $pair)
{
$get = explode("=", $pair, 2);
$_GET[$get[0]] = $get[1];
}
// Define the Query String Path
define("QS_PATH", $url);
Depending on what you want to do or how much work you want to do, another option versus writing your own MVC is to use Zend Framework. It does exactly what you're asking for and more. You still need to configure URL rewriting as mentioned in the other answers, but it quick and easy.
Even if you're not interested in Zend Framework, the following link can help you configure your rewrite rules: http://framework.zend.com/wiki/display/ZFDEV/Configuring%2BYour%2BURL%2BRewriter

how do i hide var passing info in the url if i have no form tags?

Hey guys - im using var passing links like this to jump around a site...
<a href = "index.php?content=about.html">
...problem is, i have all the ugly var info visible in the url. I would usually hide it by using the post method, but i dont have any form tags, so is it even possible?
Thanks!!!!!!!
It's a bad idea. GET is used for reading, POST is used for updating. A better solution would be to use some sort of mod_rewrite to make friendly URLS. Often called SEO friendly URLS...
Yes, you can POST with a <a href... but you have to have a lot of ugly javascript to do it... which breaks all sort of standard conventions.
Update, combining some new information
#FDisk has the simplest solution below, but I would add a condition to it which would allow existing files to be passed through directly by the webserver without having to run it through PHP:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)$ /index.php?content=$1 [L]
That way, a request to /images/bar.png will be served directly from the filesystem if that image exists.
Note, that your page does not necessarily need to have ".html" on the end anymore. So your URL could look like: http://example.com/about which would then be converted to: index.php?content=about
Taking it one step further from the link you listed in your post, you could then parse the url for various parameter. The example you looked up stuffed them into [$_GET, $HTTP_GET_VARS, $_REQUEST] respectively, but I think that's not such a good idea. Just make your own array of parameters.
You can try using the mod_rewrite extention
The original URL:
http://www.youwebsite.com/index.php?content=about.html
The rewritten URL:
http://www.youwebsite.com/about.html
.haccess file content:
RewriteEngine On
RewriteRule ^([^/]*)$ /index.php?content=$1 [L]
you can hide info (var name and content) by encoding it. Thus the user won't be able to understand or change what you are passing around. But he will still see something in his url.
I guess you should give use some more context to understand why you cant use direct links to static pages ?

using seo user friendly in php

this is the URL path I currently use:
/index.php?page=1&title=articles
I want to get the URL path as
/index/page-1/title-articles
using SEO user friendly URLs in PHP.
And how to get the value of the "title"? Any one can help me pls.
Check out the mod_rewrite module, and maybe for a good starting point, this tutorial on how to take advantage of it with PHP.
You need to ensure two things:
your application prints out the new URLs properly, and
your webserver can understand that new URLs and rewrites them to your internal scheme or redirects them back to your application and your application does the rest.
The first part can be simply accomplished by using
echo ' … ';
instead of
echo ' … ';
The second part can be accomplished either with URl mapping features of your webserver (most webservers have a module like Apache’s mod_rewrite). With mod_rewrite, the following will do the rewrite:
RewriteEngine on
RewriteRule ^index/([^/-]+)-([^/]+)(.*) /index$3?$1=$2 [N,QSA]
RewriteRule ^index$ index.php [L]
The first rule will extract one parameter at a time and append it to the query. The second rule will finally rewrite the remaining /index URL path to /index.php.
I want to get the URL path as
/index/page-1/title-articles
Why? I’ve got two objections:
index is a no-information and I doubt that it belongs in the URI
page-1, as well as title-articles looks plain weird. Like with index, you should ask yourself whether this information belongs here. If it does, make clear that it’s the key of a key-value pair. Or remove it entirely.
Thus, I propose either:
/‹article›/1
or
/‹article›/page/1
or
/‹article›/page=1
or
/‹article›[1]
or
/articles/‹article›/page/1
Or any combination thereof. (In the above, ‹article› is a placeholder for the real title, the other words are literals).

Categories