index.php with parameters VS separate files? Where to put them? - php

I am learning and I got two different opinions and ways of this very trivial step. I have different pages in a project like Home, About, Contacts etc..
I did the following: An index.php files and parameters like ?page=about, ?page=contacts etc. I have a switch statement with $_GET['page'] for every parameter. For every case I include a different file for the page content.
Example:
switch ($current_page) {
case ('about'):
include VIEWS_PATH . PAGES_CONTENTS . 'about.php';
break;
case ('contacts'):
include VIEWS_PATH . PAGES_CONTENTS . 'contacts.php';
break;
default:
include VIEWS_PATH . PAGES_CONTENTS . 'homepage.php';
}
With this kind of navigation:
Home
About
Contacts
I read here that this way is not recommended because it is hackable and the switch statement will be very large if the pages are lot.
I was told about this practice: For every page from the project, a real physical file exist like index.php, about.php, contacts.php etc and every one of them includes its content.
And the navigation is like:
Home
About
Contacts
Which way is better? If the project has 100 pages do I have to place 100 files? This means my root directory will contains a lot of files. Is there a way I store these files in some folder instead of the root dir of the project?
Thank you very much in advance for your attention and answers!
I looked a lot at CodeIgniter to see how it is managed, but it seems to complicated and understandable for me yet. I think it is something with the .htaccess files and some routings. Is it the way?

am assuming you have 90+ files, you can go for dynamic content like:
index.php
content.php
index.php will run normally
content.php will execute all other pages by fetching data from db
you menu would be like
Home
About
Contacts
also you can show the urls as per your choice via .htaccess like
content.php?page=content can be shown as /page.php r /page.html and so on...
i hope you get an idea.

Main file with parameters is better because you as a programmer have control over what content is loaded at what address. This is what all frameworks do - they fetch the whole path and query parameters using mod_rewrite Apache module and .htaccess file and interpret them according to configuration stored in project code. This is especially useful when you're moving things between parts of your project as you can dynamically say that /contact loads not contact page but (for example) internal client support system.

The second solution is not common because you'd have to include the whole bootstrapping into every single content script. If you have to change something, you'd have to change it in every single file.
Your first example is prefered but as you said it's very static and uncomfortable for many pages. So you'd like to store this in an array in a file or in the database.
In the db you'd store
current page script
home home.php
about about.php
You fetch the current page ($_GET['page']) and in return have the script to include.
Instead of:
Home
You should implement
Home
If you want mod_rewrite support or nginx rewrites, you can enforce redirecting /index.php?page=X to /X then have to adjust your stored current page value in database.

Related

PHP code for every single page of a website

I am a beginner in web development. I know that the index.php file provides the foundation of a website. With some template design, we can re-use the headers and footers for many of the pages of the site. For the content, suppose I have the following:
<?php include 'content.php';?>
However, each page contains unique content. Therefore, this makes me think that for every page that I have, I need to create a separate PHP file. For instance, for page one I create a content_one.php file and for page two I create a content_two.php etc. Am I correct in my assumption? Thanks in advance.
The simplest way of doing this is to make your index.php the front controller for the site.
You do this with a case statement like this:
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
switch ($page) {
case 'faq' :
require_once('includes/faq.php');
exit;
case 'blog' :
require_once('includes/blog.php');
exit;
case 'home':
default:
require_once('includes/home.php');
}
Then your menus just need to use www.test.com?page=blog and adding new pages is as simple as putting the code and markup for that page in a new script in the includes directory and updating your menu code.
With rewrite rules, you can easily have url's like www.test.com/page/blog
It's a simple and effective way to handle routing.
Yes, that's pretty much the standard pattern for those coming to PHP from a predominantly HTML background. Typically they'll start with a multiple-page HTML site, each page with its own HTML file. As the site grows, they'll realize there is a lot of duplicated markup (header, footer, etc) and it becomes tedious to keep it all consistent. The solution is to rename their pages with a .php extension so the files are processed before they're served to the client, then the duplicate markup is removed and placed in an include file. The files are then all updated to pull in the content from the file using either include or require.
I wouldn't say that approach is wrong. This is exactly how I came to PHP oh so many years ago! But it isn't really the best in the long run. Realize that it's a stepping stone and as you learn more you'll realize what proper architecture/design looks like.
I don't know the true level of your programming experiences. When you're comfortable, you make want to look into some web frameworks, like Slim and Laravel. In these frameworks, the index.php file serves as a central entry point. All requests go through index and then are dispatched to different classes/methods/functions depending on the requested path. This is when your site starts to resemble a web application more than a web site from the development standpoint.
Best of luck!

Using /index.php as a simple template and document router for a website?

I need to put together a simple/small website fairly quickly for internal use (no external access), which will contain a few forms and simple interactive pages.
I don't really want the maintenance overhead of a CMS, but so that each page has a consistent look and feel, etc, it would be useful to be able to have each page be based on a common template to wrap around the unique page content, to include the HTML head, title, site navigation, footer, etc.
One approach would be to include various snippets via PHP within each individual page, but that involves repetition in each page, and doesn't scale well if I decide I might need to substantially change things later.
The alternative approach would be to use the main DocumentRoot index.php file as the template, and instead have it include the requested page 'within' itself (so that each of the other pages is actually really only a partial file defining variables for the 'title' and 'body' (for the main page body content)).
I see that I can use $_SERVER['PATH_INFO'] to extract the desired file path (relative to the DocumentRoot) and $_SERVER['REQUEST_URI'] to get the whole request string (in case there might be any GET parameters); for the actual content of the index page itself I could have it include an alternatively-named file instead; and there must be some way in Apache rewrite rules that it would be possible to elide out the index.php from the eventual URIs, ..but I haven't yet thought through very much further than this.
I am sure that this must be a scenario encountered many many times before. I could well spend a couple of days trying to think this through and re-invent my own wheel, but I don't really have the time to do this, and it probably wouldn't be a very good use of it in any case.
Does anybody have some existing "quickie" code that would be "good enough" for this, or know of something "formally" published (at which point does a working quick hack become an actual software package?!)?
Thanks for any advice.
You could send your requested page as url parameter to your index.php, like 'index.php?page=requested_page' and include the following rule in your index.php at the position where you like to get your content
<?php
include("./pages/".$_GET['page'].".php");
?>
I'm not sure if any effort you will put into this will be less than the effort of implementing a simple CMS. Most systems have simple setups and do most of the work for you. Any time you save on not implementing a CMS will cost you later on maintenance. Don't use 'internal use' as an excuse to make bad software. Unless it's a one-time solution that will be disregarded in a few weeks, you (or another developer) will have to extend and maintain the software.
Redirect all requests to index:
RewriteEngine on
RewriteBase /
RewriteRule ^(?!index\.php$|(?:css|js|media)(?:/|$)). index.php [L]
Something like that will stop redirect loops on the index and send everything except requests to static content folders (change to suit) to your handler in the index. Access the URL via $_SERVER['REQUEST_URI'].

Designing a content delivery system using PHP

Currently, I have a system that actively generates the pages on my site using PHP, more or less like so:
index.php ------include(query.php);-----> query.php grabs content from a file that corresponds to index.php
Query.php simply assembles the page from the mentioned index.php file and from header, footer, and navigation files.
The index.php file acts as a sort of proxy or label if you will so that when users visit the site, instead of having urls like "query.php?page=index" they have real pages.
The issue of course is that this is a bit convoluted. For each page of the site, I need 2 files: the "wrapper" file (such as index.php) and a content file to which it corresponds. I'd like to only be using a single file. The issue is that the single file should only contain the content of the page - not structure, header, footer etc.
So, what I'd like to be able to do is to be able to have index.php contain ONLYand a paragraph for example. When it is accessed, somehow PHP kicks in and applies a template and the header and footer.
Is PHP too high level a language to be able to do this? I know it is often done with Tomcat and java servlets, but I thought it would be cool to do with PHP.
EDIT: Important point, I don't want to use GET variables.
It's a bit hard to tell what you're trying to do, but have you looked into using a framework such as Kohana or Synfony? This will do pretty much exactly what you're asking.
If you're looking for a good template system, I suggest PHPTAL.
Failing that, it doesn't sound like you need to do anything that special. On the index.php page, why not just include header.php, the content, and footer.php? Short of using auto_append_file and auto_prepend_file, you can't add content to the page that is not explicitly in the code.
It sounds like what you want to do is route all requests through a single point (like frameworks do). Let's call it main.php.
On main.php you would have:
include header.php
include $_SERVER['PATH_INFO'] . ".php" //Requested file from URL. TODO handle this better
include footer.php
Then you would route all requests (using your server configuration) to "/main.php/pagename." Then pagename would only need its respective content.

PHP file structure for a simple website?

I have been working with PHP for a couple of years now but I don't consider myself any more than a moderate programmer.
While creating some websites (varying from presentation websites to some simple CMS'es), I have taken 2 approaches which I will discuss below. My question is simple: which one is better in terms of customization (it needs to be as customizable as possible) and speed (to load as fast as possible).
First choice
files: header.php , content1.php, content2.php , footer.php
idea: all the content files include the header at the beginning of the file and the footer at the end.
Second choice
files: index.php , content1.php, content2.php
idea: based on a GET variable or something similar, index.php includes the relevant php file
Thanks in advance for the answer!
I have a nifty framework that works equally well for small sites as it does large. The structure is pretty much the same in all instances and my directory structure looks as follows:
.htaccess
inc/
tpl/
css/
images/
js/
index.php
The job of index.php is to determine what file to load, where any programming logic is held in files in the inc directory, and templates are held in the tpl directory. For example, index.php could be as simple as this:
<?php
switch ($_GET['filename']) {
case 'news':
require 'inc/news.php'; // your news functions
include 'tpl/news.tpl.php'; // your news template
break;
case 'events':
require 'inc/events.php';
include 'tpl/events.tpl.php';
break;
case 'contact':
require 'inc/contact.php';
include 'tpl/contact.tpl.php';
break;
default:
if ($_GET['filename'] == '') {
include 'tpl/home.tpl.php';
} else {
header('HTTP/1.0 404 Not Found');
include 'tpl/page_not_found.tpl.php';
}
break;
}
Coupled with the following .htaccess rules:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+) index.php?filename=$1
Hopefully that makes sense. If not, let me know what doesn’t and I’ll be happy to explain further.
I would go with the 2nd one. This is the approach taken by many frameworks and a very good one. You have a single place that get's always called, so you could do some processing in there like cleaning up the URL, checking for a valid Session,...
Furthermore, you can store some basic options inside the index.php (since it's a small site I see ne problem in this way of doing it but with bigger projects, sperate config files are the better way IMO) that can be accessed by all pages that are getting called (included) from within the index.php file.
Speed should not be an issue with a small site so whatever solution you may choose in the end will have good results.
i didnt use any framework for my projects. but everyone advice me to use a framework.
i maintain a file/directory structure of my own
INSIDE ROOT DIR
/backups
/config
/library
/media
/models
/modules
/templates
/sql files
index.php
If the website really is simple and doesn't need any additional utility, i would go with the second choice. Mostly the HTML is not so complicated, that it has to be splitted into several files, the actual presentation magic should rest in the CSS file anyway...
With the second choice you have your - simple - website in one place and don't have to look around in several files if you want to edit something.
Victorelu - not really an answer to your question. But you might be advised to begin looking at some of the lighter weight MVC php frameworks (i'm not talking about CI, kohana, cake etc, more the very lightweight ones such as caffeine). I did a little proof of concept using caffeine (a lightweight MVC framework based on a few core files) that neatly addresses the requirement that you state:
'... customization'.
jim
[edit] - link to caffeine: http://code.google.com/p/caffeine-php/
there's agreat little pdf that walks the entire process: http://code.google.com/p/caffeine-php/downloads/list
Check mofe information about website page structure.
The most important and very basic part of php website is page structure of php website because it help when you want to redesign website or you want to edit some code then sure you need to know page structure of website.
Check full detail here

Should I use mod_rewrite for my site's URLs?

My site currently handles URL's like this...
/?p=home
/?p=profile&userid=1
/?p=users.online
/?p=users.online&page=23
/?p=mail.inbox
/?p=mail.inbox&page=12
... and so on, there is probably at least 120-150 different pages, on my site a page is built like this,
index.php includes a main config file which then includes function/class files into it
index.php then includes a header file
index.php then includes the page file which is from the url ?p=pagename
index.php then includes a footer file
That is how every page on my site is compiled, through the index page like that and I have been considering/thinking about cleanning up the URL's as I am re-writing/restructuring most of my sites code right now, it's the perfect time to do it if I am going to do it. What I mean by cleanning up the URL's is using mod-rewrite so the URL structure above would look like this instead...
/home
/users/1 //user ID might switch to use username as well
/users/online
/users/online/23 or /users/online/page/23
/mail/inbox
/mail/inbox/12
So first of all is there any downfalls to doing this, does it create a lot more processing work since it is using mod_rewrite?
Also would it be hard to write the regex or whatever is needed to match the file names in the format that I show above, I listed only a few of the pages but there would be at least 100 different URL pages I have blogs, bulletins, forums, all kinds of stuff
Absolutely. That's one of Apache's main purposes, so it's been designed to do it very efficiently. In fact, I'd emplore you to use that method.
It makes cleaner URLs for visitors
It's fantastic for SEO
It makes the website more professional
It makes it easier for users to guess URLs if they are trying to find a certain page without actually traversing through your site ti find it.
There are no downfalls, and a ton of advantages to using that URL structure. Go for it!

Categories