0% found this document useful (0 votes)
95 views25 pages

PHP Basic

This is useful content for PHP Basics

Uploaded by

sankulsybca
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
95 views25 pages

PHP Basic

This is useful content for PHP Basics

Uploaded by

sankulsybca
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

PHP Basics

Requesting Data from a Web Page It can be tricky to understand how all of these pieces integrate. When a web server detects PHP code, it turns over the processing of the page to the PHP interpreter. The server processes the PHP file and sends the resulting HTML file to the browser. If that result includes an external CSS stylesheet, the browser issues a separate request for that stylesheet before displaying the page. Processing PHP on the server is called server-side processing. When you request a web page, you trigger a whole chain of events. Figure illustrates this interaction between your computer and the web server, which is the host of the web site.

The HTML file called directory.html is called a static web page because everyone who requests the directory.html page gets exactly the same page. For the web server to customize the returned page, PHP and MySQL are added to the mix. Figure (b) illustrates the extra steps that occur in the chain of events on the web host. Each step in the chain is listed here: Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

Figure( b) The PHP interpreter, MySQL, and the web server cooperate to return the page

This may seem like a lot of steps, but all of this processing happens automatically every time a web page with PHP code is requested. In fact, this process may happen several times for a single web page, since a web page can contain many image files and the CSS definition, which must all be retrieved from the web server.

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Super global variables. PHP uses special variables called super globals to provide information about the PHP scripts environment. These variables dont need to be declared as global. They are automatically available, and they provide important information beyond the scripts code itself, such as values from a users input. Since PHP 4.01, the super globals are defined in arrays. Arrays are special collections of values that well discuss in Chapter 6. The older super global variables such as those starting with $HTTP_* that were not in arrays still exist, but their use is not recommended, as they are deprecated. Table shows the existing arrays since PHP 4.01.

Constants You can define constants in your program. A constant, like its name implies, cannot change its value during the execution of your program. Its defined using the define( ) function, which takes the name of the constant as the first parameter and the values as the second parameter. The definition of a constant is global and can be defined as any simple (scalar) data type, such as a string or number. You can get the value of a constant by simply specifying its name, as shown in Example, or by using the constant function. Unlike how you handle variables, you should not put the dollar sign ($) before a constant. If the name of a constant is stored in a variable or the result of a function, youll need to use the function constant(name) to return the constants value. It takes a parameter as the name of the constant and returns its value. Or you could use get_defined_constants( ) to return a list (as an array) of all your defined constants. These are the differences between constants and variables: Its common practice to capitalize a variable name for constants. Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Constants do not have a dollar sign ($) at the start of their names. Constants can be defined only by using the define function, not by simple assignment. Constants are defined and accessed globally. Constants cannot be redefined or undefined once they have been set. Constants can evaluate only to scalar values. Example

Constants are useful for values that you need to make sure dont change, such as a configuration file location. If you use an undefined constant, PHP assumes that you mean the name of the constantitself, just as if you called it as a stringfor example, CONSTANT as opposed to "CONSTANT". If the define line of Example 3-20 is commented out, for example: // define ("HELLO", "Hello world!"); the output becomes: HELLO Youll also see a warning if PHP is configured to issue notices.

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

Control Structures
if, else, and else if
The if statement offers the ability to execute a block of code if the supplied condition is TRUE; otherwise, the code block doesnt execute. The condition can be any expression, including tests for nonzero, null, equality, variables, and returned values from functions. No matter what, every single conditional you create includes a conditional clause. If a condition is TRUE, the code block in curly braces ({}) is executed. If not, PHP ignores it and moves to the second condition, continuing through all clauses written until PHP hits an else. Then it automatically executes that block only if the IF condition proves to be FALSE; otherwise, it moves on. The curly braces are not required if you have only one line of code to execute in the block. An else statement is not always required.

Example

Example:- If-Else

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

All of this is great except for when you want to test for several conditions simultaneously. To do this, you can use the elseif statement. It allows for testing of additional conditions until one is found to be true or until you hit the else block. Each elseif has its own code block that comes directly after the elseif condition. The elseif must come after the if statement and before an else statement if one exists.

The switch Statement


If a multitude of conditions exist, you can use the switch control structure to create different responses for different conditionsmuch as you can for an if statement. However, switch works much better in situations where you have more than one or two conditions. A switch accepts an expression, then sets up cases. Each case is functionally equivalent to an if statement; this means that if the expression passed to the switch matches the case, then the code within the case is executed. You must separate each case with a break statement or else your code will continue to execute, producing unexpected results. To see switch in action, you can write a quick script that determines what day it is and outputs a different response based on the result. Example: <? php $action = ADD switch ($action) { case "ADD": echo "Perform actions for adding."; Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
break; case "MODIFY": echo "Perform actions for modifying."; break; case "DELETE": echo "Perform actions for deleting."; break; default: echo "Error: Action must be either ADD, MODIFY, or DELETE."; } ?> Looping The while loop allows you to repeat a block of code continuously for as long as a condition is TRUE. This allows you to cycle through data sets without needing to know how many exist; all that matters is the number of datasets you want to use at a maximum. The while loop takes the expression followed by the code to execute.

The syntax for a while loop is: while (expression) { code to execute; } Example

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

Output

Before the loop begins, the variable $num is set to 1. This is called initializing a counter variable. Each time the code block executes, it increases the value in $num by 1 with the statement $num++;. After 10 iterations, the evaluation $num <= 10 becomes FALSE, then the loop stops and it prints Done. Be sure to increase the $num var, as the while loop depends on it.

do while Loops
You need to use a do-while loop if you want to set up a loop that executes at least once, then continues if the condition is met. The do ... while loop takes an expression such as a while statement but places it at the end. The syntax is: do { code to execute; } while (expression); This loop is useful when you want to execute a block of code at least once regardless of the expression value. For example, lets count to 10 with this loop Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

if you change the value of $num to 11, the loop processes differently:

This produces: 11 The code in the loop displays 11 because the loop always executes at least once. Following the pass, while evaluates to FALSE, causing execution to drop out of the do ... while loop.

for Loops
One of the most versatile statements in PHP programming is the for loop, which accepts three expressions: expression one is evaluated once at the beginning of the loop, unconditionally; expression two is evaluated at the beginning of each iteration of the loop, and the loop continues only if the expression evaluates to true; expression three is evaluated at the end of each iteration. Each expression can have more than one part, with each part separated by a comma. Their syntax is: for (initialization expression; condition expression; modification expression) { code that is executed; }

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

When your PHP program process the for loop, the initialization portion is evaluated. For each iteration of the portion of code that increments, the counter executes and is followed by a check to see whether youre done. The result is a much more compact and easy-to-read statement.

Breaking Out of a Loop


PHP provides the equivalent of an emergency stop button for a loop: the break statement. Normally, the only way out of a loop is to satisfy the expression that determines when to stop the loop. If the code in the loop finds an error that makes continuing the loop pointless or impossible, you can break out of the loop by using the break statement.

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Possible problems you might encounter in a loop include running out of space when youre writing to a file or attempting to divide by zero. In Example we simulate what can happen if you divide based on an unknown entry initialized froma form submission (that could be a usersupplied value). If your user is malicious or just plain careless, she might enter a negative value where youre expecting a positive value (although this should be caught in your formvalidation process). In the code thats executed as part of the loop, the code checks to make sure the $counter is not equal to zero. If it is, the code calls break. Example

continue Statements
You can use the continue statement to stop processing the current block of code in a loop and jump to the next iteration of the loop. Its different from break in that it doesnt stop processing the loop entirely. Youre basically skipping ahead to the next iteration. Make sure you are modifying your test variable before the continue statement, or an infinite loop is possible. Example

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

The new output is as follows: 100/-3 -33.3333333333 100/-2 -50 100/-1 -100 Skipping to avoid division by zero. 100/1 100 100/2 50 100/3 33.3333333333 100/4 25 100/5 20 100/6 16.6666666667 100/7 14.2857142857 100/8 12.5 100/9 11.1111111111 Notice that the loop skipped over the $counter value of zero but continued with the next value.

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics

Including and Requiring PHP Files


A great feature provided by PHP is the ability to load a script from an external file; this makes it much easier to organize your code in larger projects. PHP provides four constructs you can use to load an external script: include, include_once, require, and require_once. The PHP manual recommends that developers use include_once and require_once because these constructs first check whether the file has already been loaded before either will load a given script. This saves resources and can increase the performance of your applications. include() The include() statement includes and evaluates the specified file. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
vars.php <?php $color = 'green'; $fruit = 'apple'; ?> test.php <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.
<?php function foo() { global $color; include 'vars.php'; } echo "A $color $fruit";

/* vars.php is in the scope of foo() so $fruit is NOT available outside of this scope. $color is because we declared it as global. */ foo(); echo "A $color $fruit"; ?> // A green apple // A green

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

include_once
Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
A problem may arise when you include many nested PHP scripts because the include statement doesnt check for scripts that have already been included. For example, if you did this: <?php include('add.php');include('add.php'); echo add(2, 2); ?> youd get this error: Fatal error: Cannot redeclare add( ) (previously declared in /home/www/htmlkb/oreilly/ch5/add.php:2) in /home/www/htmlkb/oreilly/ch5/add.php on line 2 This directory may not be where your file is located; your file will go wherever youve designated a place for it. To avoid this type of error, you should use the include_once statement.
Extra.php <?php $foo = "green"; $bar = "red"; ?> Test.php <?php include_once 'extras.php'; echo 'Variable $foo has a value of ', $foo, "<br />\n"; echo 'Variable $bar has a value of ', $bar, "<br />\n"; ?> Output:Variable $foo has a value of green Variable $bar has a value of red

By including the extras.php file you created using include_once, you are able to access the information stored in the file. This proves especially useful when youre working with a large set of functions, which allows common functions to be stored in a file that is included in other areas of your site, rather than requiring that you copy-and-paste those functions into each file. Adopting this approach reduces the size of your applications and can play a part in optimizing your applications performance.

This next short example illustrates how using include_once can reduce the load on your server.
Extra.php <?php $var += 1; ?>

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Test.php <?php $var = 0; include 'extras.php'; echo $var, "<br />"; include 'extras.php'; echo $var, "<br />"; ?> This code produces the following output when loaded into a browser: 1 2 Now, change test.php so it uses include_once instead of include: <?php $var = 0; include_once 'extras.php'; echo $var, "<br />"; include_once 'extras.php'; echo $var, "<br />"; ?> Next, load test.php in a browser to see the result: 1 1

The file is loaded only once, the script executes only once. This reduces the load on the server, which in turn reduces the execution time of your scripts.

require()
The require() function is identical to include(), except that it handles errors differently. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error). If you include a file with the include() function and an error occurs, you might get an error message like the one below.

Example
<html> <body> <?php include("wrongFile.php"); echo "Hello World!"; ?> </body>

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
</html>

Output
Error message:
Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 Hello World!

Notice that the echo statement is still executed! This is because a Warning does not stop the script execution. Now, let's run the same example with the require() function. PHP code:
<html> <body> <?php require("wrongFile.php"); echo "Hello World!"; ?> </body> </html>

Error message:
Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5

The echo statement was not executed because the script execution stopped after the fatal error. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed. Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Note:- require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.

require_once()
The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
For example, if you attempt to require a file that doesnt exist, as follows: <?php require_once('add_wrong.php'); echo add(2, 2); ?> youd get this error: Warning: main(add_wrong.php): failed to open stream: No such file or directory in/home/www/htmlkb/oreilly/ch5/require_once.php on line 2 Fatal error: main( ): Failed opening required 'add_wrong.php'(include_path='.:/usr/share/php:/usr/share/pear') in/home/www/htmlkb/oreilly/ch5/ require_once.php on line 2

require_once used a relative file location and doesnt include the full path to a file. This means that the paths are relative to where your PHP script is located.

GET Method The $_GET variable is an array of variable names and values sent by the HTTP GET method. The $_GET variable is used to collect values from a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and it has limits on the amount of information to send (max. 100 characters).

Example
<form action="welcome.php" method="get"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" />

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
<input type="submit" /> </form>

When the user clicks the "Submit" button, the GET data ispassed through a query string in the URL, which looks something like this:
http://example.com?var1=somevalue&var2=othervalue Example:http://www.w3schools.com/welcome.php?name=Peter&age=37

The query string begins with a question mark (?) and then names a variable (var1 in the preceding example). The next part of the query string is an equals sign (=), followed by a value. You can add more variables by appending an ampersand (&) to the end of the first value, then declaring another variable name (var2 in the preceding example), followed by an equals sign and a value. Note that you do not enclose the values in the query string in quotes; this can cause problems when you use values that have spaces and/or special characters.

The "welcome.php" file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array):
Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!

Why use $_GET?


Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.

Arrays
Variables are great for storing a single piece of information, but what happens when you need to store data for a whole set of information, such as the results of a query? When this happens, use arrays. Arrays are a special kind of variable that stores many pieces of data. Arrays allow you to access any of the values stored in them individually yet still copy and manipulate the array as a whole.

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
To work with arrays, you need to learn two new terms: elements and indexes. Elements are the values that are stored in the array. Each element in the array is referenced by an index that differentiates the element from any other unique element in the array. The index value can be a number or a string, but it must be unique. You can think of an array like a spreadsheet or a database that has only two columns. The first column uniquely identifies the row in the spreadsheet, while the second column contains a stored value.

Associative Versus Numeric Indexed Arrays


Numeric arrays use numbers as their indexes, while associative arrays use stings.When using associative arrays, you must supply an index string each time you add an element. Numeric arrays allow you to just add the element, and PHP automatically assigns the first free number, starting at 0. Both types of arrays allow you to add new elements to the array one at a time. Associative arrays are nice for storing configuration data since their keys can have a meaningful name.

Creating an Array
Numerically Indexed Arrays
Lets assume that youve been tasked with creating a simple website for a local office supplies company and youre currently working on the section devoted to paper. One way to manage the various items of stock in this category would be to place them in a numeric array. PHP provides two ways of assigning values to arrays. Well discuss array identifiers for assignment first. Array identifiers look like normal variable assignments except a pair of square brackets ([]) are added after the name of the array variable. You can optionally add an index value between the brackets. If you dont supply an index, PHP automatically picks the lowest empty numeric index value for the array. For example, to assign the first two days of the week to a numeric indexed array, you would use the following:
<?php ?> $weekdays[] = 'Monday'; $weekdays[] = 'Tuesday';

You could also specify the index values, which would have the same end result as the following: Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
<?php $weekdays[0] = 'Monday'; $weekdays[1] = 'Tuesday'; ?>

If you do specify the index yourself, be careful not to skip over numbers:
<?php $weekdays[0] = 'Monday'; $weekdays[1] = 'Tuesday'; $weekdays[3] = 'Wednesday'; ?>

This code creates an array that doesnt have a value assigned for the key of 2. That might be OK, but if youre going through the array values sequentially and your code unexpectedly encounters a missing value, that could cause problems, but PHP itself wont report an error. The other way to assign values to an array is to use the array language construct, a special function. The array function allows you to create your array and assign multiple elements all at once. The array takes pairs of index keys and values as parameters. It returns an array that is usually assigned to a variable. The elements to be assigned are separated by commas.
<?php $weekdays = array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ); ?>

we can create an associative array using the format index => value
<?php $weekdays = array( [0]=>'Monday', [1]=>'Tuesday', [2]=>'Wednesday', [3]=>'Thursday', [4]=>'Friday', [5]=>'Saturday', [6]=>'Sunday' ); ?>

Associative Arrays
Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Keeping track of array elements by index works just fine, but can require extra work in terms of remembering which number refers to which product. It can also make code hard for other programmers to follow. This is where associative arrays come into their own. Using them, you can reference the items in an array by name rather than by number.
<?php $paper['copier'] = "Copier & Multipurpose"; $paper['inkjet'] = "Inkjet Printer"; $paper['laser'] = "Laser Printer"; $paper['photo'] = "Photographic Paper"; echo $paper['laser'];

?>

In place of a number (which doesnt convey any useful information, aside from the position of the item in the array), each item now has a unique name that you can use to reference it elsewhere, as with the echo statementwhich simply prints out Laser Printer. The names (copier, inkjet, and so on) are called indexes or keys and the items assigned to them (such as Laser Printer) are called values. So far, youve seen how to assign values to arrays by just adding new items one at a time. Whether you specify keys, specify numeric identifiers, or let PHP assign numeric identifiers implicitly, this is a long-winded approach. A more compact and faster assignment method uses the array keyword.
<?php $p1 = array("Copier", "Inkjet", "Laser", "Photo"); echo "p1 element: " . $p1[2] . "<br>"; $p2 = array ( 'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper" ); echo "p2 element: " . $p2['inkjet'] . "<br>"; ?>

The first half of this snippet assigns the old, shortened product descriptions to the array $p1. There are four items, so they will occupy slots 0 through 3. Therefore the echo statement prints out the following: p1 element: Laser The second half assigns associative identifiers and accompanying longer product descriptions to the array $p2 using the format index => value. The use of => is similar to the regular = assignment operator, except that you are assigning a value to an index and not to a variable. The index is then inextricably linked with that value, unless it is reassigned a new value. The echo command therefore prints out: Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
p2 element: Inkjet Printer You can verify that $p1 and $p2 are different types of array, because both of the following commands, when appended to the code, will cause an undefined index or undefined offset error, as the array identifier for each is incorrect: echo $p1['inkjet']; // Undefined index echo $p2['3']; // Undefined offset |

Multidimensional Arrays While weve shown only arrays that hold simple values like strings so far, remember that an array can also store another array as an element. Multidimensional arrays exploit the fact that an array can have another array as an element. Each set of keys and values represents a dimension. Multidimensional arrays have a key and value set for each dimension. Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
Expanding on your shapes array, weve created a new associative array called $objects with keys that are the names of the objects. Each element of the $objects array is another associative array containing the keys shape, color, and material with the associated values as the elements.

Example Creating a multidimensional array

<?php $objects=array(

'Soda can' => array( 'Shape' => 'Cylinder', 'Color' => 'Red', 'Material' => 'Metal'), 'Notepad' => array( 'Shape' => 'Rectangle', 'Color' => 'White', 'Material' => 'Paper'), 'Apple' => array('Shape' => 'Sphere', 'Color' => 'Red', 'Material' => 'Fruit'), 'Orange' => array( 'Shape' => 'Sphere', 'Color' => 'Orange', 'Material' => 'Fruit'), 'Phonebook' => array( 'Shape' => 'Rectangle', 'Color' => 'Yellow', 'Material' => 'Paper') );

echo $objects['Soda can']['Shape'];

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

PHP Basics
?> Output
Cylinder

Youre able to access the second dimension of the array by using a second set of brackets ([]) to specify the second key. If the array has more dimensions than just two, you must specify the key for each dimension. True to form, if you access $objects['Orange'], you would get an array.
Example Displaying a multidimensional array <?php foreach ($objects as $obj_key => $obj) { echo "$obj_key:<br>"; while (list ($key,$value)=each ($obj)) { echo "$key = $value "; } echo "<br />"; } ?> Now you can loop the inner index like this in phpmultiloop.php <html> <body> <?php $A [0][]=78; $A [0][]=90 $A [1][]=90; $A [1][]=89; for($i=0 ; $i< count($A) ; $i++) { for($j=0 ; $j< count($A[$i]) ; $j++) { echo $A [$i][$j] <br>; } } ?> </body> </html>

Mr. Deependra Rastogi Lecturer, TMU, Moradabad

You might also like