Creating And Using Includes With PHP - A simple tutorial

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > PHP

Creating And Using Includes With PHP - A simple tutorial

Houdini
OK so you are now wanting to learn to use PHP and a few includes which are file(s) that you place into your script on any given page to indlude stuff that you have written previously. I did see another tutorial on such matters but possibly this tutorial will make more sense.

PHP has the abilty to include other PHP files into the current script that is being processed by the server. Let us just take a simple example. This will be a file that will connect yo your database and a specified table. It will include all the necessary parameters to actually do just that. This is a program on its own right and as such will perform a specific funtion (connect to the MySQL Server and select a database to work with).

So for testing purposes we will create this file to be included when the script we are using needs this to happen. Look at it as its own program (which it is) that helps save typing a new program. Usually you would like this program or include file to ahave a name that is not easily recognized as a database connection, so call it something like error.php or happy.php and to really throw off hackers you could also include a file that doesn't even do anything and call it db.php (this is a file with nothing at all in it). Security matters aside then there are other ways to protect this important file which will be explaines later in the tutorial. So lets build the connection file for inclusion where and when needed. NOTE anything in the code below behind // is a comment and can be copyed and pasted into a working script

CODE
<?php//always use this in your script <? is deprecated and unreliable
$host="localhost";//This will work with most MySQL servers but your server might be different
$user="root";//This is a default for a new MySQL install use you own username if assigned one
$password="";//This is a default, if you have a password for your MySQL USE IT
$db="yourDatabase";//The name of the datebase you want to connect to goes here between the double quotes
Ok now name the above script whatever you want and use it as an include in other scripts where and when you need it like below.
CODE
<?php
include("yourIncludeScript.php");
$connect =($host,$user,$password)
  or die("Could not connect with server, check settings, MySQL said: ".mysql_error());
//If anything is wrong the file will stop and show an error Could not connect with server, check settings, MySQL said:  and the actual MySQL error.
$query ="SELECT * FROM $db";//This is from the included file as is the variable from above
$result =mysql_query($query)
  or die("Execution of query failed".mysql_error());
...//more code
So how does this look to PHP on the server which is what this little tutorial is about?

CODE
<?php
//here is the include file as specified see above code
$host="localhost";//This will work with most MySQL servers but your server might be different
$user="root";//This is a default for a new MySQL install use you own username if assigned one
$password="";//This is a default, if you have a password for your MySQL USE IT
$db="yourDatabase";//The name of the datebase you want to connect to goes here between the double quotes
//end of the includeed file
$connect =($host,$user,$password)
  or die("Could not connect with server, check settings, MySQL said: ".mysql_error());
//If anything is wrong the file will stop and show an error Could not connect with server, check settings, MySQL said:  and the actual MySQL error.
$query ="SELECT * FROM $db";//This is from the included file as is the variable from above
$result =mysql_query($query)
  or die("Execution of query failed".mysql_error());
...//more code[

As you can see the included file is parsed by PHP as it was originally written, mistakes and comments included. If you do include a file that does not work you need to correct it before using it as an include. Many problems with using PHP are includes with flaws in them or used in the wrong place. Had the include been at the bottom of the above script the values needed to connect to the database had not been defined, so keep in mind where and when you need to include a file with a specific purpose when written your script in PHP.

Questions or for more about using an include(s) then PM me Houdini for more. Been working on other things lately, so now I am back for most questions about PHP and MySQL useage.

 

 

 


Reply

minnieadkins
A great help. I use includes all the time, they can be very handy and can kind of replicate OOP without objects. Consolidates your code and helps maintain it.

One thing to note is that you can also use require instead of include. Include will throw up a warning whereas a require will throw up a fatal error and prevent your page from loading. Obviously you'll have to choose which one is right for you, but by using the right exceptions and states includes can be your friend.

As mentioned above it's a great way to do your database configurations and connections. I'm currently working on a site that has about 10 + includes for various purposes, and they are very useful.

Be careful in naming your includes however, as if you name something
CODE
Database_File.inc
and someone knows how to navigate to your file, it will not be parsed (unless you specify it to be) and they will be able to see your code.

Reply

Houdini
To get around that use Database_File.inc.php instead of Database_File.inc you can also use and include in some cases where a header will not work due to output having already happened and you want the user sent to another page.

Reply

minnieadkins
QUOTE(Houdini @ May 30 2006, 09:25 PM) *

To get around that use Database_File.inc.php instead of Database_File.inc you can also use and include in some cases where a header will not work due to output having already happened and you want the user sent to another page.

Either that or set your configs to parse .inc files. I don't know much about server configurations though, but I think that would work as well.

I'm not sure what you mean. You can't include a file that has a header and expect it to work properly.

CODE

<html>
<head><title></title></head>
<body>
Some file is including another file
<?php include "somefile.php";?>
</body>
</html>


if somefile contatined a header("location: http://www.mysite.com"); it wouldn't work. Headers have already been sent.

 

 

 


Reply

ruben
Just wanted to add, that it is best in my humble opinion to put the database-connection file in a non-public directory.
And require should also be used as standard, especially if you're not too sure, what a hacker could do with your code without the included file. I mean, in few cases you want to continue the script with a warning from the include file (your page would not be of much use without the db-info for example. And maybe hackers who managed to get include file unavailable, can insert false values into the file (if register_globals is turned on).
Greetings,
Ruben

Reply

vujsa
For really sensitive files, there are many options for keeping them secure.
Placing such included files in non-public directories is always a good idea but adding a few simple security measures to that will really save you a lot of headaches if someone decides to hack your website.

The first thing you should always do is set your file permissions to the fewest access privledges that will still allow the script to work. Most scripts should never allow writing privledges.

Using a few .htaccess tricks, you can prevent the viewing of file contents based on the directory it is located in or by filename or extention.
You can also limit access to any file based on who is requesting it. Just set your .htaccess file to only allow certain files to be read only by the localhost or server IP address.
You can also use the rewrite engine to "HIDE" your files. You can set your rules to allow you to request one filename and have a file with a completely different name be served.

A certain degree of encryption can be encoded into included files that will make them more difficult to read when viewed in the raw form. The requesting script would need to have code that would allow it to read the encrypted information.

For more information, I suggest researching the following topics:
- File access restriction with .htaccess
- File rewrite with .htaccess
- Setting file permissions for security
- Script security using encryption

Some .htaccess file restricion options can be set using cPanel

This tutorial is another fine example of how php includes can be a real time saving tool for script developers and webmasters.

vujsa

Reply

Chesso
All the same it's a nice tutorial, I just use plain includes myself rather then anything overdone or fancy but I don't really have to worry about anything ciritical being broken into.

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : creating, includes, php, simple, tutorial

  1. Creating A Php Login Script
    A thorough look at the process behind it (3)
  2. Creating Your Own Image Gallery With Php
    A Guideline, Not A Complete Script (3)
    Recently a member asked how to create a photo gallery using his various directories filled with
    image files. Here is an overview of the steps and fuctions needed to do this. Assuming that the
    following directories exists and are full of image files: www.testsite.web/photos/gallery1/
    www.testsite.web/photos/gallery2/ www.testsite.web/pictures/album1/ In order to get the contents
    for a specific gallery you'll need to let the script know which one to look in. You'll need
    to use a link that carries the arguments needed to locate the right photos. www.testsite.we....
  3. CMS101 - Content Management System Design
    Basic CMS With PHP Includes (14)
    Overview: Frequently people ask about Content Management Systems here and are looking for
    advice regarding which CMS would work best for them. Often, the user requesting the help
    doesn't realize that they can design their own CMS that will provide them with the results they
    are looking for without needing to install a bulky program. This usually stems from the relatively
    few features that users want from their CMS. Many users just want an easy way to manage their
    website and edit their content. In this tutorial we'll discuss a very simple way to c....
  4. Creating A Content Managing System
    Using MySQL (15)
    This tutorial is for beginners that know some php and know the basics of MySQL. I will tell you how
    to make a simple Content Managing System. A Content Managing System is a way of editing and adding
    your content using your browser, so you dont have to go trough ftp all the time. This CMS uses
    MySQL databases. So what we need to do is to create a database. Well go through this step by step to
    make it as easy as posible: 1. Go in to your cPanel and select phpMyAdmin. 2. Write the name of
    your database in the input box under the text: Create new database. This database ....
  5. Tutorial: PHP Includes
    (17)
    This tutorial shows you how to put one HTML file inside another using PHP. This technique is very
    useful for menus, where you might want the whole menu to change sitewide - much easier to change 1
    file than 50 /smile.gif' border='0' style='vertical-align:middle' alt='smile.gif' /> . I have
    also used this for footers and headers; you can use it anywhere you want to be the same on each page
    of your site. CODE <?php include("file"); ?> Now I will tell you
    what it all means. and ?> - open and close the PHP statement (a bit like HTML t....

    1. Looking for creating, includes, php, simple, tutorial

Searching Video's for creating, includes, php, simple, tutorial
advertisement




Creating And Using Includes With PHP - A simple tutorial



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE