I was wondering if there is a 'best' way to have a website with multiple pages with all pages having the same layout but with different content (like facebook, stackoverflow and many many other sites)?
The way I'm currently doing this is like this:
(the content in my case is a database tablename which is then queried into content through sql.)
template.php:
<?php
function tplate($tablename){
echo "<html>content from $tablename</html>";
}
?>
subcat.php:
<?php
include 'template.php';
tplate('contenttable');
?>
This works in very simple cases but once I try to add more functionalities it gets really complicated and I spend a lot of time debugging.
Does anyone know how this is generally done/best handled?
You'd typically use a templating engine (often in concert with a framework, like Laravel or Symfony). Twig is a popular one for PHP.
this is what i have been doing for a while http://controllingnetworks.tk/ the url is rewritten using a mod re-write, if i was to type the url in full it would be index.php?page=home instead of /home
but all the pages have the same template with different content,
i have a few sites using databases to manage the content and a few that use php files to do this
Related
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!
I'm creating my own CMS from scratch as a way to build my php and mysql skills. Everything is going well, but I'm at the point where I want to create individual post pages for each blog post I write. So the index.php page has a list of all my blogs with snippets of each post and there is a read more button that should take the user to the full page for each blog post. Each post has a url created from the blog title entered in the "create post" form. I'm trying to figure out how to create unique pages for each post without passing the title, subhead, post content and other info through the GET.
This also dovetails with another feature I'm trying to add. I want to be able to create individual pages using a "create page" form like I did for my posts. So if I want an "about us" page I go to my admin form, fill out the title, add the content, and when I hit submit it creates the page dynamically. I have thought all day about how I'd do these two things but can't quite figure out how I can do this.
FYI, I'm not asking for code, I just need a push in the right direction as I try to conceptualize how to achieve this. Thanks!
If you're not familiar with the Model-View-Controller pattern, reading up on it might be prudent. MVC is frequently the right starting place for high-level design of web applications.
Also, a CMS is a big enough project you should consider using a PHP framework like CodeIgniter, Symfony, Zend, etc. to make your life easier. It removes a lot of the drudge work and common tasks.
Dynamic Page Creation and Display
I think you want to split it into two things: the text content (basically what you put in the forms) and the HTML templating surrounding that content.
When you make a page or blog post, you would want to store the actual content (what you type into the creation form) in a database of some sort (not necessarily an RDBMS, but if you're trying to build MySQL skills it's a reasonable choice).
Then you would use a separate function to bind that content into an HTML template and present it to the user when they load a given page.
URL Routing
To get nicer-looking URLs you can use something like apache's mod_rewrite. You can use that to convert a URL like this:
posts/how-to-make-a-cms
to this:
posts.php?title=how-to-make-a-cms
Then you can have posts.php read from GET as normal. How you choose to do the conversion is pretty open-ended.
To avoid getting really complicated rewrites, people often just structure everything to go to a central routing script which figures out what class and method to call and what arguments to pass it. So it would rewrite the URL above to:
main.php?a=posts/how-to-make-a-cms
Then main.php would parse out the segments of that argument from GET and figure out where to send them. Like it might take posts/show/how-to-make-a-cms and do something like:
$o = new Posts();
$o->show("how-to-make-a-cms");
If you do it that way, I think you can avoid mod_rewrite entirely as long as you're willing to accept only slightly pretty URLs, like this:
mysite.com/main.php?/posts/show/how-to-make-a-cms
I haven't done this type of thing before (because the frameworks do it so beautifully already), so I might be missing some minor details.
You should watch some tutorials from phpacademy.org or thenewboston.org, they have best and most valuable tutorials ever made about PHP.
I think you may try to start from that course/playlist:
phpacademy.org: PHP Tutorials: Creating a Blog
If you don't understand everything, watch this:
thenewboston.org: Official Beginner PHP Tutorials Playlist!
If you have no problems with PHP itself you may try to use some simple framework with MVC support. That helps A LOT in variable handling between pages, makes work with database easier etc.
phpacademy.org: Introduction to CodeIgniter
phpacademy.org: Introduction to CodeIgniter - Basic Website
I had the same problem. You can easily do this by using the fopen function. Here is a link to a tutorial: http://www.tizag.com/phpT/filecreate.php
<?php
function wwwcopy($link,$file)
{
$fp = #fopen($link,"r");
while(!feof($fp))
{
$cont.= fread($fp,1024);
}
fclose($fp);
$fp2 = #fopen($file,"w");
fwrite($fp2,$cont);
fclose($fp2);
}
//Example on using this function
wwwcopy("http://www.domain.com/list.php?member=sample", "sample.html");
//Another example
wwwcopy("http://www.domain.com/list.php?member=sample2", "sample2.html");
?>
One of the nice things about ASP.Net is the ability to set a site.master file that holds all the repeated HTML/code from a site, and still be able to alter things on it from an individual website page. (For example, changing the <title> tag for every page, or adding other things to the <head> of your document.)
In the past in PHP I've used Server Side Includes to remove duplicate HTML/code (such as the top of the document, main navigation, footer, etc.) but obviously you can't alter any of the contents from the page.
Is there any way to implement site.master type functionality in PHP? If not, what's a good way to remove repeated HTML/code while still being able to change things like the page's title, highlighted navigation, etc.
Thanks.
This is just called Template Engine and there is tons of engine for php.
Smarty is one of them
The simplest way of pulling in common fragments is to use require() which will allow you to include other files within the current file.
An example of how you might use it:
header.php - a reusable fragment
<div class="header">
<h1><?= $pageTitle ?></h1>
</div>
pageContents.php
<body>
<?php
$pageTitle = 'Check it out, the Foobar page!';
require('header.php');
?>
blah blah
</body>
What you are looking for is a templating engine built for PHP. ASP is a framework which has templating built in which provides you the functionality that you are referring to (i..e templates, membership provider, etc.)
In order to get the same in PHP you will need to use either a framework or a templating engine.
Some samples:
http://www.webresourcesdepot.com/19-promising-php-template-engines/
http://www.phpframeworks.com/
there is no such functionality in PHP, you can move your components into separate files and include them in your main file using include or require functions.
Some frameworks do provide (simulate) such functionality though. e.g. In cakePHP you can have a layout file where you can output your pages.
Lets say we have index.php with the following links.
Home>
Contact
Followed by the following dynamic content...
<div id="content">
<?php inlclude "./content/" . $_GET['page'] . ".php"; ?>
</div>
I am in the process of creating my own light weight CMS and i'm wondering if search engines will crawl through these links with the get variables and pull/index the content. I also plan on controlling my meta-content in a similar fashion.
Do Search Engines read/apply get variables?
They surely will. Else they'd miss most of the dynamic content on the web not using nice urls ;)
Search engines will scan a webpage for hyperlinks and store any unique locations that they come across. index.php is a different location than index.php?q=home is a different location than index.php?q=about.
Unless of course you've told the search engines not to scan that page with a robots.txt file.
Back in the early days of search engines, the answer was no. Nowadays search engines are smarter and are for the most part able to differentiate pages even with the same root pagename.
However, it will definitely be better to use a RESTful application design, and that will entail using mod_rewrite or some other technique to make your URLs more transparent. Given that you're in the planning stages of creating the CMS, I would definitely read up on how to implement REST in your program, avoiding the problem entirely.
I have a web application developed using PHP. I want my users to select themes for their pages throughout the application.
Where should I start before using PHP themes?
What should I know about Themes in a PHP application?
Edit:
My question about themes is only about changing the color of the layout, not the images.
Suppose My ADMIN user will have white and Orange, but my staff user will have white and green...
How it can be done in PHP with CodeIgniter?
There are lots of directions you can go with this.
1) "CSS ZEN"
This is where the markup remains unchanged, but you totally change the design just by using CSS and images. Demonstrated very well on http://www.csszengarden.com/
2) MVC Stylee
This is where you create a model that represents the page data and then pass it to a view, which contains some inline echo statements. The idea is that you could send the same model to a totally different view so it could look entirely different, HTML and all. Cake PHP is a good start for this: http://cakephp.org/
Example:
<div class="content">
<? echo $Page->Content ?>
</div>
3) Micro-Markup
With this method, you add your own "special tags" to an HTML page. You then read in your plain HTML page and replace the special tags with the information you want to display. This is good if you want your templates to be recognisable to HTML guys that don't know PHP and might break the PHP code in the MVC app.
Example:
<div class="content">
<#Content#>
</div>
Out of all of these, MVC is a very structured way of achieving what you want - however, I listed the other options as they cater for specific scenarios that might be relevant to you.
I have implemented the concept in all three of these, in situations that were appropriate for each.
Regarding The Edit In The Question
I imagine you'll have "something" that represents your user - so it is as easy as:
(In the event of just wanting to override a few settings...)
<link href="style.css" type="text/css" rel="stylesheet">
<?php if ($User->Type === USER_ADMIN) { ?>
<link href="admin.css" type="text/css" rel="stylesheet">
<?php } ?>
You can adjust this example in the following ways:
Use a switch statement if there will be many user types
If the replacement is total, rather than just a few overrides, you may want to completely swap the stylesheet.
You would usually set up template files that contain the HTML and CSS, and build in the PHP generated values at runtime.
The best approach to this is to have the theme reside in a separate directory, containing no code, just template variables like {mainmenu}, {backbutton}, {content} ... you get my drift. Those are then filled by your PHP script, possibly with the help of a template engine like Smarty (No need to re-invent the wheel here).
There is also the approach of having PHP markup directly in the template file(s) like echo $xyz; while this is a perfectly valid practice I use myself often, I recommend using a template engine over using PHP markup in the code if you want a solid, future-proof templating system because:
First, there is less that a designer can break when working on the HTML.
Second, having PHP markup in the code is a temptation to program PHP logic inside the template (loops, conditions) instead of properly preparing them in the PHP code at the point where the template variables are created. That is terrible for maintenance and the further use of your templates, because you have to replicate that PHP soup into every new template again. After all, you want to have a template engine so others can create new looks for your product, without having to know how to program it.
Third, with the templating engine based approach you have the possibility to add caching where necessary without any additional work. Not possible with the scripting approach. Yes, in a web application you won't be able to cache that much, but with a lot of data, there will be instances where it will help the user experience.
Fourth and least important, it makes your template less easy to export to other applications, and import templates from other applications.
The CSS Zen approach mentioned by Sohnee is great for websites, but is going to be too limited for a web application that uses complex input elements, JS based menus, and the like. It is too often that those elements need to be changed and customized in the markup.
If you have a look at my CodeIgniter Template library it briefly explains how you can set up themes and layouts (the equivalent of header & footer).
If you set up global code such as a Hook or a MY_Controller then you can dynamically set your theme based on the logged in user, the user type, etc.
Eg:
if($user->role == 'admin')
{
$this->template->set_theme('admin_skin');
}
else
{
$this->template->set_theme($user->theme);
}
That is just a VERY basic example of the sort of thing you could use this Template library for.
CMS Solutions
Magento and Wordpress package all theme related files into their own seperate directories. These contain the serverside code, stylesheets, images and javaScript for the theme. The user in effect chooses a directory to use which affects how the page is layed out and styled.
An easier approach
A much easier way to get started would be to accept that the actual content, e.g. HTML of a page would stay the same, but let the user choose from various CSS style sheets.
When choosing a style sheet the system could use JavaScript to load it in dynamically so that the user can preview the look they are choosing.
If you have really good semantic HTML it will be enough to change the CSS files. Unless the design changes are really heavy. Then it would make sense to provide PHP templates that are build with some sort of modules: variables which contain certain HTML structure like navigation or sidebar, etc.
For themes you do not need PHP. Just define your themes in CSS (the best way is one file for each theme) and use a simple JavaScript chooser like at this site: http://www.fotokluburan.cz/switchcss.js.