Apache MySQL PHP (AMP)

PHP, Apache, MySQL are all part of the open source group of software programs. These all of which work together to help you develop dynamic web sites.

Look at them like this:


www.opensource.org

Open source is a development methodology,[1] which offers practical accessibility to a product's source (goods and knowledge). Some consider open source as one of various possible design approaches, while others consider it a critical strategic element of their operations. Before open source became widely adopted, developers and producers used a variety of phrases to describe the concept; the term open source gained popularity with the rise of the Internet, which provided access to diverse production models, communication paths, and interactive communities.

The open source model of operation and decision making allows concurrent input of different agendas, approaches and priorities, and differs from the more closed, centralized models of development.[2] The principles and practices are commonly applied to the development of source code for software that is made available for public collaboration, and it is usually released as open-source software.

www.opensource.org

Why Open Source Rocks


Apache

Apache acts as your web server.  Its main job is to parse any files requested by a browser and display the correct results according to the code with in that file.  Apache is quite powerful and can accomplish virtually any task that you as a webmaster require.


PHP

PHP is a server-side scripting language that allows your web site to be truly dynamic.  PHP stands for PHP: Hypertext preprocessor. Its flexibility and relatively small learning curve makes it one of the most popular scripting languages around.  www.php.net


MySQL

MySQL is the database construct that enables PHP and Apache to work together to access and display data in a readable format to a browser.  It is a Structured Query Language server designed for heavy loads and processing of complex queries.  As a relational database system, MySQL allows many different tables to be joined together for maximum efficiency and speed.  www.mysql.com

Popular Features of MySQL

MySQL is the perfect choice for providing data via the Internet because of its ability to handle heavy loads and its advanced security measures.


PHP Structure and Syntax

In a five-star restaurant, patrons see just a plate full of beautiful food served up just for them.  They don't see where the food comes from, nor how it was prepared.  In a similar fashion, PHP fits right into your HTML code and is invisible to the people visiting your site.

extension of a PHP file is usually .php

The way you indent your lines does not matter to PHP, but it matters to the human eye, so if possible try to keep your indents consistent and easy to read.

How PHP fits with HTML

What makes PHP so different is that it not only allows HTML pages to be created on the fly, but it is invisible to your web site visitors.

HTML can also be written inside the PHP section of your page

PHP can also be written as a standalone program, with no HTML at all.  This is helpful for storing your connection variables, redirection your visitors to another page of your site, or performing other functions.

The Rules of PHP Syntax

Always keep in mind two basic rules of PHP

  1. PHP is denoted in the page with opening and closing tags
    <?php
    ?>
  2. PHP lines end with a semicolon, generally speaking
    <?php
    //First line of code goes here;
    //Second line of code goes here:
    //Third line of code goes here:
    ?>

Adding comments in your program as in the preceding code, through double slashes (//) for one liners or /* and */ for opening and closing comment tags that may extend over several lines of code.  Indents don't matter and generally speaking, neither do line returns, this give you freedom as a programmer but a little freedom can be a dangerous thing.

Truly professional code follows three general guidelines

  1. Consistency o well written code
  2. Frequent Comments
  3. The use of Line Numbers

Reasons for this is for efficiency, for debugging and for future expansions and modifications


echo

Is one of the most commonly used PHP functions.  It is used to send text (or variables values or a variety of other things) to the browser.

Outputs all parameters.

echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.

 

How it works: When a browser calls a PHP program, it first searches through the entire code line by line to locate all PHP sections (those encased in the appropriate tags) and it then processes them one at a time. All PHP code is treated as one line. After the PHP code has been parsed accordingly, the server goes back and gobbles up the remaining HTML and spits it out to the browser, PHP sections included.

HTML can be inserted within your PHP block of code using the echo function

Inserting some html code within the PHP section of the program you accomplish two things:

  1. You can improve the look of your site.
  2. You can keep PHP lines of code together without having to jump back and forth between HTML and PHP

Consideration with HTML inside PHP

Pitfalls commonly seen with the practice of inserting HTML inside PHP

    1. You have to check for double quotes
            •    Use single quotes inside your HTML
            •    Escape your HTML double quotes with a backslash, as following
                      echo "<font size=\"2\";

    2. Remember that you still have to follow PHP rules, even though you're coding in HTML

    3. Don't try to cram too much HTML into your PHP sections


Using Constants and Variables to Add Functionality

Using constants and variables allows you to take advantage of the power of PHP

Constants

A constant is a placeholder for a value that you reference within your code. Constants are typically named with capital letters (so you can easily find them within your code), and the values are usually formally defined before using them.  Constant names must begin with a letter or and underscore and can not begin with a number.  Names are also case-sensitive.

You define a value assigned to a constant with the PHP function define (). Once you've defined a constant, it can't be changed or undefined. defined() only applies to constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

 

<?php
    define ("FAVMOVIE", "The Life of Brian");
    echo "My favorite movie is ";
    echo FAVMOVIE;
?>

How it works: By defining the constant known as FAVMOVIE, you have set the value as "The Life of Brian", which can be recalled and displayed later on.  Although this constant can't be changed or reset through your script, it is available for use by any part of your script

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>

Note that constant name must always be quoted when defined.
e.g.
define('MY_CONST','blah') - correct
define(MY_CONST,'blah') - incorrect

Variables

Unlike constants, variables are obviously meant to be variable -- they are meant to change or be changed at some point in your program.  Variables also do not need to be defined or declared and can simply be assigned when needed.  Variables can hold either numeric or text values.

Variables are denoted with a dollar sign ($) and are case-sensitive, as are constants (in other words, $dateEntered and $DateEntered are not the same thing).  The first letter of the variable name must be an underscore or letter and cannot be a number.

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

 

PHP has numerous built-in mathematical functions that you can use on variables that contain numbers such as the following:

rand([min] , [max]) Generates a random integer.
ceil(number): Round a decimal up to the next highest integer.
floor(number): Rounds a decimal down to the next lowest integer.
number_format (number [,dec places] [,dec point] [thousands]): formats the number based on the chosen number of decimal places, an uses the designated decimal oint and thousands separator if applicalbe.
max(argument1, argument2, ...): Returns the maximum value of the supplied arguments
min(argument1, argument2, ...); Returns the minimum value of the supplied arguments

These are the differences between constants and variables:


Passing variables between pages:

There are basically four ways to accomplish this task: pass the variables in the URL, through a session, via a cookie, or with and HTML form.  The method you choose is based on the situation and what best fits your needs at the time.

Passing variables through a URL

The first method of passing variables between pages is through the page's URL.  You've undoubtedly seen URLs such as:

    http://www.mydomain.com/news/articles/showart.php?id=12345

The text after the URL is called the query string

You can combine variables in a URL by using an ampersand (&), as in the example:

    http://www.mydomain.com/news/articles/showart.php?id=12345&lang=en

There are a few disadvantages to passing variables through URL

PHP  code can be inserted in a straight line in the midst of your HTML code. This is helpful when you just need to insert one tidbit of information grabbed from PHP.

Passing a value through a URL is fine if the information is not a particularly sensitive nature or if it is relatively static and there is no danger of a user pulling up old information from a previously saved page.

Special Characters in URLs

Passing variables through a URL poses an interesting problem if there are spaces, ampersands, or other special characters in the value of your variable. Luckily, substitutes exist for special characters that maintain the integrity of the variables' values.  There is a special function call urlcode() to use when passing these values through a URL

Passing Variables with Sessions

If you are transmitting information such as usernames or passwords, however, or personal information such as addresses and phone numbers, better methods exist for passing the information while keeping it private.

A Session is basically a temporary set of variables that exists only until the browser has shut down.  Examples of session information include a session ID and whether or not an authorized person has "logged in" to the site.  This information is stored temporarily for your PHP program to refer back to whenever needed.

Every session is assigned a unique session ID, which keeps all the current information together.  Session ID can either be passed through the URL or through the use of cookies.

To begin a session, use the function session_start()

You need to decide what information will be stored in your session.  Anything that has been stored in a database can be retrieved and stored temporarily along with your session information.

An SID (session ID) will also be stored in the session array of variables.

All the session information is at the top of the page. before any HTML code.

WARNING: session_start(): cannot send session cache limiter - headers already sent:

you must use the function session_start*( at the beginning of every page that references the session variables.

Passing Variables with Cookies

Cookies are tiny bits of information stored on your Web site visitor's computer.

To set a cookie, you use the appropriately named setcookie() function.  When setting a cookie, you can determine that the following information be set along with it:

You make each of these setting as follows:

    setcookie('cookiename', 'value', 'expiration time', 'path', 'domain', 'secure connection');

Like sessions, cookies must be placed at the very top of the page, before your first <html> line.

Unlike sessions, cookie information can't be accessed in the current page where the cookies have been set.  You have to move on to the next page for the cookie to be set and accessible to your program.

Passing information with Forms

Forms are the great Venus Fly Traps, just lying in wait to gobble up useful information from Web site visitors.  Forms allow your Web site to be truly interactive.

Fast Primer on Forms:

Forms are coded in HTML and stay in HTML.  A form is made up of four parts:

  1. Opening tag line, indicated by the <form>tag.
  2. Content of the form, including input fields.
            Text, Checkbox, Radio, Select, Password
  3. Action button (s) or images, typically submit/clear or user-defined button, technically considered input type as well.
  4. Closing tag line indicated with a </form> tag.

Using if/else Arguments

At some point in the course of your script, you're going to want to take specific actions based on the value of a variable.  For example, consider a $password variable.  If the user supplies the correct password, you'll want to grant hi access to the site.  If the password is incorrect, you might want to ask the user to try again, or maybe lock him out.  You can use the if statement to dictate the action your script takes based on the value of a variable.  If you add the else statement to an if, you open up a whole range of possible actions.

Using If Statement

Unlike some other programming languages, in PHP, the if statement can be used alone,  The syntax is as follows:

if (condition1 operator condition2) action to be taken if true:

as in this example:

if($stockmarket >= 10000) echo "Hooray! Tome to Party!"'

If the action to take a longer then a simple statement that will easily fit on one line, you must use brackets ({}) to enclose your action section:

if ($stockmarket >= 10000) {
    echo "Hooray! Time to Party!";
    $mood = "happy";
    $retirement = "potentially obtainable";

Operators

Operators use to compare the two conditions are similar to those comparision operators you likely encountered in elementary - school math.  A list of these operators follows.  Only for use within the if statement.

Special Syntax Considerations

Pay special attention to the use of semicolons in if statements.  Semicolons are required in individual lines with in the if statement, but not at the end of the if statement itself.  Special not of the use of the double equals sign when comparing conditions1 and conditions2

The way you indent your lines does not matter to PHP, but it matters to the human eye, so if possible try to keep your indents consistent and easy to read.

Using if and else Together

Using if by itself is fine and dandy in some cases, but there are other times when the if/else combination is more appropriate.  For example, suppose you want to show a certain message on your site, but you have a holiday message you'd like shown for the month of December.  Or suppose that on your movie review site, you want to show an abbreviated version of a movie review for those who haven't yet seen the movie.  It's these "either/or" cases where you need to whip out the all powerful if/else combination

Using Includes for Efficient Code

A little time-saving device called "includes" that save you from reentering frequently used text over and over.

Suppose that you want to type the same message on every page of your site.  Perhaps it is your company name and address, or maybe today's date.  If you are coding each page of your site from scratch this is not very efficient.

Includes are PHP files tucked into other PHP files.  You take commonly used information and put it in a separate file.  Example: if you have a set of defined variables that need to be referenced in every page on your site, you could define them once, in a single PHP script.  Then on each of your pages where you want the variables to appear, you use an include statement that specifies the file that defines the variables.  When your script is parsed, the parser inserts the code from the include file into your page, just as if you'd type it there yourself.  The final output is then sent to the browser.

Includes can use any extension, but are sometimes referenced as .inc files.  If you are adding potentially sensitive information, for example server variables such as passwords, then it is advisable to save these in .php files so they are never accessible to anyone because the information is parsed before it is sent to the browser.  You can add an include in any other file, and if you place the include statement in an if statement you can control when the include is inserted.

When PHP comes across an include line in a script, it stops working on the current program and immediately shoots on over to whatever file it's told to include.  The server parses that second file and carries the results back to the original file, where the parsing continues from where it left off.


Using Functions for Efficient Code

 

 

 

 

 

 

 

 

 

 

Back to Top

©2008 www.damitjanet.com
Do not surf site while drinking liquids,
 damage to keyboard may result.