From the course: Learning PHP

Organizing your code - PHP Tutorial

From the course: Learning PHP

Start my 1-month free trial

Organizing your code

- [Instructor] As you can imagine, writing lots of code in a single file can get unwieldly and slow to run and manage. There is a better way. External files. PHP offers a few ways for you to include files inside your code but they are all referred to as server side includes. This, as the name suggests, includes all of the files in a single package that it sends to the browser. That means there's only one HTTP request. Unlike HTML, CSS, and JavaScript, which generally require one HTTP request per file, PHP does all of the processing, including the files on the server, and sends them as one. There are several benefits to using server side includes in your applications. First, it allows you to break up large sections of code. You can put your classes in separate files, you can group functions together, and more. As a result, you can keep output files separate from processing files. So if you have heavy HTML files, then you might not want to put them in a class file or a file that requires a lot of functions. You can separate them out. You can also organize your website into different files, taking the reusable parts and templatizing them. So far, we haven't talked much about the HTML output or organization side of PHP. We were focused more on how PHP works. But when you include files, PHP essentially inserts those files and the code wherever you include that file. So let's say on line one we have some code, on line five we have more code, and on line three we include an external file. PHP is essentially copying everything in that external file and putting it on line three. That means that if you want to break your website into different parts like a header, a footer, and a sidebar, then you can. You can use the same header and footer throughout the entire website. And whenever you change them, they'll change across every page that includes them. So if you have a website with 100 pages and you want to change one of the links in the navigation, you'd only have to do it once instead of 100 times. It's up to you to figure out how to best organize your files. And that might change based on the size and scope of the project you're working on. But for now, let's take a closer look at how to use server side includes.

Contents