PHP in a Nutshell

only for RuBoard - do not distribute or recompile

PHP in a Nutshell

The PHP language is described as an "HTML embedded scripting language" in the online documentation. It strongly resembles the C language, so if you have experience in that language you are in great shape. You place PHP commands on a Web page and have the server interpret those Web pages before sending the results to the Web browser.

In any computer language, you have three main capabilities. These capabilities can vary in degree of implementation, but they exist. In every language you can make calculations, perform actions, and change the course of execution based on decisions.

PHP allows you to do all of this. For example, in PHP, you can use Perl-like syntax to add two numbers together:

 $a = $b + 3; 

You can also perform actions. With PHP, you can print information to the Web browser, operate on files, and run other programs. To print something to the screen with PHP, you could do this:

 printf("This is a test\n"); 

You can also use print() or echo to print something on the screen. The printf() function works exactly like its C counterpart . The print statement has a similar counterpart in Perl.

With PHP you can decide to execute instructions based on results of previous answers. The two constructs are "if (test) A else B", and "switch(test)". For example, the following will print "B is less than 3" if the value of B is less than 3, and will print the "B is greater than..." statement in all other cases:

 $b = $a+ 1; if ($b < 3)         printf("B is less than 3\n"); else printf("B is greater than or equal to 3\n"); 

The switch statement allows you to select from individual answers and execute code based on the answer. The following prints one, two, three, or none of the above, based on the value of $b:

 switch ($b)         {         case 1:         printf("one\n");         break;         case 2:         printf("two\n");         break;         case 3:         printf("three\n");         break;         default:         printf("none of the above\n");         break;         } 

PHP supports looping constructs. Loops are sections of code that continue executing until a condition is met. Instructions to exit from a loop early are also available, as shown in Table 5.1.

Table  5.1. PHP Looping Instructions
Statement Description
while (condition) {statements} Execute statements while condition evaluates to TRUE.
do { statements; } while (condition) Execute the statements at least once, continuing to execute while condition evaluates to TRUE.
for (start; continue_execution ; statement) {statement} Execute the statements while the continue_execution condition evaluates to TRUE.
continue This immediately takes you to the conditional test of a statement, bypassing the execution of rest of the code in the loop for that pass.
break When this is encountered , the loop is executed, bypassing the execution of the rest of the code in the loop, and ignoring the conditional test.

PHP also enables you to include code written in other files. You do this using the include or require statement with strings or variables as arguments. The require statement always reads the file in, even if the contents of the file will not be used. The include statement might not actually cause the file to be read if a conditional test causes PHP to skip execution of the line the include is in. The following includes code from another file. If you enter your code exactly as shown, the file will be included twice:

 require "filename"; $a = "filename"; include $a; 

PHP also enables you to create your very own functions, put them in files, and include them using the previously mentioned include or require statements. You can also create and use functions in the current Web page. You use your own functions in much the same way you would use built-in database functions. With this ability, PHP allows you to build up a comfortable set of personal tools that you can use to greatly speed up Web page development. For example, the following function will print this is my function and return a value of 3 to the caller:

 function my_function() {    echo "this is my function";    $returnvalue = 3;    return $returnvalue; } 

GEEK SPEAK: A function is a subroutine that is "called." When you call a function, you place its name in the code and the PHP parser begins executing the code in the function when it encounters the function name . When a function returns a value, the PHP parser takes the value of the expression the function places in the return statement and treats the function call as if it were a variable. In the following code, $a will have a value of 5 when using the my_function() call defined previously:

 $a = my_function() + 2; 

For many people, functions are hard to understand because they are so simple. In PHP, a function's code will not be used until it is called. This enables you to carry functions in a page and not worry about their effect.

General Format

The PHP language has a few general rules to follow. The first rule is that almost every statement ends with a semicolon. If the end tag is encountered ( ?> ), the semicolon is assumed to exist. You can stack multiple statements on a line by ending each one with a semicolon. For example

 $a=$b+$c; $g=$d+$e ;  $f= $f+1; // starting at the '//' is a comment 

The exception to using semicolons is a comment. Comments don't require semicolons.

Comments are notes you make in the code that the compiler ignores completely.

Comments can span several lines, or can be only part of a line. Multiline-capable comments start with /* and end with */. Single-line or partial-line comments start with // or #. The first comment below is a multiline comment. The rest are single-line or partial-line comments. Even single-line comments only comment to the end of the block, as indicated by the ?> tag.

 /* This is a comment   that spans several   lines */ // this is a single line comment.  It ends at the end of the line. $a=$b+$c;// this is a line comment.  It starts at the // and ends here. <?php a=3;// this comment ends at the tag ?> this is displayed by the bowser $b=$c+$a;# This is a shell style line comment.  It starts at # and ends here. 

All variables in PHP begin with a $ sign. There are a few types of variables in PHP. The PHP parser automatically determines these types at run time, although you can override this automatic determination. The types of variables will change depending on use in a statement.

The types and modes of variables available in PHP are the following:

  • Integer number ”   Can be represented in octal by beginning with the number 0, or in hexadecimal by beginning with 0x. For example, 010 is an octal number with a value of 8. The number 0x10 is a hex number with a value of 16. The number 10 is a decimal number with a value of 10. For example, each of the following sets the variable a to a value of 16:

     $a = 16; $a = 020; $a = 0x10; 
  • Floating-point number ”   Floating-point numbers have decimal points. The value 123.45 is a floating-point number. The following sets the variable a to a value of 16.5:

     $a=16.5; 
  • String ”   A string is enclosed in quotation marks or single quotes.

  • Array ”   Arrays can be of one or more dimensions. An array can be indexed by a value or by an association. By association, you can associate the name George with the value super, as in the following example:

     $a["super"]= "George"; 

    If you use $a["super"] in an expression, it will return "George". You can also use numbers to index arrays:

     $b[1] = "George"; $c[1] = 14.56; $d[1][1] = 12; 
  • Object ”   An object is similar to a C++ object. You generate an object definition with a class statement, and set a variable to be an object using the new statement. For example:

     class MyClass {         function MyClassFunction()                {                echo "This is the MyClassFunction";                }         } // the end of class MyClass $ACV = new MyClass; // call the MyClassFunction in the new object $ACV $ACV->MyClassFunction(); 
  • Variable variables ”   A variable that is a string can be used as a variable name by using two $ symbols in a row. (Note: Strictly speaking, this is not a type of variable. The result of the interpretation of the string is the resulting type of the variable.) For example, let's make a variable with a value of "test". Then let's create a variable named "test", and fill it with the value of "complete". After this, print the value of the $test variable.

     $a = "test"; $$a = "complete"; echo " $a == $$a, the same as $test"; 
  • Type-cast variables ”   You can change the type of a variable by casting. If a variable is an integer, you can force it to be a double. The types available to you for casting are the variable types already covered. You can also abbreviate int for integer, or use the terms real or float instead of double. To do this, you must put the type in parentheses:

     $b = 3; // $b is an integer $a = (real)1 +(float)$b;//forces everything to double, and $a now equals 4.0 
  • Null ”   A variable that is Null does not yet have a value assigned to it. It does not yet exist in memory space. This is new to PHP 4.

  • Boolean ”   The Boolean value is either TRUE or FALSE. In PHP 3, TRUE is 1, FALSE is 0.

  • Resource ”   An identifier that specifies a system resource, such as returned from a mysql_connect() call. This is new to PHP 4.

Strings and Parsing

PHP does some interesting things with strings. A string is a group of characters that is usually displayed verbatim. Under PHP, strings change their meaning. What you get might not be what you expect unless you are very careful.

For example, assuming $a has a value of 3, the statement

 echo "This is a string. The value of $a is $a." 

will print

 This is a string. The value of $a is 3. 

The second occurrence $a variable was expanded to print out the string equivalent of its value. The first occurrence was not expanded because it was escaped by the use of the \ character. The escape character tells PHP

to use the next character literally, and not to try to interpret it before printing it.

To avoid printing the expanded value of the variable, put the string in single quotes. This line

 echo 'This is also a string. The value of $a is $a.' 

will print

 This is also a string.  The value of $a is $a. 

A string using quotation marks will have the internal value of all variables that are listed in them printed. For example, suppose the variable $a equals 3, and $b has the value of Hello. The following will print "3 brown cows", and "Hello, George".

 echo "$a brown cows.  $b, George."; 

Web Page Use

To use PHP, you must let the server know that it could possibly call the PHP interpreter for a Web page. You do this by encoding the Web page type in the extension. Most Web pages for Linux end in .html. It is typical practice to end the Web page in .php (or in .php3 if you are running the PHP version 3 interpreter) to indicate a PHP Web page.

PHP can change the contents of a Web page as delivered to the user . When you view a Web page on a browser, you will see the results of the PHP script. In very few cases, you will see the PHP code behind the script when you use the view page source command that is available in most browsers. I recommend you do this when you test your PHP pages. You might discover information you want to hide.

The showing of source code is usually because of a mistake you have made in wrapping your code. If the PHP interpreter does not expect to see source code at certain places in your document, it will not remove that code.

Apache Web Server

Normally, the main page in a Web server directory is titled index.html. In our project, it is necessary to use an index.php3 Web page as the main Web page. To enable this, edit the /etc/httpd/conf/httpd.conf file, and around line 448 (for Red Hat 6.1 Apache installation), change the DirectoryIndex line to look like this:

 # # DirectoryIndex: Name of the file or files to use as a pre-written HTML # directory index.  Separate multiple entries with spaces. # irectoryIndex index.php3 index.html index.htm index.shtml index.cgi 

NOTE

The standard for PHP version 3 is to use .php3 as your extension. For PHP version 4, the standard is to use .php. This enables you to run both versions 3 and 4 simultaneously on a Web site. This version of IMP was written for PHP 3, and needs the .php3 extension. You can also add index.php to the DirectoryIndex line, in addition to index.php3.


If you still have the /home/httpd/html/test directory you set up in Chapter 4, under "Testing the PHP and IMP Configuration," you can test this change. First, restart the server, and then load the test page by specifying only the test directory:

 [root@winbook net]# /etc/rc.d/init.d/httpd restart Shutting down http:                                        [  OK  ] Starting httpd:                                            [  OK  ] [root@winbook net]# lynx http://127.0.0.1/test 

NOTE

In this situation I used the command-line Web browser called lynx. It comes with every version of Red Hat, and is an easy and quick way to test a Web page. I use it whenever I want to see something very quickly. It loads quickly and usually does not hang for long periods of time. If it does, a Ctrl + C will exit it.


You should see the PHP info page that is generated by the phpinfo() function call. If it does not show, make sure you don't have an error in your changes to the /etc/httpd/conf/httpd.conf file. Verify the server restarted properly by running ps ax grep httpd. If it did not, refer to the "Troubleshooting" section of Chapter 4.

EXCURSION: Interaction of Web Server and Browser

One problem that occurred is very interesting. Whenever I entered a http://127.0.0.1/test line without the trailing slash, I was told the server was unavailable. I had temporarily changed the IP address on the computer, and the normal Web server-Web browser interaction threw a wrench into the works.

When your browser asks for a page, it does it exactly as you type it in. In our case, test is a directory, not a page. The browser is refused . This always happens, and is not a problem. The browser then requests the page with a trailing slash, to save you frustration. (In this case it turns /test into /test/ ) When it does that, it also substitutes the name of the server it received from the first contact in place of the IP address. If this name resolves differently from the original IP address, you might be told that it couldn't find the server!

If you enter the line with the trailing slash, it will find the page right away, because it does not do another lookup. Therefore, if you have problems finding a page, try entering the directory name with a trailing slash. It can lead you to the solution of a problem.

This happened because I had temporarily changed the IP address on my machine, and the Web server name was no longer resolvable back to my machine's IP address. The server name entry in the /etc/httpd/conf/httpd.conf file could have been changed to resolve to the new IP address. However, adding a / at the end of the line is the lazy way of solving a temporary problem.

only for RuBoard - do not distribute or recompile


MySQL and PHP From Scratch
MySQL & PHP From Scratch
ISBN: 0789724405
EAN: 2147483647
Year: 1999
Pages: 93
Authors: Wade Maxfield

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net