preview

Organize Your Next PHP Project the Right Way

Jul 20th, 2009 in PHP by Derek Reynolds

When starting out with PHP, it can be daunting figuring out how best to organize a project. If you've ever been confused with where to put your images, external libraries, or keeping your logic separate from your layout, then check out these tips; they'll get you heading in the right direction.

PG

Author: Derek Reynolds

Boston based web developer whom primarily lives in PHP, but breaks things in Objective-C from time to time. Loves working with front-end technologies such as HTML, CSS and Javascript. Feel free to follow me on twitter or check out my blog.

Tutorial Details

  • Program: PHP/Projects
  • Version: 1
  • Difficulty: Easy
  • Estimated Completion Time: 20 minutes

Directory Structure

I'd say the number one thing in getting your project up and running quickly is having a solid directory structure you can reuse for multiple projects. If you are using a framework, usually it will provide a structure to use, but in this scenario we're working on a simple site or app.

Breakdown

  • You are probably very familiar with the public_html structure. This is the Document Root in which all your public files are accessed (/public_html/page.php is accessed at example.com/page.php).

    • img — All your image files. I decided to split content images from layout images.
    • css — All your css files.
    • js — All your javascript files.
  • The resources directory should hold all 3rd party libraries, custom libraries, configs and any other code that acts as a resource in your project.

    • config.php — Main configuration file. Should store site wide settings.
    • library — Central location for all custom and third party libraries.
    • templates — Reusable components that make up your layout.

The Config File

As designers and developers our main goal is to do as little work as possible. One way to reach this goal is with config files. To get a better idea of what the configuration file should have check out this example.

<?php

/*
	The important thing to realize is that the config file should be included in every
	page of your project, or at least any page you want access to these settings.
	This allows you to confidently use these settings throughout a project because
	if something changes such as your database credentials, or a path to a specific resource,
	you'll only need to update it here.
*/

$config = array(
	"db" => array(
		"db1" => array(
			"dbname" => "database1",
			"username" => "dbUser",
			"password" => "pa$$",
			"host" => "localhost"
		),
		"db2" => array(
			"dbname" => "database2",
			"username" => "dbUser",
			"password" => "pa$$",
			"host" => "localhost"
		)
	),
	"urls" => array(
		"baseUrl" => "http://example.com"
	),
	"paths" => array(
		"resources" => "/path/to/resources",
		"images" => array(
			"content" => $_SERVER["DOCUMENT_ROOT"] . "/images/content",
			"layout" => $_SERVER["DOCUMENT_ROOT"] . "/images/layout"
		)
	)
);

/*
	I will usually place the following in a bootstrap file or some type of environment
	setup file (code that is run at the start of every page request), but they work 
	just as well in your config file if it's in php (some alternatives to php are xml or ini files).
*/

/*
	Creating constants for heavily used paths makes things a lot easier.
	ex. require_once(LIBRARY_PATH . "Paginator.php")
*/
defined("LIBRARY_PATH")
	or define("LIBRARY_PATH", realpath(dirname(__FILE__) . '/library'));
	
defined("TEMPLATES_PATH")
	or define("TEMPLATES_PATH", realpath(dirname(__FILE__) . '/templates'));

/*
	Error reporting.
*/
ini_set("error_reporting", "true");
error_reporting(E_ALL|E_STRCT);

?>

This is a basic drop-in config file. A multi-dimensional array serves as a flexible structure for accessing various config items such as database credentials.

  • db — Store database credentials or other data pertaining to your databases.
  • paths — Commonly used paths to various resources for your site.
    • log files
    • upload directories
    • resources
  • urls — Storing urls can be really handy when referencing remote resources throughout your site.
  • emails — Store debugging or admin emails to use when handling errors or in contact forms.

Using constants for commonly used paths makes include statements (require or include) a breeze, and if the path ever changes you'll only need to update it in one place.

Using Different Config Files For Multiple Environments

By using different config files for multiple environments you can have relevant settings depending on the current environment. Meaning, if you use different database credentials or different paths for each environment, by setting up the respective config files you ensure that your code will work without hassle when updating your live site. This also allows you to have different error reporting settings based on the current environment. Never ever display errors on your live site! Displaying errors on the live site could expose sensitive data to users (such as passwords).

The Layout

Reusable templates are another big time saver. There are some great libraries for templating (such as Smarty), and I always encourage using such a library rather than reinventing the wheel. These libraries offer a lot of functionality (like helper methods for formatting currency and obfuscating email addresses). Since this is a simple site however we don't want to take the time to setup the library and will be using the most basic of basic templates. We achieve this by including common sections or modules in to our site pages; this way if we want to change something in the header, like adding a link to the global navigation, it is propagated throughout the site.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Simple Site</title>
</head>

<body>
<div id="header">
	<h1>Simple Site</h1>
	<ul class="nav global">
		<li><a href="#">Home</a></li>
		<li><a href="#">Articles</a></li>
		<li><a href="#">Portfolio</a></li>
	</ul>

</div>

rightPanel.php

<div id="siteControls">
	<ul class="categories">
		<li>PHP</li>
		<li>HTML</li>
		<li>CSS</li>
	</ul>
	<div class="ads">
		<!-- ads code -->
	</div>

</div>

footer.php

<div id="footer">
	Footer content...
</div>
</body>
</html>

index.php

Let's say that we put all of our layout components (header, footer, rightPanel) in our resources directory under templates.

<?php	
	// load up your config file
	require_once("/path/to/resources/config.php");
	
	require_once(TEMPLATES_PATH . "/header.php");
?>
<div id="container">
	<div id="content">
		<!-- content -->
	</div>
	<?php
		require_once(TEMPLATES_PATH . "/rightPanel.php");
	?>
</div>
<?php
	require_once(TEMPLATES_PATH . "/footer.php");
?>

Taking It Further

While this basic template system gets you off to a great start, you can take it a lot further. For instance, you can create a class or functions that include all the template files and accept a content file as an argument to render within the layout. This way you don't need to keep including the template files in every page of your site, but rather abstract that logic out meaning even less work down the road. I'll show you a quick example.

/resources/library/templateFunctions.php

<?php
	require_once(realpath(dirname(__FILE__) . "/../config.php"));

	function renderLayoutWithContentFile($contentFile, $variables = array())
	{
		$contentFileFullPath = TEMPLATES_PATH . "/" . $contentFile;
	
		// making sure passed in variables are in scope of the template
		// each key in the $variables array will become a variable
		if (count($variables) > 0) {
			foreach ($variables as $key => $value) {
				if (strlen($key) > 0) {
					${$key} = $value;
				}
			}
		}
	
		require_once(TEMPLATES_PATH . "/header.php");
	
		echo "<div id=\"container\">\n"
		   . "\t<div id=\"content\">\n";
	
		if (file_exists($contentFileFullPath)) {
			require_once($contentFileFullPath);
		} else {
			/*
				If the file isn't found the error can be handled in lots of ways.
				In this case we will just include an error template.
			*/
			require_once(TEMPLATES_PATH . "/error.php");
		}
	
		// close content div
		echo "\t</div>\n";
	
		require_once(TEMPLATES_PATH . "/rightPanel.php");
	
		// close container div
		echo "</div>\n";
	
		require_once(TEMPLATES_PATH . "/footer.php");
	}
?>

index.php

This is assuming you have a file called home.php in your templates directory that acts as a content template.

<?php

	require_once(realpath(dirname(__FILE__) . "/../resources/config.php"));

	require_once(LIBRARY_PATH . "/templateFunctions.php");

	/*
		Now you can handle all your php logic outside of the template
		file which makes for very clean code!
	*/
	
	$setInIndexDotPhp = "Hey! I was set in the index.php file.";
	
	// Must pass in variables (as an array) to use in template
	$variables = array(
		'setInIndexDotPhp' => $setInIndexDotPhp
	);
	
	renderLayoutWithContentFile("home.php", $variables);

?>

home.php

<!-- Homepage content -->
<h2>Home Page</h2>

<?php

	/*
		Any variables passed in through the variables parameter in our renderLayoutWithContentPage() function
		are available in here.
	*/

	echo $setInIndexDotPhp;

?>

Benefits of This Method Include:

  • Greater separation of logic and view (php and html). Separating concerns like this makes for cleaner code, and the job of the designer or developer becomes easier as they are mostly working with their respective code.

  • Encapsulating the template logic into a function allows you to make changes to how the template renders without updating it on each page of your site.

Symlinks

On Unix based systems (os x, linux) there is a neat little feature called symlinks (Symbolic Links). Symlinks are references to actual directories or files on the filesystem. This is really great for when you have a shared resource, such as a library used between multiple projects. Here are a few concrete things you can do with symlinks:

  • Have two versions of your resource directory. When updating your live server you can upload your latest files into an arbitrary directory. Simply point the symlink to this new directory instantly updating your code base. If something goes wrong you can instantly rollback to the previous (working) directory.

  • Shared resources are easily managed with symlinks. Say you have a custom library you've been working on, any updates to the library you make in one project will be immediately available in another.

Using Symlinks

Symlinks vs Hardlinks

Symlinks, or softlinks, act as references to full paths on the filesystem. You can use symlinks in multiple locations and the filesystem treats them as if they were the actual file or directory they reference. Hardlinks on the other hand are pointers to a file on the disk (think shortcuts in windows); they take you to the actual location of the file.

There are a few things you should consider when using symlinks. Your server configuration must be set up to follow symlinks. For Apache this is done in the httpd.conf file. Find the Directory block and make sure that Options FollowSymLinks is there. If not add it and then restart Apache.

<Directory />
	Options FollowSymLinks
	AllowOverride None
</Directory>

Creating Symlinks in OS X

There are 2 ways to create symlinks in OS X:

  • Via the command line, navigate (cd, change directory) to the directory in which you want the symlink to be created, then use the following command:

    $: ln -s /path/to/actual/dir targetDir

    So if our custom library lives in ~/Sites/libraries/myCustomLibrary we'd cd to where we want to use that library cd ~/Sites/mySite/resources/library and enter:

    $: ln -s ~/Sites/libraries/myCustomLibrary myCustomLibrary
    Note that this method should work in all Unix based operating systems.
  • The alternative is through the finder. By holding alt + cmd while clicking and dragging a file, a Symlink (or alias in os x) that points to the file is created.

Creating Symlinks in Windows

To accomplish this in windows you'll need to use the mklink command in the command prompt:

C:\mklink /D C:\libraries\myCustomLibrary C:\Users\derek\Sites\mySite\resources\library\myCustomLibrary

Summary

These tips are meant for beginners or those creating simple sites or applications. Ideally for larger applications or sites, you'll want to consider something more advanced like the MVC architecture and Object Oriented programming. I encourage you to look into these once you've gotten your feet wet and feel that you've outgrown most of the steps above. I decided not to cover source control as it's a pretty large subject on its own, but these tips should help you in organizing your files for easier source control if desired (hint: store stuff like layout images in your resource directory and symlink it into your /public_html/img dir). Definitely look in to using source control, like subversion or git for all of your projects.

Hope you find these tips helpful when starting your next PHP Project. Thanks!

Resources


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Benjamin Reid July 20th

    I’m working on my ‘New Site Template’ at the moment. So I can just copy and paste a folder to start a new project with something very similar to this.

    Fo instance when wanting to add an image I’d use :

    <img src=”images ?>” ?>

    Nice to see how someone else is doing it.

    ( Reply )
    1. PG

      Benjamin Reid July 21st

      Urr.. that code code destroyed.

      ( Reply )
  2. PG

    Diego SA July 20th

    Awesome, it’ll come in handy for future PHP websites. Very useful! Thanks!

    ( Reply )
  3. PG

    umpirsky July 20th

    Configuration is global, that’s bad, use registry pattern instead. Otherwise looks good :)

    ( Reply )
  4. PG

    Jeff Adams July 20th

    Useful post cheers. I liked the config file, though why two database links?

    ( Reply )
    1. PG

      Derek Reynolds July 20th

      Sometimes it’s necessary to work with multiple databases, so I wanted to demonstrate organizing such a case.

      ( Reply )
    2. PG

      Shaun July 20th

      I think it was just shown as an example of how you could store multiple db configurations. Sometimes it is necessary to connect to more than one database.

      ( Reply )
      1. PG

        Mohammad Atif July 21st

        yes and usually the username, password and database name are different on our local machines than online. So you can have it changed in one go :)

    3. PG

      Dave M July 20th

      Sometimes you need to set up a test db for local development and a live db when the site goes live. you can add a host check to detect what is the current environment and use the appropriate db config.

      ( Reply )
  5. PG

    killerwolf July 20th

    the code you are using is not that efficient, because having begining and eding html tag on different files would break the rules of any good IDE (Eclipse PDT) you may use, and would give something crappy when using lame editors ( wysiwyg ) such as dreamweaver

    USE PHP5 framework

    ( Reply )
  6. PG

    Rohan July 20th

    Interesting. I’ll come back to this when I *have* a PHP project to do :-)

    ( Reply )
  7. PG

    Muhammad Adnan July 20th

    helpful tut !

    ( Reply )
  8. PG

    Atroxide July 20th

    Once again, an A++ tutorial :)

    ( Reply )
  9. PG

    saurabh shah July 20th

    wow ! very handy article …

    ( Reply )
  10. PG

    Craig Maclean July 20th

    Great article!

    One question: which is preferred: require_once() or include()? Any difference?

    ( Reply )
    1. PG

      Angelo R. July 27th

      I would go with include() as require_once() actually takes a bit longer to work, and if you were including() multiple files, speed would be of importance.

      ( Reply )
  11. PG

    Cory July 20th

    I generally do something pretty similar, good to know others do it the same. Also do you recommend including any “globally” needed classes in the config as well? That seems to be the way I have been going about it lately.

    ( Reply )
  12. PG

    Soner Gönül July 20th

    Wow! It’s great;

    twitter.com/sonergonul
    friendfeed.com/sonergonul

    ( Reply )
    1. PG

      nutsplus July 21st

      Stop idiotically promoting yourself !
      You are embarrassing your fellow citizens.
      You should offer something valuable on your site or here on tutsplus, so you can create traffic to you or your websites.
      That’s an honest opinion from me.

      ( Reply )
  13. PG

    Andrew July 20th

    This is a very helpful tutorial!

    ( Reply )
  14. PG

    Zac Vineyard July 20th

    This is always good to see. I’ve been working to make my sites more organized. Having separate folders for images is excellent.

    ( Reply )
  15. PG

    Chirs_IM July 20th

    how do you incorporate this architechture with progress enhancement in terms of CSS. does your css strucuture around your php now? or should it just be dumped into the final html output of after the php has been rendered out.

    hope that makes sense.

    ( Reply )
  16. PG

    Michael July 20th

    Great tut! It’s always good to see different ways of organizing all the files.

    ( Reply )
  17. PG

    Aqib Mushtaq July 20th

    great tut, thanks.

    ( Reply )
  18. PG

    3CK July 20th

    Uhm, I don’t think that it’s a good solution. Procedural programming is hangover these days…

    ( Reply )
    1. PG

      Ben July 20th

      Agreed. + This structure assumes that you will have access to run php code outside of the document root. Some hosts won’t allow this.

      ( Reply )
  19. PG

    Jam July 20th

    This is a bit over kill for a “simple site”.
    If you want this much distance between logic and view, you might as well just go ahead and use a framework.

    ( Reply )
    1. PG

      Brian Temecula July 20th

      This is exactly what I was thinking. CI, Kohana, or any MVC framework would help anyone organize their site (with the exception of media)

      ( Reply )
      1. PG

        Phil Morris July 20th

        I second the that. Organization is great, but documentation and standards will help others when reading your code. CodeIgniter will give u organization, configuration files, a template library, and many more.

        No site is too small to be organized.

    2. PG

      Shane July 21st

      The aim of the tutorial was to illustrate the organisation of files. Seems appropriate to use a simple site to get the point across, and organisation is a valuable part of site development, of course. Nobody’s arguing with that.

      However, as Brian has said, a big advantage of an MVC framework such as CodeIgniter, is that much of the organisation is already done for you.

      ( Reply )
  20. PG

    Hardeep Khehra July 20th

    @jam Couldn’t agree more.

    First of all, I would say use a framework based on this article just because you’ve mentioned creating “environments”.

    Secondly, This whole article outlines re-inventing the wheel by creating a framework. Why not start in the right direction by using a framework like Symfony which separates your Model, View, & Controller; has an ORM layer, Caching at multiple levels and a lots of libraries, plugins, helpers in case you ever want to take your project/site to the next level.

    ( Reply )
    1. PG

      goutham November 8th

      I have been using symfony its great go with it everyone.

      ( Reply )
  21. PG

    Juan Felipe Alvarez Saldarriaga July 20th

    cool, anyway, I just need to use zend framework :)

    ( Reply )
  22. PG

    Rata July 20th

    To keep order is a good idea, a difficult task … but yes ;) you’re right.
    Thanks to remind me.

    Kind regards
    Rata

    ( Reply )
  23. PG

    techietim July 20th

    Constant name error:

    error_reporting(E_ALL|E_STRCT);

    ( Reply )
  24. PG

    Matthieu July 20th

    Hi,
    Very nice !
    the only difference between this architecture and the MVC architecture is the absence of controller, right ?

    ( Reply )
    1. PG

      Derek Reynolds July 20th

      It’s a stretch, but pretty much. The file that includes renders the template (makes the call to renderLayoutWithContentFile()) can be considered the controller in this case. Though things get a little blurry when it comes to the model unless you use some set of classes or functions that handle the business logic; for example, `getNewUsers()` which would retrieve new users from your data layer.

      ( Reply )
  25. PG

    Ellery July 20th

    Good post.

    Maybe you may also want to reference to the MVC model (without using a framework) by going to

    http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html

    Combine your article with this may create more insights to your reader.

    My 0.2

    ( Reply )
  26. PG

    Page Gardens July 20th

    Useful tip!

    ( Reply )
  27. PG

    Style Swamps July 20th

    Will be sure to use this when I actually make something with PHP.

    ( Reply )
  28. PG

    Cody July 20th

    Awesome, thanks for the article. Keeping thing organized will help a lot in development. Its a good idea to have some sort of framework to save time.

    ( Reply )
  29. PG

    Vijay Joshi July 20th

    Hi Derek,
    great post. That’s a very clean and organized layout.

    thanks

    P.S. – your twitter link is broken. please fix. :)

    ( Reply )
    1. PG

      Derek Reynolds July 21st

      Oh no! I don’t have control over the article once it’s published, but you can find me at http://twitter.com/whatupderek.

      Thanks for the comment!

      ( Reply )
  30. PG

    Dzinepress July 20th

    nice article and keep help me.

    ( Reply )
  31. PG

    Sandeep Sharma July 20th

    Wow, this is great.. Useful post.. Thank you very much!

    ( Reply )
  32. PG

    Fayat July 20th

    great explanation to work php with projects, thank you.

    ( Reply )
  33. PG

    Daquan Wright July 20th

    Interesting tutorial, although I expect people to know it’s easier to maintain anything if you keep it organized. While this may be too basic for advanced developers, it’s a nice overview for any developers with sloppy habits. Not every situation will need a framework but perhaps there is a tiny window of a chance you want to be doing things yourself.

    ( Reply )
  34. PG

    ezoryak July 20th

    This is a very helpful tutorial..!

    ( Reply )
  35. PG

    Lamin Barrow July 20th

    Very neat tut. Great tips and esay to follow. It look very similar to wordpress too. Thanx. :)

    ( Reply )
  36. PG

    unicolored July 21st

    Clap clap, this tut is very well done! I recommend it to all webmasters. A lot of good advice that can be applied to the many ways of developping!

    Thanks!

    ( Reply )
  37. PG

    Nanane July 21st

    Interesting Tutorial.

    But what if we got in index.php :
    $variables = array(‘variables’=>’hahaha…’);

    I know this tut is all about organisation, but still :)
    I suggest to use an unusual name instead.

    Thx for the tut !

    ( Reply )
    1. PG

      Derek Reynolds July 21st

      It wouldn’t matter because you are just passing that array in to a function which is outside the scope of the original $variables.

      Thanks for the comment!

      ( Reply )
  38. PG

    Tomas July 21st

    Great Tutorial, simple and precious.

    I personally think this is very practical! I going to bookmark or print or make whatever to archive this for the future!

    Thank you!

    ( Reply )
  39. PG

    Yatrik July 21st

    Nice article.

    ( Reply )
  40. PG

    yadirosadi July 21st

    great tutorial..

    Thank you!

    ( Reply )
  41. PG

    grant July 21st

    Nice but you can do this kind of template in dreamweaver mx without php

    ( Reply )
  42. PG

    Martyn Web July 21st

    I have already been using the php include method for a while now but to see how you structure the folders and files could help me with some of the larger projects Im going to end up tackling.

    ( Reply )
    1. PG

      Kevin Quillen July 21st

      Use an established framework.

      ( Reply )
  43. PG

    Developnew July 21st

    nice article…

    ( Reply )
  44. PG

    Chris July 21st

    Great article and already practice most of this if not using a framework.

    Just one question which has bugged me for years – including the “CONFIG” file in each PHP page. Is there a better way than typing the full path as you have done?

    I’m not sure if the code below will appear, but I’ve been using a method similar to what you’ve put in the CONFIG dirname()

    [CODE]
    if((strpos($_SERVER['PHP_SELF'], ‘index’) == TRUE)) {
    require_once(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . ‘httpdocs’ . DIRECTORY_SEPARATOR . ‘includes’ . DIRECTORY_SEPARATOR . ‘config.php’);
    } else {
    require_once(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . ‘includes’ . DIRECTORY_SEPARATOR . ‘config.php’);
    }
    [/CODE]

    Just wondering what others thoughts were on including a config file in each page. Sometimes the pages need to be in sub-folders so the path changes.

    May I also add, its a good idea to have a ‘DEVELOPMENT’ variable in your config file so you can swap database user/pass, paths etc.

    ( Reply )
    1. PG

      Derek Reynolds July 21st

      Well if you know your config file is going to live in say the resources directory, above your Document Root you could simply use:

      require_once(realpath($_SERVER["DOCUMENT_ROOT"] . “/../resources/config.php”));

      ( Reply )
  45. PG

    awake July 21st

    Darn It… Yet another way…

    ( Reply )
  46. PG

    Chris July 21st

    thanks for the resources at the end of the article! symlinks are very useful info!

    ( Reply )
  47. PG

    Thomas R. July 21st

    use a framework …. far more easier

    ( Reply )
  48. PG

    MonkeyT July 21st

    Under OS X, a symlink and an alias are not precisely the same thing: an Alias is great for GUI interaction, but sometimes fails if used with unix applications or command line tools. I suspect it’s that aliases work through the Finder while symlinks work through the underlying filesystem processes directly. For anything that involves unix tech, use symlinks.

    ( Reply )
    1. PG

      Derek Reynolds July 22nd

      Good tip. I was trying to research this, but came up inconclusive. Thanks!

      ( Reply )
  49. PG

    Jason July 21st

    I think config.php would be a great place for an __autoload func if you need one.

    ( Reply )
  50. PG

    Jeroen July 21st

    You can replace:
    [code]
    // making sure passed in variables are in scope of the template
    // each key in the $variables array will become a variable
    if (count($variables) > 0) {
    foreach ($variables as $key => $value) {
    if (strlen($key) > 0) {
    ${$key} = $value;
    }
    }
    }
    [/code]

    with [code]extract($variables)[/code]

    When not using Smarty you could use a function like the one found at:
    http://www.bigsmoke.us/php-templates/functions

    ( Reply )
  51. PG

    Mom to D July 21st

    Derek,

    I don’t know a thing about building a web site, with or without a framework. But I do know about technical writing; I write process and procedural scripts as part of my job. Your article incorporated the organization that you write about, making the article simply flow. Outstanding! Applying organization skills to any project allows us to reach success much sooner. You also sparked a lot of conversation and thought, and much gratitude!

    I couldn’t be prouder!

    Love, Mom

    ( Reply )
    1. PG

      Dan August 9th

      What a cool Mom, and for beginners it’s very important to understand the business of separating logic and view code well before going any where near a framework, if you understand PHP you should not need to use templates anyway. Nice work Derek A+ Bro.

      ( Reply )
  52. PG

    Chris Paraiso July 21st

    thanks for this. I was just asking about program structure in PHP projects in IRC and didn’t really get a response.

    ( Reply )
  53. PG

    Haim Michael July 21st

    Excellent article. Thanks for your good work! I want to take this opportunity and invite you all to use the free courses (PHP courses incl.) I develop available for free at http://www.abelski.com. Best, Haim.

    ( Reply )
  54. PG

    Anandkumar Jadhav July 21st

    This is very useful tutorial… Thanks, Derek.

    ( Reply )
  55. PG

    Andrew Toan July 21st

    Thanks for post. THis is just a basict. You should use a framework…

    ( Reply )
  56. PG

    Arnost July 22nd

    Very good..

    ( Reply )
  57. PG

    Gregory Patmore July 22nd

    Great post.

    I have issue with the way you present a solution that provides a template directory, and then proceed to embed php code in them. I think that one of the hardest things for new php developers moving into the professional world and tackling their first large project is to learn how to separate presentation from application logic. I’ve been met with many a walleyed stare from a new developer when I try to explain how to use templating systems. I believe that this is truly the biggest thing keeping php from being widely accepted as an enterprise ready platform.

    My opinion is that if you can’t manage to write a small template parser, then use something like Smarty or one of the HTML_Template_* pear packages. It will pay huge dividends for applications that might one day need to be changed, as well as really do a lot to clean up your code.

    ( Reply )
  58. PG

    Timuism July 22nd

    Nice to see how others get set up! thanks for this.

    ( Reply )
  59. PG

    DemoGeek July 22nd

    I would rather do it this way,

    move config file to public_html
    move images folder down to resources

    ( Reply )
  60. PG

    matthew fedak July 22nd

    Ha ha I alreadydo this, I must be a web developer genius..(joke)

    ( Reply )
  61. PG

    ragingfx July 22nd

    Very useful tut. I’ll surely grab these ideas for my next php project.

    Can anyone advice on which is much better, going for personal organization of files or going to CodeIgniter?

    ( Reply )
  62. PG

    Jaspal Singh July 24th

    Useful post for php Programmers. Thanks for sharing.

    ( Reply )
  63. PG

    KHALID July 25th

    Very nice one I like it

    ( Reply )
  64. PG

    Joseph Griffin July 27th

    Nice article!

    ( Reply )
  65. PG

    Sam July 28th

    Thanks for the useful information, it is nice to see how other developers organise their work.

    ( Reply )
  66. PG

    jayson August 3rd

    what if i have a multiple data to be displayed? is there anyone can teach me how to do it…for example i will post 2 diffrent information like name 1 and name 2..

    how can i loop this 2 in order to pass it to where i wanted it to be printed..

    tnx a lot for the future help..tnx

    ( Reply )
  67. PG

    Paul August 5th

    hmm TEMPLATES_PATH doesnt see to contain a path. When I echo it theres nothing there but if I echo LIBRARY_PATH it shows up fine.

    This is true when using the example code or my own.

    Very strange, any ideas?

    ( Reply )
  68. PG

    Sadia August 7th

    Awesome! But I think having tag in the start and ending of each file is not so useful. Say in a header file, you should have html/php tag required for that file only. Your proper tags should be in the file you are including in. Php will compose whole page for you

    ( Reply )
  69. PG

    Erik Stark August 7th

    I’m actually fairly competent with PHP, but for some reason having issues with understand why index.php (in the public_html) is calling in ‘home.php’ as content to be rendered. I understand seperation of php/HTML, but does that mean if I want to create ‘about.php’ in my public_html folder, I’d also need to create an about.php in my /resources/templates folder for the actual content? It seems like double the work. I could easily be missing something, though.

    ( Reply )
  70. PG

    AbhiTechBlog August 12th

    What an excellent tutorial… the one I was searching for, for a long long time.

    ( Reply )
  71. PG

    Darma August 12th

    How to start php projects i am newly entered into php projects so i need to know how i am going to start and how many folder i have to maintain plz let me know the correct directory structure of php .

    ( Reply )
  72. PG

    Keiran August 16th

    I have single criticism. Thats in the part where you talk about creating symlinks

    ln -s

    Is not just for OSX it works on all major unix/linux distributions

    ( Reply )
  73. PG

    assssss August 18th

    adsd

    ( Reply )
  74. PG

    Kazi Ataul Bari August 20th

    Great post for me.

    ( Reply )
  75. PG

    Kazi Ataul Bari August 20th

    what the problem, I can’t found. show this warning and fatal error in localhost.

    Warning: require_once() [function.require-once]: Filename cannot be empty in K:\xampp\htdocs\public_html\index.php on line 3

    Fatal error: require_once() [function.require]: Failed opening required ” (include_path=’.;K:\xampp\php\pear\’) in K:\xampp\htdocs\public_html\index.php on line 3

    pl z help me.

    ( Reply )
  76. PG

    Pablo Valenzuela August 30th

    Hello!

    thanks very much!

    I am Spanish

    always had problems when starting a project PHP clutter of files and folders kept me from finishing.

    But with your help I believe that we managed to work well. Thanks

    ( Reply )
  77. PG

    newbie October 26th

    I know my questions about this GREAT article are very – extremely – basic… but the answers will surly save me some time… So:
    1) how do I refer to the arrays defined in the config file (images->content and layout…) ((the correct directory path isn’t ‘/img’ in this example??)) f.e. when i insert a bg img in the css…
    2) can someone help me with the exact connection string when I have 2 – a local and an online – server connection?
    3) the titles usually change page-by-page, as the keyword… in the header i used: ?php if (defined (‘TITLE’)) {print TITLE;} else {print ‘Site Title Not Set.’; }? and define in the page files, my question. is there a better way doing this?
    Thanx a lot!

    ( Reply )
  78. PG

    Jarod October 28th

    instead of realpath(dirnam(__FILE__).”…/”) you can use $_SERVER['DOCUMENT_ROOT'] instead, right?

    ( Reply )
  79. PG

    Vin November 13th

    Im using the same technic. Do you have a solution for hiding the public_html folder in de url, so:

    localhost/mywebsite/public_html/page.php

    becomes

    localhost/mywebsite/page.php

    Im struggling like 3 days now with htacces bit not one clearly solution for me ..

    Hope you could point me in the right direction

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    November 13th