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!
Related
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'].
I realize this question is similar to this one but there didn't seem to be a definitive answer there. Currently I'm using <?php include "banner.html"; ?> but in order for this to work I need to change the ext of ALL pages to .php instead of .html.
I don't think this is really best practice. I'd prefer to keep my basic webpages as html files and reserve php files for server-side logic - isn't that the way it's supposed to be??
The banner should be displayed at the top of each page by default as soon as the page loads, so from what I've read jquery.load() is not appropriate as that should typically be triggered by user input. This is not an ASP.NET project so master pages is not an option. Also heard about HTML templating but after googling it I walked away more confused than ever.
I don't think this is really best practice.
It's fine, especially for small sites.
I'd prefer to keep my basic webpages as html files and reserve php files for server-side logic - isn't that the way it's supposed to be??
Keeping business logic and view logic apart is a good idea, but you don't need to go so far as to ban .php extensions on files that don't include business logic.
You might want to investigate the MVC pattern and the approaches taken by frameworks such as CodeIgniter or CakePHP if you want to see how other people keep their logic and HTML separate.
Either go ahead and convert the files to .php (totally fine practice), or use file_get_contents rather than include to get the HTML content:
<?php echo file_get_contents('banner.html'); ?>
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.
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.
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!