4WebHelp: PHP Basics

What is PHP? How do I use it?

Resources

Introduction

When I arrived at Freedom2Surf, I had little experience in web designing. I soon heard of server-side includes (SSI) and was burning to try them out.

To my dismay, I found out that Freedom2Surf did not support SSI (Note: this is no longer the case). Anwers to my protests were of the form "use PHP instead! it can do everything SSI does, and much more!".

I didn't know what PHP was, and a trip to the official PHP site gave me the impression the monster was too ferocious for me to tackle. I was wrong. But once you know PHP, the basics are so simple that nobody ever bothers to explain them, which can make PHP seem inaccessible to the non-initiated. This article will hopefully fill in that blank.

If you know nothing about PHP and are wondering what all the fuss is about, or if you want to know how to use PHP to replace SSI, you will find the anwers here.

Short description of PHP

PHP is server-side:
Your browser doesn't realise the pages it is viewing are initially written with PHP. All it receives is an HTML page - as complex or as simple as you want.

PHP is HTML-embedded:
A PHP page can be simply an HTML page with a little PHP sprinkled here and there (we'll see how).
The PHP bits are parsed ("translated") by the server - in the examples presented here, they will be mainly used to produce more HTML code. The HTML code on the page is sent directly to the browser.

PHP has similarities with other programming languages:
C and Perl are two of them. In my case, learning a bit of Perl really helped me get started and understand what PHP could do for me - and how it worked.

Inserting PHP code in HTML

To insert bits of PHP code in an HTML page, all you have to do is insert it in a special tag, like this:

<? any amount of PHP code ?>

Note: depending on your HTML editor, or if you are using XML, you might need to use one of these alternate "PHP tags":

<?php "blah blah blah" ?>

<% "blah blah blah" %>

Here is an example which uses a variable:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title> <? print($pagetitle); ?> </title>
</head>
<body>
HTML code... <? PHP code ?> ...HTML code... <? PHP code ?> ...HTML code... etc...
</body>
</html> /p>

The print statement in the "Title" line simply sends the value of the variable $pagetitle to the browser.

Let's say we had previously assigned a value to $pagetitle, by using the following expression (somewhere in the beginning of the same page, for example):

<? $pagetitle='This is my page!'; ?>

Then what the browser would receive is:

<html>
<head>
  <title>This is my page!</title>
</head>
etc...

As you can see, as far as the browser is concerned, this is just HTML...

Here is another example, using an include:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>This is my page!</title>
</head>
<body>
HTML code... <? require("nav.inc"); ?> ...HTML code... <? PHP code ?> ...HTML code... etc...
</body>
</html>

The require expression tells the server to stick in the contents of the file named "nav.inc", instead of the PHP tag. Let's say this file contains the main navigation table for your site and looks like this:

this is the beginning of the file

<table class="nav">
  <tr>
    <td><a href="/" title="Home page">Home</a></td>
    <td><a href="/computers/" title="Everything about computers">Computers</a></td>
    ...
    <td><a href="/recipes/" title="My favorite recipes">Recipes</a></td>
  </tr>
</table>

the file ends here

This is what the server sends to the browser:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>This is my page!</title>
</head>
<body>
HTML code...

<table class="nav">
  <tr>
    <td><a href="/" title="Home page">Home</a></td>
    <td><a href="/computers/" title="Everything about computers">Computers</a></td>
    ...
    <td><a href="/recipes/" title="My favorite recipes">Recipes</a></td>
  </tr>
</table>

...more HTML code... <? PHP code ?> ...HTML code... etc...
</body>
</html>

Again, the browser has no idea that PHP exists.

Comments on the HTML code for the navigation table:

A little PHP syntax

Here is a little information about what matters and what doesn't when writing PHP.

PHP.net is your friend!

PHP.net can be overwhelming for the beginner. I spent hours getting lost in that site before I found out how to use it efficiently. Though the interface seems to be a little more friendly than it used to be, here are a few tips which might come in handy:

More about variables, print and echo

Variables can have just about any size. For example, all the text you are reading now is the value of one big variable named $content.

Variable names start with a dollar sign ("$"), followed by an alphabetic character or an underscore, optionally followed by alphanumeric characters or underscores.
They are case-sensitive. They do not have to be declared or assigned a type.
PHP also supports array variables (e.g. $somevar[3] = "something") and objects, but their discussion is beyond the scope of this article.

print and echo do just about the same thing: they send their argument to the browser. There is a small difference between them, but I'm not yet sure what it is... ; )

When using print, echo, or when assigning a string value to a variable, you have the choice between using double quotes or single quotes (if the argument is a naked variable, you can also use no quotes at all).
Single quotes will reproduce the text between them with no modifications. Line breaks, spacings, variable names and fun characters will all come out how you printed them. But! if the text between the quotes contains single quotes, you have to replace them by the escape sequence "backslash-quote": "\'". And what if you want a backslash? Use a double backslash: "\\". That's all.
Double quotes will replace variables by their value, and ignore newlines and tabs. Here are some escape sequences: newline = "\n", tab = "\t", double quote = "\"", backslash = "\\", dollar = "$"...
Until you know better, I recommend using single quotes unless the string contains a variable to be replaced.

If you want to define a very long variable (for example, lots of text), you might want to use the here doc syntax.

An empty variable, e.g. $potato = ''; will return false when its boolean value is called for. It will not create an error if you attempt to print it.

More about includes

As it should be clear from the example above, an include is a simple ASCII file, and there is no special "dressing" to put around it. Just cut out a chunk of HTML from a page and stick it in a separate file: you have an include.

Include files can have any extension. You can name an include "blahblah.bla" if you wish.
It is common to name them "something.inc", but using other extensions can sometimes make sense. For example, a file with a ".txt" extension will be viewable directly in most browsers, whereas trying to view includes with other extensions may simply result in the browser prompting you to "Save as...". I have often used ".des" for some of my files to indicate that they were "design" files. Naming includes is a perfectly personal choice.

The require function replaces itself with the contents of the file it calls, whereas include is more like a branch that points to it. This can make a difference if you are using a loop to call different includes: if you use require, the statement will be replaced by the first file during the first loop, and you will end up with (e.g.) three times the same file instead of three different files. If you are not quite sure which to choose, follow this rule of thumb: In control statements and functions, use include. Otherwise, use require (which is supposed to be a little faster).

An include can call another include. The include is read just as a normal PHP file, which means that you can put in an include anything that you would put in a "normal" PHP file.

Calling an include with relative or server-relative urls sometimes creates trouble. I usually use include("$DOCUMENT_ROOT/path/filename"); or include("http://$HTTP_HOST/path/filename") - do a few tests on your own server to see what works for you. You will get a listing of server variables like $DOCUMENT_ROOT or $REQUEST_URI with the function phpinfo().

Making a template

Here is a method I have used to create quite simply a general design for a site. I have included it here as an example of how you can quickly get PHP to work for you. Of course, this is only the beginning of PHP...
PHP4 offers a built-in template feature.

I will give you here the basic principle of my method, and links to example pages, but will not discuss all the details - though this may be done in a future update of this article if it is needed.

The idea is to create a unique page with a "skeleton" of the design you want for your site, i.e. all the HTML that is constant from one page to another. The parts that change from page to page are replaced in it by variables. This page is then "required" at the end of another page which gives values to these variables. Here are the main steps to take:

  1. Make a standard page for your site. Don't forget to polish up your HTML and validate it ; ) ...
    Here is an example of what your standard page could look like.
  2. Identify the "variable" parts of your page. The bits of HTML that change from page to page will be replaced by PHP variables, like in the "Title" example higher up in this page. This is how the finished design template would look like.
  3. Create a new file, which could be named here "example.php3", and give the necessary values to the needed variables to produce the finished page once the server has parsed the PHP. Here is what this "PHP page" could look like.
  4. You can now create as many "PHP pages" as your site requires, which all call up the design template. This allows you to create new pages without worrying about design and layout, and it also allows you to change the design completely by modifying a single file.
    If you keep entering the same value for a given variable, it might make sense to include its value directly in the "design template"...

© 4WebHelp and Tara

Latest comments on this tutorial
Forex
idyff5xfcifmq, http://mdl3.com/ Indicator forex, prKshcO.
Reverse phone lookup by address
yadgq5xfcifmq, http://reversephonelookuptutorial.com/ A reverse phone lookup, lyClXaY.
Aniza
what programs do I need to start using php?
Aniza
Hi, I'm used to using html but found out that using php is much easier.  I don't understand how to start using php.  I've been using microsoft frontpage for my html editor, editing my webpages and then uploading them to the server.  How do I change from using .htm to .php??  You can look i my site at http://www.triumphvillage.com

thanks
Daniel, 4WebHelp Team Member
la: I'm sure that having figured out comment spam, PHP will come easily to you. Wink
la
i inserted this code ][   <?php require ( "nav.inc") ; ?>][ into the html file.
But how can php be executed, if your browser doesnt read php and there is nowhere in the script a reference line that tells php where to look to execute the script?
It will maybe be a stupid question - that'sbecause I still don't get the real basics of the working of php.
[Spam deleted]
James Maynard
OK, It made some sense at first, then got too bogged down in examles for me. I can do HTML all day long (I do!) and have taken a course in C++, etc., but I'm completely lost.
What I would need would be a SIMPLE example with steps listed one by one.
1) take the following code. 2) Put it into an HTML file caled name.html 3) sent to server, or whatever. Just my two cents.
Craig
I think this is a great intro to PHP.  Im a complete beginer trying to work on an OScommerce template - this has explained a lot to me.  Thanks
Patrick
Thanks Tara, That was a big help. I read some of the other comments and I am disappointed with some of them. Newbies like me owe a lot to people like you that take the time to help. Thanks again-Patrick
John
Very nice site!
Ryan
if anyone can help me talk to me on msn messenger ryyz2004@yahoo.com Thanks
Roger Burgess
<?php

$email = "you@yourdomain.com";

if (eregi("googlebot",$_SERVER['HTTP_USER_AGENT']))

{

mail($email, "The Googlebot came to call",

"Google has visited: ".$_SERVER['REQUEST_URI']);

}

?>

<?

Works
Thomas Tallon
please help that is so confusing and i want to learn it so much i can do html but php is as hard as lerning everthing in the world i need help please email me ether to help or if u carnt do it and u want to meet some one who also carnt so we could help each other

thanks !!
Benny
I am totally lost in this... If this is the simplest way to explain it, i'm screwed... Anyone who can help, please send me an e-mail Smile
RAJEEV
its ok for the beginers. aslo the article can be beautified by adding the some information about why need php?
Jim
This tutorial is alright. Expand it so that it would be more useful
Aime
Still dang lost.... you are speaking French to me. I have no clue about what you are saying. .... Damn I am going to have to pay someone to do this. I was trying to avoid this at all cost.


DaNza
Iam so lost with the whole php code! Html and css no probs, but php is just hell at the moment!!! CAN ANYONE HELP ME?
HELP!!!!
Woad
Not working for me at all. I tried <? and it didn't do anything, I tried <% and it changed color but that was it.
Rebecca K.
Hey thanks SO much! I can do HTML in my sleep but I had trouble wrapping my mind around PHP - this broke the barrier. Now I can start USING it. Thanks!
Eik
Difficult....
But I realize that I can do a lot of sh*t on the net with php code... ;p
Krystof
Thank you for explaining [b]there is no need to name an include file ".inc"[/b]. I am converting from SSI to PHP. Now I don't have to change my include files from [b].htm.[/b] And a nice clear introduction to PHP all around. I will post a link from www.Kwik-n-free.com.
Brendan
I want to place basic text advertisements on my website, but I want to be able to change them frequently.  I have so many pages, I was wondering if I could place a php script in each page which would enable me just to modify one page instead of all of them
avi
thats a great work.. it really helped.
thanks
Jacob Pilegaard
Great introduction, I wish other introductions could be as precise and clear as this.
Thanks Jacob
Nintendud
Thanks a bunch for the basics! I was searching around for a small introduction and this did the trick. Now I can start reading my book on PHP. Yay!
yanie
can any one tell me how to create cms i really really new to php
Dave Walters
Thanks Tara. This has really helped to get a basic understanding of how PHP mingles with HTML. Am just beginning down the PHP path. Appreciate your information.
Dave Walters
Thanks Tara. This has really helped to get a basic understanding of how PHP mingles with HTML. Am just beginning down the PHP path. Appreciate your information.
sureind
iam new to php plz give tutorails
surekumar
hai
iam new to php programming can bring some
useful sites url
dawa sonam
I m getting a grasp on PHP now
Pip
i dont understand a word you just said



hel;p
Amit
What are .tpl files and how are they different than .php files
seems to do the trick
<html>
<body>

<?php require("header.htm"); ?>
actually
actually it works for some things and not others

whats the best way to make a template file

and then put html into in?
same
<? echo ($reviews); ?>

seems to do it

unless there is a better way

hi
can someone tell me how store html tags in a PHP varable

for example

<?
$reviews = "<br><br>some html here <a href="whatever.html">agff</a>";
include ("temp.html");
?>

etc

i understand that varables are not for this
but how is it done

thanks I am very new
Reshma Reddy
This site is very useful for the beginners
viksra
Thanks for helping me get one step closer to becoming a billionaire.
JM
OH Yes!

This is what the world has been waiting for  - Thanks Tara
Susan
Thanks a heap for this well-written tutorial!  I've been exploring PHP for several days and really find it useful.  I've been using several of these bits of code without knowing what they really mean.  
Moe
Hey man thanks a lot for taking the time to put this together. I feel a lot more confident that yes, I CAN do this! Cheers Wink
Daniel, 4WebHelp Team Member
Greg: The page's filename has to end with ".php", not the actual contents Smile. Also, in the code you posted, you should remove the "<?" at the end.
Greg
Thanks for keeping it simple.  I just received a bit of PHP code to add to my website to tell if a spider has visited.  It said to end the page with
.php
but it kept showing up on the published page.  I believe from your examples that
?>
will do the job.

Here's the code if anyone is interested.


<?php

$email = "you@yourdomain.com";

if (eregi("googlebot",$_SERVER['HTTP_USER_AGENT']))

{

mail($email, "The Googlebot came to call",

"Google has visited: ".$_SERVER['REQUEST_URI']);

}

?>

<?



Thanks again
Jake
Cheers,
Ive been looking through a load of PHP guides all day but none of them had the basics!
Casper
Thanks for the quick introduction!
lakshman
now i came to know php is really cool!
Dan
Thanks. I have been saved!
Daniel, 4WebHelp Team Member
figidigi: Your file's extension has to be .php Wink
figidigi
Hi there,
this is the first page that I find which is written clearly. I made notes and all to understand the stuff. I am a veryvery newbee at php , i bought a book, but still cant figure somethings out.

Still I have a few questions, hope thats okay...

My server has php dev installed. I myself did not install anything. I wrote a testfile according to your tutorial.
test is on: http://www.showerzone.nl/test/testphp.htm

i inserted this code ][   <?php require ( "nav.inc") ; ?>][ into the html file.
But how can php be executed, if your browser doesnt read php and there is nowhere in the script a reference line that tells php where to look to execute the script?
It will maybe be a stupid question - that'sbecause I still don't get the real basics of the working of php.

hope u can help me out.
thanx - figidigi
Daniel, 4WebHelp Team Member
<?php
header('Location: http://www.site.com/');
?>
will redirect visitors to the location of your choice.
Fayez
First .. I am new to PHP so do not lough!
I am writing a script in which it should transfer to another web page under certain condition. I know in ASP that I can use redirect statement but I would like to know about that in PHP.

Thanks
matej
Thanx this tutorial really helped me...
Mathew
Tara thanks for this wonderful Tutorial
Somsak Wisitwatanawong
Thanks for your generosity, introducing the features of PHP to those guys lost in web info, including me.

Add a new comment


Page URL: http://www.4webhelp.net/tutorials/php/basics.php?example=full
Back to the "pretty" page!

© 2024, 4WebHelp Team.