php include - alternative with better url - php

i want to build a website with different views, but a stable header and footer - no problem so far. But i dont like the kind of urls i got at the moment with the php GET method.
My site at the moment works like this (what istn working properly):
$_page = $_GET['p'];
if ($_page == "city-sitemap"){ include "views/city-sitemap-view.php"; }
if ($_page == "place"){ include "views/place-view.php"; }
else { include "views/index-view.php";}
this isnt a very sweet solution but i dont know a other for now. I tried to use a mvc framework but failed dramatically. So everytime i add a link i use for example this "index.php?p=place" - not very nice.
The including of the views isn very smart as well? is there a better way?
I would like to use something like the rewriteEngine that the new url is like a folder.
Can you help me to find a better solution?
Thanks a lot

Page including
For the page inclusion, you can use a simple array to dynamically allocate your page to a specific name. As so:
$pages = array('city-sitemap'=>'views/city-sitemap-view.php',
'place'=>'views/place-view.php',
)
if(array_key_exists($_GET['p'], $pages){
include $pages[$_GET['p']];
}else{
include 'views/error.php';
}
This array should be added in a general configuration file. With this configuration if you want to display your city-sitemap-view.php view, you will have to write this url: http://www.domain.com/index.php?p=city-sitemap
Url rewriting
It is possible to rewrite an URL with a .htaccess file. Here is an example of code you would can to write in your .htaccess file.
RewriteEngine On
RewriteRule ^(.*)$ index.php?p=$1 [L,QSA]
An url that looks like this:
http://www.domain.com/index.php?p=city-sitemap
will be converted to this one:
http://www.domain.com/city-sitemap

There is something called the front controller that you should look into. You can write a very simple one yourself. It works in conjunction with URL rewriting. If for example your url looks like this:
/mypage.html
the url rewriter will reroute the request to index.php .
Index.php will then look at the URL and do somehting like this:
1) break the page out into string, ignoring .html extention
preg_match("\/(.*?)\.html", $_REQUEST['URI'], $matches);
$pageClass = $matches[1];
//$pageClass = "mypage"
2) look for and load a class named "Mypage.php"
$controller = new $pageClass();
3) call the run method on the page class, passing it all the request parameters
$request = new Request($_REQUEST);
$controller->run($request);
you can then do all the page specific stuff inside your controller class that is specific to the page.
At each simple step along the way, you will find you want to do more and more things like authentication, filtering, tracking, etc. You will get end up developing a front controller that is specific to your needs, as well as a base Controller class that does a bunch of standard stuff that all your controllers have in common.

As per my comment, i really think you should consider the framework i linked, (it is very logical) or any other micro framework, but if you really wish to do this yourself then you can handle your includes like so:
<?php //index.php
$requested_page=isset($_GET['p'])?$_GET['p']:'home';
//maybe have this included from pages.php for organization
$pages=array(
'home'=>'home_content.php',
'about'=>'about_content.php',
'contact'=>'contact_content.php'
);
include "views/header.php";
if(array_key_exists($requested_page, $pages)){
include "views/".$pages[$requested_page];
}else{
header('HTTP/1.0 404 Not Found');
include "views/error404.php";
}
include "views/footer.php";
This keeps your pages in a single array, and protects against arbitrary inclusion vulnerabilities.
For nicers urls, see The other users .htaccess rewrite rules

Related

How to make a URL link like this http://stackoverflow.com/questions/tagged/php [duplicate]

When you edit a question on stackoverflow.com, you will be redirected to a URL like this:
https://stackoverflow.com/posts/1807421/edit
But usually, it should be
https://stackoverflow.com/posts/1807491/edit.php
or
https://stackoverflow.com/posts/edit.php?id=1807491
How was
https://stackoverflow.com/posts/1807421/edit
created?
I know that Stackoverflow.com was not created by using PHP, but I am wondering how to achieve this in PHP?
With apache and PHP, you might perform one of your examples using a mod_rewrite rule in your apache config as follows:
RewriteEngine On
RewriteRule ^/posts/(\d+)/edit /posts/edit.php?id=$1
This looks for URLs of the "clean" form, and then rewrites them so that they are internally redirected to a particular PHP script.
Quite often rules like this are used to route all requests into a common controller script, which might do something like instantiate a "PostsController" class and ask it to handle an edit request. This is a common feature of most PHP application frameworks.
It's called routing. Take a look at tutorials on the subject.
If you use a framework such as cake php it should be built in.
As #mr-euro stated you can use mod_rewrite but front controller is a far better solution.
You force every request to index.php and you write your application controlling in index.php.
You use Apache's .htaccess/mod_rewrite, and optionally a PHP file, which is the approach I like to take myself.
For the .htaccess, something like this:
RewriteEngine On
RewriteRule ^(.*)$ index.php
Then in your PHP file, you can do something like this:
The following should get everything after the first slash.
$url = $_SERVER['REQUEST_URI'];
You can then use explode to turn it into an array.
$split = explode('/', $url);
Now you can use the array to determine what to load:
if ($split[1] == 'home')
{
// display homepage
}
The array is starting from 1 since 0 will usually be empty.
It's indeed done by mod_rewrite, or with multiviews. But i prefer mod_rewrite.
First: you create a .htaccessfile with these contents:
RewriteEngine On
RewriteRule ^posts/([0-9])/(edit|delete)$ /index.php?page=posts&postId=$1&action=$2
Obvious, mod_rewrite must be enabled by your hostingprovider ;)
Using mod_rewrite this can be achieved very easily.
I am poor at this but i do know you can redirect urls using apache mod_rewrite and by touching config files. From what i remember htaccess can be used to redirect. Then internally when the user hits
http://stackoverflow.com/posts/1807421/edit it can use your page http://stackoverflow.com/edit.php?p=1807421 instead or whatever you want.
You could use htaccess + write an URI parser class.

codeigniter only pages to an existing website

My website structure somewhat looks like below
css/
lib/
js/
index.php
profile.php
products.php
checkout.php
orders.php
invoice.php
I have added a codeigniter folder in there ...
codeigniter/application/
codeigniter/application/controllers/
codeigniter/application/controllers/mycontroller.php
and other files
I can access CodeIgniter stuff by going to mywebsite.com/codeigniter/mycontroller etc fine.
However, I want to get rid of /codeigniter/ part from the URL. So I was wondering if it is possible to create a whitelist of the files which are CodeIgniter specific? For example, if the URL is mywebsite.com/mycontroller then it does CI stuff otherwise it looks for the plain PHP code file. I have only a couple of CI controllers and loads other non-CI files.
Any ideas?
I think you could use .htaccess to rewrite URL's that don't contain .php, css, lib and js. Something like:
RewriteCond %{REQUEST_URI} !^(\.php|css|js|lib)$
RewriteRule (.*) codeigniter/index.php/$1
So:
http://example.com/css/test.css
stays
http://example.com/css/test.css
(as will all requests to css|lib|js. You can append more things here for the rewrite to ignore)
http://example.com/controller/method
becomes
http://example.com/codeigniter/index.php/controller/method
You can test it out here: http://htaccess.madewithlove.be/
More on rewriting: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Short-term Solution
You can start by simply converting the index.php file into a controller and name it whatever you wish:
<?php
class New_default_controller extends CI_Controller {
public function index()
{
// home page stuff here
}
}
Alter the route.php file and set your default controller so that simply visiting your site will trigger the proper controller:
$route['default_controller'] = 'new_default_controller';
Apply the instructions for Removing the index.php file
Now calls to www.mysite.com/profile.php will access the profile.php at your root and calls to www.mysite.com/new_future_page will call your new_future_page controller.
Please let me know if any of this is confusing or you get stuck.
Optimal Solution
I wanted to leave a comment above but this would have been impossible to show as a comment.
You will have to take your PHP files and put them in the controllers folder like this:
codeigniter/application/controllers/profile.php
codeigniter/application/controllers/products.php
codeigniter/application/controllers/checkout.php
codeigniter/application/controllers/orders.php
codeigniter/application/controllers/invoice.php
Please go through and do the Tutorial before continuing any further. Specifically the Static Pages section will help you in achieving your goal.
You will have to convert your current PHP files to follow the flow of CodeIgniter

Load template or view depending upon a $_GET variables content

I am designing a Q & A website use php. Here is the directory structure:
+include
db.php
user.php
template.php
...
question.php
+public
+images
+styles
.htaccess
index.php
...
I want to use index.php 's REQUEST_STRING to load a template.
For example: index.php?page=signin will load the function get_signin_template() in template.php. And will show the visitor a URL like http://example.com/signin/.
Here are my questions:
How to load different templates in index.php (what should do in this file)?
How to rewrite the url (using apache mod_rewrite)?
Answer to Question 1
$valid_templates = array('signin', 'logout', 'home');
if(isset($_GET['page'])
and in_array($_GET['page'], $valid_templates)) {
$function_name = 'get_' . $_GET['page'] . '_template';
$template = call_user_func($function_name);
}
See call_user_func() in the PHP manual and the in_array() function in the PHP manual.
I think it is also worth mentioning that I would not do it this way myself. Mapping URLs directly to functions is an inflexible way of doing things.
The reason I have added the $valid_templates array is to ensure the user doesn't attempt to change the URL in an attempt to call a nonexistant function etc. You would need to add each page/template function to it.
If you really like this way of working then I would recommend you check out Limonade as it uses a similar dispatch method as the one you are attempting to setup (the following example is from their official site):
require_once 'vendors/limonade.php';
dispatch('/', 'hello');
function hello()
{
return 'Hello world!';
}
run();
But is a little safer and easier to manage in my opinion. Plus all the "hard" plumbing work has been done and you can just focus on adding your pages.
Another similar option is Slim, which looks like this:
require 'Slim/Slim.php';
Slim::init();
Slim::get('/hello/:name', function ($name) {
echo "Hello $name";
});
Slim::run();
Example from their site.
Answer to Question 2
Something along these lines in your .htaccess file should work for your rewriting needs.
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
1.for index.php?page=signin
$urlEnd=$_GET['page'];
require('path_to_file'.$urlEnd);//Require your file
header('Location: index.php?/$urlEnd');//WARNING!!! HEADER MUST go befor any echo's

Creating Vanity URLs

I currently run a site where I want to give people the ability to make their own URLs. For example, here is my URL:
http://www.hikingsanfrancisco.com/hiker_community/hiker_public_profile.php?community_member_id=2
You see, it is named just by id, which is uninteresting and also bad for SEO (not that it matters here).
Ideally I want my site members to also have their names in the URL. How is that typically done? So in my case, it would be something like:
http://www.hikingsanfrancisco.com/alex-genadinik and have the id hidden.
Is that possible? Any advice would be appreciated!
Thanks,
Alex
you need router, see https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Generally this is accomplished via the use of an htaccess file on a server with mod_rewrite (most Linux servers). An example might be like:
Options -Indexes
RewriteEngine On
RewriteRule ^([0-9a-zA-Z\-]+)$ $1.php
RewriteRule ^/(alex[\-]genadinik)$ /hiker_community/hiker_public_profile.php? community_member_name=$1
This implies that your hiker_public_profile.php script will need to accept "alex-genadinik" as $_GET variable "community_member_name," and then query the database via the name instead of the ID.
So you'd take the above code, save it in a file called ".htaccess," and then upload it to the root directory of your website. Learning regular expressions is recommended.
Code Igniter is a great MVC framework which provides configuration derived routes, which can easily be configured to send all requests through a common controller, where content can be dynamically pulled from a database and rendered.
Here is an example of a basic routing rule, which excludes request for users, students, and lessons, but routes all other request to a common content controller.
So if you request http://mydomain.com/hiking-and-camping-info, the url would be parsed, and hiking-and-camping-info would be looked up in the database and the related content pulled down.
Routing configuration:
$route['^(?!lessons|students|users|content).*'] = 'content';
and the content controller then grabs the url segment and finds the matching content and loads it:
class Content extends Controller {
function __construct() {
parent::Controller();
$this->load->model('Content_model', 'content');
}
function index() {
$content_url = $this->uri->segment(1);
$data['content'] = $this->content->get_content_by_name($content_url);
$this->load->view('content', $data);
}
}

How to solve the case when users surf to index.php

In Zend framework, using the MVC, if A user surf explicitly to http://base/url/index.php instead of just http://base/url, The system thinks the real base url is http://base/url/index.php/ and according to that calculates all the URLs in the system.
So, if I have a controller XXX and action YYY The link will be
http://base/url/index.php/XXX/YYY which is of course wrong.
I am currently solving this by adding a line at index.php:
$_SERVER["REQUEST_URI"]=str_replace('index.php','',$_SERVER["REQUEST_URI"]);
I am wondering if there is a built-in way in ZF to solve this.
You can do it with ZF by using Zend_Controller_Router_Route_Static (phew!), example:
Read the manual page linked above, there are some pretty good examples to be found.
$route = new Zend_Controller_Router_Route_Static(
'index.php',
array('controller' => 'index', 'action' => 'index')
);
$router->addRoute('index', $route);
Can't say I totally disagree with your approach. That said, others may well point out 5000 or so disadvantages. Good luck with that.
Well it really depends on how you want to solve this. As you know the Zend Frameworks build on the front controller pattern, where each request that does not explicitly reference a file in the /public directory is redirected to index.php. So you could basically solve this in a number of ways:
Edit the .htaccess file (or server configuration directive) to rewrite the request to the desired request:
RewriteRule (.*index.php) /error/forbidden?req=$1 // Rewrite to the forbidden action of the error controller.
RewriteRule index.php /index // Rewrite the request to the main controller and action
Add a static route in your bootstrapper as suggested by karim79.
Use mod_rewrite. Something like this should do it:
RewriteRule ^index.php/(.*)$ /$1 [r=301,L]
I don't think you should use a route to do this.
It's kind of a generic problem which shouldn't be solved by this way.
You better should have to do it in your .htaccess, which will offer you a better & easier way to redirect the user to where you want, like to an error page, or to the index.
Here is the documentation page for the mod_rewrite
I've never faced this problem using Zend Framework. just do not link to index.php file. that's it. and when your are giving your application's address to users, just tell them to go to http://base/url/
when the user enters http://base/url/ her request URI is base/url and your .htaccess file routs the request to index.php, but the request IS base/url. you do not need to remove 'index.php' from the request. because it is not there.
when you are trying to generate URLs for links and forms and ..., use the built-in url() view helper to generate your links. like this:
// in some view script
<a href="<?php
echo $this->url( array('controller'=>'targetController','action'=>'targetAction') );
?>" >click</a>
do not worry about the link. Zend will generate a URL for you.
The way I look at this is that if I have a website powered by PHP and a user goes to http://site/index.aspx then I would send a 404.
Even though index.php does exist in theory, it's not a valid URL in my application so I would send a 404 in this case too.

Categories