Você está na página 1de 9

PHP Tutorial PHP Basics In this lesson, we will introduce you to PHP and show you how it works.

You will also be able to write your first PHP script after learning the basic syntax of PHP. Lesson Goals

Learn what PHP is. Learn how PHP works. Write a simple PHP page. Understand and work with simple PHP variables. Use PHP operators. Pass values from one page to another via the URL. How PHP Works

When a user navigates in her browser to a page that ends with a .php extension, the request is sent to a web server, which directs the request to the PHP interpreter.

As shown in the diagram above, the PHP interpreter processes the page, communicating with file systems, databases, and email servers as necessary, and then delivers a web page to the web server to return to the browser. The php.ini File Before we look at PHP syntax, we should briefly mention the php.ini file. This is a plain text file that is used to configure PHP. When the PHP interpreter is started, it reads thephp.ini file to determine what settings to use. We will mention this file from time to time throughout the course, but for now, it is enough that you are aware of its existence.

Basic PHP Syntax PHP Tags PHP code must be contained in special tags so that the PHP interpreter can identify it. Depending on the PHP configuration, these tags can take several forms: <?php This is the most commonly used (and recommended) form. PHP CODE GOES IN It is known as the XML style, because it can be used inside HERE of an XML document without causing the document to ?> become poorly formed. <script language="php"> PHP CODE GOES IN HTML or Script style tags. HERE </script> <? PHP CODE GOES "Short" tags. Must be enabled via the short_open_tag HERE php.ini configuration file directive. ?> <% PHP CODE GOES ASP-style tags. Must be enabled via the asp_tags php.ini HERE configuration file directive. %> In this manual, we will use the first form shown as it is the most common and the most portable. PHP Statements and Whitespace PHP statements must be inside of PHP tags to be processed by the PHP interpreter. Each PHP statement must end with a semi-colon, which tells the PHP interpreter that the statement is complete. If a semi-colon does not appear at the end of a line, the interpreter will assume that the statement continues onto the next line. The PHP interpreter condenses all sequential whitespace in PHP scripts to a single whitespace. This convenient feature allows PHP developers to structure their code in a readable format without being concerned about the effects of line breaks and tabs. Comments PHP has two forms of comments:

Single-line comments begin with a double slash (//). Multi-line comments begin with "/*" and end with "*/".

Syntax 1 // This is a single-line comment 2 3 /* This is 4 a multi-line 5 comment. 6 */ 7 PHP Functions There are literally hundreds of built-in PHP functions that do everything from returning the current date and time on the server to pulling data out of a database. A function might take zero arguments (e.g, phpinfo(), which returns information on the PHP environment) or it might take several arguments (e.g, mail(), which takes three required and two optional arguments). The syntax for calling a function is straightforward:

Syntax function_name(arguments); 1 The example below shows how the phpinfo() function works. Code Sample: PhpBasics/Demos/PhpInfo.php 1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>PHPINFO</title> </head> 6 <body> 7 <?php 8 //Output information on the PHP environment 9 phpinfo(); 10 ?> 11 </body> 12 </html> 13 Introduction to php.net PHP functions are well documented at http://www.php.net. You can quickly look up documentation on a function by going to http://www.php.net/function_name. For example, to see documentation on phpinfo(), go to http://www.php.net/phpinfo. Another very good function reference is located at http://www.phpdig.net/ref. Hello World! It is an unwritten rule that every programming course must contain a "Hello World!" script. Here it is: Code Sample: PhpBasics/Demos/HelloWorld.php 1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Hello World!</title> </head> 6 <body> 7 <?php 8 //Write out Hello World! 9 echo 'Hello World!'; 10 ?> 11 </body> 12 </html> 13 Notice the following about the above code:

Code between <?php and ?> is processed by the PHP interpreter. The echo command is used to print text back to the browser.

This code isn't very exciting. In fact, PHP doesn't buy us anything here as we could have just as easily output the result using straight HTML. There is nothing dynamic about this script. After learning about variables, we'll take a look at some more interesting examples. Variables

PHP variables begin with a dollar sign ($) as shown below. Syntax $varName = "Value"; Variable Types Variable TypeExplanation Integer whole number Double real number String string of characters Boolean true or false Array list of items Object instance of a class Variable Names (Identifiers) Variable, function and class names are all identifiers and all follow the rules above, with the exception that function names are not case sensitive.

consist of letters, digits, underscores and dollar signs cannot begin with a digit are case sensitive

Type Strength PHP is weakly typed, meaning that variables do not need to be assigned a type (e.g, Integer) at the time they are declared. Rather, the type of a PHP variable is determined by the value the variable holds and the way in which it is used. Hello Variables! Here is the "Hello World!" script again, but this time we use a variable. Code Sample: PhpBasics/Demos/HelloVariables.php 1 <?php 2 $greeting = 'Hello World!'; 3 ?> 4 <!DOCTYPE HTML> 5 <html> 6 <head> <meta charset="UTF-8"> 7 <title><?php echo $greeting; ?></title> 8 </head> 9 <body> 10 <?php 11 echo $greeting; 12 ?> 13 </body> 14 </html> 15 This time the string "Hello World!" is stored in the $greeting variable, which is output in the title and body of the page with an echo command. Variable Scope A variable's scope determines the locations from which the variable can be accessed. PHP variables are either superglobal, global, or local. Variable Scope superglobal Explanation Superglobal variables are predefined arrays, including $_POST and $_GET. They are accessible from anywhere on the page.

Variable Scope

Explanation

Global variables are visible throughout the script in which they are declared. global However, they are not visible within functions in the script unless they are redeclared within the function as global variables. Variables in the function scope are called local variables. Local variables are function local to the function in which they are declared. Superglobals Again, superglobal variables are predefined arrays, including $_POST and $_GET and are accessible from anywhere on the page. The complete list of superglobals is shown below.

$_GET - variables passed into a page on the query string. $_POST - variables passed into a page through a form using the post method. $_SERVER - server environment variables (e.g, $_SERVER['HTTP_REFERER'] returns the URL of the referring page). $_COOKIE - cookie variables. $_FILES - variables containing information about uploaded files. $_ENV - PHP environment variables (e.g, $_ENV['HTTP_HOST'] returns the name of the host server. Which environment variables are available depends on the specific server setup and configuration.

$_REQUEST - variables passed into a page through forms, the query string and cookies. $_SESSION - session variables.

The elements within superglobal variables can be accessed in three different ways, which the authors of PHP and MySQL Web Development refer to as short style,medium style, and long style. PHP & MySQL Web Develpoment, Third Edition. Style Syntax (using $_GET) Notes

Short

$varname

Convenient, but it makes it difficult to distinguish superglobal variables from other variables in the code. Requires register_globals config setting to be on. Recommended approach. Happy medium between convenience and clarity. Not available before v. 4.1. Inconvenient to type. Deprecated, but still supported in current versions. Can be disabled via theregister_long_arrays directive in thephp.ini file.

Medium$_GET['varname']

Long

$HTTP_GET_VARS['varname']

Many of these superglobals will be covered later in the course. Constants

Constants are like variables except that, once assigned a value, they cannot be changed. Constants are created using the define() function and by convention (but not by rule) are in all uppercase letters. Constants can be accessed from anywhere on the page. Syntax define('CONST_NAME',VALUE); Variable-Testing and Manipulation Functions For a complete list of variable functions seehttp://www.php.net/manual/en/ref.var.php. PHP provides built-in functions for checking if a variable exists, checking if a variable holds a value, and removing a variable. To output the results of these functions to a browser, use the var_dump() function (e.g. var_dump(isset($a));). FunctionExplanation Example isset()Checks to see if a variable exists. Returns true or false. isset($a) unset()Removes a variable from memory. unset($a) empty()Checks to see if a variable contains a non-empty, non-false value.empty($a)

PHP Operators Operators in PHP are similar to those found in many modern C-like programming languages. Mathematical Operators OperatorName Example Addition + $a + $b Subtraction $a - $b Multiplication $a * $b * Division / $a / $b Modulus % $a % $b String Operators OperatorName Example $a . $b Concatenation . 'Hello' . ' world!' Assignment Operators Operator Name Example $a = 1; Assignment = $c = 'Hello' . ' world!'; += $a += 1; -= $a -= 1; *= $a *= 2; Combination Assignment /= $a /= 2; %= $a %= 2; .= $a .= ' world!'; $a++; Increment By One ++ ++$a; $a--; Decrement By One ---$a; Other Operators

Operator Name ?: Ternary Error Suppression @

Example $foo = ($age >= 18) ? 'adult' : 'child'; $a = @(1/0);

Creating Dynamic Pages Single Quotes vs. Double Quotes In PHP, for simple strings you can use single quotes and double quotes interchangeably. However, there is one important difference of which you need to be aware. Text within single quotes will not be parsed for variables and escape sequences Escape sequences are used for characters that cannot easily be output within strings. Common escape sequences are \n for a newline, \t for a tab, \\ for a backslash, \" for a double quote, and \$ for a dollar sign. Compare the examples below. Code Sample: PhpBasics/Demos/SingleQuotes.php 1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Single Quotes</title> </head> 6 <body> 7 <?php 8 $person = 'George'; 9 echo '\tHello\n$person!!'; 10 ?> 11 </body> 12 </html> 13 Because of the use of single quotes above, the string "\tHello\n$person!!" will be output literally, as shown below.

Code Sample:

PhpBasics/Demos/DoubleQuotes.php 1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Single Quotes</title> </head> 6 <body> 7 <?php 8 $person = "George"; 9 echo "\tHello\n$person!!"; 10 ?> 11 </body> 12 </html> 13 This time, because of the double quotes, the string will be parsed for variables and special characters and will be output as shown below.

To see the effect of the special characters (\n and \t), you will have to view the source of the resulting page. Passing Variables on the URL A common way to pass values from the browser to the server is by appending them to the URL as follows: Syntax http://www.webucator.com/hello.php?greet=Hello&who=World 1 The part of the URL that follows the question mark is called the query string. One or more name-value pairs can be passed to the server in this way. Each name-value pair is separated by an ampersand (&). The processing page can read these name-value pairs and use them to determine its response. The HTML page below shows an example of how these name-value pairs might be passed. Code Sample: PhpBasics/Demos/HelloHi.html 1 <!DOCTYPE HTML> <html> 2 <head> 3 <meta charset="UTF-8"> 4

<title>Preferred Greeting</title> 5 </head> 6 <body> 7 Do you prefer a formal greeting or an informal greeting? 8 <ul> 9 <li><a href="HelloHi.php?greet=Hello">Formal</a></li> 10 <li><a href="HelloHi.php?greet=Hi">Informal</a></li> 11 <li><a href="HelloHi.php?greet=Howdy">Friendly</a></li> 12 </ul> 13 </body> 14 </html> 15 Code Sample: PhpBasics/Demos/HelloHi.php 1 <?php 2 //Assign the passed variable to a variable with 3 //a more convenient name. 4 $greeting = $_GET['greet']; 5 ?> 6 <!DOCTYPE HTML> 7 <html> <head> 8 <meta charset="UTF-8"> 9 <title><?= $greeting ?> World!</title> 10 </head> 11 <body> 12 <?php 13 echo "$greeting World!"; 14 ?> 15 </body> 16 </html> 17 Notice the following about the code above.

Variable names begin with a dollar sign ($). Values passed in the query string are part of the $_GET array and can be accessed using the following syntax: $_GET['fieldname']. A shortcut for echo 'text to print'; is <?= 'text to print' ?>. Many PHP developers feel that it is best practice to avoid using this shortcut syntax for echo. One reason for this is that the shortcut syntax makes the resulting PHP file impossible to parse as XML. Another is that the short_open_tag directive must be turned on for it to work. Seehttp://us3.php.net/manual/en/ini.core.php#ini.short-open-tag

Please watch this video on our YouTube channel to get a better understanding of variable scope and superglobal variables.

Você também pode gostar