The foreach Loop
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
There are two syntaxes:
foreach (array as $value) { code to be executed; }
//or
foreach (array as $key => $value) { code to be executed; }
The first form loops over the array. On each iteration, the value of the current element is assigned to $value, and the array pointer is moved by one, until it reaches the last array element. The second form will additionally assign the current element's key to the $key variable on each iteration.
The following example demonstrates a loop that outputs the values of the $names array. $names = array("John", "David", "Amy"); foreach ($names as $name) { echo $name.'<br />'; }
// John // David // Amy -------------------------------------------------------------------------------------------------------------------------------------- The switch Statement
The switch statement is an alternative to the if-elseif-else statement. Use the switch statement to select one of a number of blocks of code to be executed.
Syntax: switch (n) { case value1: //code to be executed if n=value1 break; case value2: //code to be executed if n=value2 break; ... default: // code to be executed if n is different from all labels }
First, our single expression, n (most often a variable), is evaluated once. Next, the value of the expression is compared with the value of each case in the structure. If there is a match, the block of code associated with that case is executed. Using nested if else statements results in similar behavior, but switch offers a more elegant and optimal solution. -------------------------------------------------------------------------------------------------------------------------------------- Switch
Consider the following example, which displays the appropriate message for each day. $today = 'Tue';
switch ($today) { case "Mon": echo "Today is Monday."; break; case "Tue": echo "Today is Tuesday."; break; case "Wed": echo "Today is Wednesday."; break; case "Thu": echo "Today is Thursday."; break; case "Fri": echo "Today is Friday."; break; case "Sat": echo "Today is Saturday."; break; case "Sun": echo "Today is Sunday."; break; default: echo "Invalid day."; } //Outputs "Today is Tuesday."
The break keyword that follows each case is used to keep the code from automatically running into the next case. If you forget the break; statement, PHP will automatically continue through the next case statements, even when the case doesn't match. ------------------------------------------------------------------------------------------------------------------- default
The default statement is used if no match is found. $x=5; switch ($x) { case 1: echo "One"; break; case 2: echo "Two"; break; default: echo "No match"; }
//Outputs "No match"
The default statement is optional, so it can be omitted. --------------------------------------------------------------------------------------------------------------------- Switch
Failing to specify the break statement causes PHP to continue to executing the statements that follow the case, until it finds a break. You can use this behavior if you need to arrive at the same output for more than one case. $day = 'Wed';
switch ($day) { case 'Mon': echo 'First day of the week'; break; case 'Tue': case 'Wed': case 'Thu': echo 'Working day'; break; case 'Fri': echo 'Friday!'; break; default: echo 'Weekend!'; }
//Outputs "Working day"
The example above will have the same output if $day equals 'Tue', 'Wed', or 'Thu'. ---------------------------------------------------------------------------------------------------------------------- The break Statement
As discussed in the previous lesson, the break statement is used to break out of the switch when a case is matched. If the break is absent, the code keeps running. For example: $x=1; switch ($x) { case 1: echo "One"; case 2: echo "Two"; case 3: echo "Three"; default: echo "No match"; }
//Outputs "OneTwoThreeNo match"
Break can also be used to halt the execution of for, foreach, while, do-while structures. The break statement ends the current for, foreach, while, do-while or switch and continues to run the program on the line coming up after the loop. A break statement in the outer part of a program (e.g., not in a control loop) will stop the script. ----------------------------------------------------------------------------------------------------------------------- The continue Statement
When used within a looping structure, the continue statement allows for skipping over what remains of the current loop iteration. It then continues the execution at the condition evaluation and moves on to the beginning of the next iteration.
The following example skips the even numbers in the for loop: for ($i=0; $i<10; $i++) { if ($i%2==0) { continue; } echo $i . ' '; }
//Output: 1 3 5 7 9
You can use the continue statement with all looping structures. -------------------------------------------------------------------------------------------------------------------------- include
The include and require statements allow for the insertion of the content of one PHP file into another PHP file, before the server executes it. Including files saves quite a bit of work. You can create a standard header, footer, or menu file for all of your web pages. Then, when the header is requiring updating, you can update the header include file only.
Assume that we have a standard header file called header.php. <?php echo '<h1>Welcome</h1>'; ?>
Use the include statement to include the header file in a page. <html> <body>
<?php include 'header.php'; ?>
<p>Some text.</p> <p>Some text.</p> </body> </html> --------------------------------------------------------------------------------------------------------------------------- include
Using this approach, we have the ability to include the same header.php file into multiple pages. <html> <body>
<?php include 'header.php'; ?>
<p>This is a paragraph</p> </body> </html>
Files are included based on the file path. You can use an absolute or a relative path to specify which file should be included. ----------------------------------------------------------------------------------------------------------------------------- include vs require
The require statement is identical to include, the exception being that, upon failure, it produces a fatal error. When a file is included using the include statement, but PHP is unable to find it, the script continues to execute. In the case of require, the script will cease execution and produce an error. Use require when the file is required for the application to run. Use include when the file is not required. The application should continue, even when the file is not found. ------------------------------------------------------------------------------------------------------------------------------ Using the for loop, print only the even numbers between 0 and 10. for ($i=0; $i<=10;$i++) { if ($i%2 != 0) { continue; } echo $i."<br/>"; } -------------------------------------------------------------------------------------------------------------------------------- Functions
A function is a block of statements that can be used repeatedly in a program. A function will not execute immediately when a page loads. It will be executed by a call to the function. A user defined function declaration starts with the word function: function functionName() { //code to be executed }
A function name can start with a letter or an underscore, but not with a number or a special symbol. Function names are NOT case-sensitive. -------------------------------------------------------------------------------------------------------------------------------- Functions
In the example below, we create the function sayHello(). The opening curly brace ({) indicates that this is the beginning of the function code, while the closing curly brace (}) indicates that this is the end. To call the function, just write its name: function sayHello() { echo "Hello!"; }
sayHello(); //call the function
//Outputs "Hello!" ----------------------------------------------------------------------------------------------------------------------------- Function Parameters
Information can be passed to functions through arguments, which are like variables. Arguments are specified after the function name, and within the parentheses. Here, our function takes a number, multiplies it by two, and prints the result: function multiplyByTwo($number) { $answer = $number * 2; echo $answer; } multiplyByTwo(3); //Outputs 6
You can add as many arguments as you want, as long as they are separated with commas. function multiply($num1, $num2) { echo $num1 * $num2; } multiply(3, 6); //Outputs 18
When you define a function, the variables that represent the values that will be passed to it for processing are called parameters. However, when you use a function, the value you pass to it is called an argument. ------------------------------------------------------------------------------------------------------------------------------ Default Arguments
Default arguments can be defined for the function arguments. In the example below, we're calling the function setCounter(). There are no arguments, so it will take on the default values that have been defined. function setCounter($num=10) { echo "Counter is ".$num; } setCounter(42); //Counter is 42 setCounter(); //Counter is 10
When using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. ------------------------------------------------------------------------------------------------------------------------------- Return
A function can return a value using the return statement. Return stops the function's execution, and sends the value back to the calling code. For example: function mult($num1, $num2) { $res = $num1 * $num2; return $res; }
echo mult(8, 3); // Outputs 24
Leaving out the return results in a NULL value being returned. A function cannot return multiple values, but returning an array will produce similar results. -------------------------------------------------------------------------------------------------------------------------------- Predefined Variables
A superglobal is a predefined variable that is always accessible, regardless of scope. You can access the PHP superglobals through any function, class, or file.
PHP's superglobal variables are $_SERVER, $GLOBALS, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, $_SESSION.
$_SERVER
$_SERVER is an array that includes information such as headers, paths, and script locations. The entries in this array are created by the web server. $_SERVER['SCRIPT_NAME'] returns the path of the current script: <?php echo $_SERVER['SCRIPT_NAME']; //Outputs "/somefile.php" ?>
Our example was written in a file called somefile.php, which is located in the root of the web server. -------------------------------------------------------------------------------------------------------------------------------- $_SERVER
$_SERVER['HTTP_HOST'] returns the Host header from the current request. <?php echo $_SERVER['HTTP_HOST']; //Outputs "localhost" ?>
This method can be useful when you have a lot of images on your server and need to transfer the website to another host. Instead of changing the path for each image, you can do the following: Create a config.php file, that holds the path to your images: <?php $host = $_SERVER['HTTP_HOST']; $image_path = $host.'/images/'; ?>
Use the config.php file in your scripts: <?php require 'config.php'; echo '<img src="'.$image_path.'header.png" />'; ?>
The path to your images is now dynamic. It will change automatically, based on the Host header. -------------------------------------------------------------------------------------------------------------------------------- Forms
The purpose of the PHP superglobals $_GET and $_POST is to collect data that has been entered into a form. The example below shows a simple HTML form that includes two input fields and a submit button: <form action="first.php" method="post"> <p>Name: <input type="text" name="name" /></p> <p>Age: <input type="text" name="age" /></p> <p><input type="submit" name="submit" value="Submit" /></p> </form> --------------------------------------------------------------------------------------------------------------------------------- Forms
The action attribute specifies that when the form is submitted, the data is sent to a PHP file named first.php. HTML form elements have names, which will be used when accessing the data with PHP. The method attribute will be discussed in the next lesson. For now, we'll set the value to "post". ---------------------------------------------------------------------------------------------------------------------------------- Forms
Now, when we have an HTML form with the action attribute set to our PHP file, we can access the posted form data using the $_POST associative array.
In the first.php file: <html> <body>
Welcome <?php echo $_POST["name"]; ?><br /> Your age: <?php echo $_POST["age"]; ?>
</body> </html>
The $_POST superglobal array holds key/value pairs. In the pairs, keys are the names of the form controls and values are the input data entered by the user. We used the $_POST array, as the method="post" was specified in the form. To learn more about the form methods, press Continue! ----------------------------------------------------------------------------------------------------------------------------------- POST
The two methods for submitting forms are GET and POST. Information sent from a form via the POST method is invisible to others, since all names and/or values are embedded within the body of the HTTP request. Also, there are no limits on the amount of information to be sent. Moreover, POST supports advanced functionality such as support for multi-part binary input while uploading files to the server. However, it is not possible to bookmark the page, as the submitted values are not visible. POST is the preferred method for sending form data. ------------------------------------------------------------------------------------------------------------------------------------ GET
Information sent via a form using the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also sets limits on the amount of information that can be sent - about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page, which can be useful in some situations.
For example: <form action="actionGet.php" method="get"> Name: <input type="text" name="name" /><br /><br /> Age: <input type="text" name="age" /><br /><br /> <input type="submit" name="submit" value="Submit" /> </form>
actionGet.php <?php echo "Hi ".$_GET['name'].". "; echo "You are ".$_GET['age']." years old."; ?>
GET should NEVER be used for sending passwords or other sensitive information! When using POST or GET, proper validation of form data through filtering and processing is vitally important to protect your form from hackers and exploits! ------------------------------------------------------------------------------------------------------------------------------------ Sessions
Using a session, you can store information in variables, to be used across multiple pages. Information is not stored on the user's computer, as it is with cookies. By default, session variables last until the user closes the browser.
Start a PHP Session
A session is started using the session_start() function. Use the PHP global $_SESSION to set session variables. <?php // Start the session session_start();
$_SESSION['color'] = "red"; $_SESSION['name'] = "John"; ?>
Now, the color and name session variables are accessible on multiple pages, throughout the entire session. The session_start() function must be the very first thing in your document. Before any HTML tags. ------------------------------------------------------------------------------------------------------------------------------------ Session Variables
Another page can be created that can access the session variables we set in the previous page: <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php echo "Your name is " . $_SESSION['name']; // Outputs "Your name is John" ?> </body> </html>
Your session variables remain available in the $_SESSION superglobal until you close your session. All global session variables can be removed manually by using session_unset(). You can also destroy the session with session_destroy(). ------------------------------------------------------------------------------------------------------------------------------------- Cookies
Cookies are often used to identify the user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page through a browser, it will send the cookie, too. With PHP, you can both create and retrieve cookie values.
Create cookies using the setcookie() function: setcookie(name, value, expire, path, domain, secure, httponly);
name: Specifies the cookie's name value: Specifies the cookie's value expire: Specifies (in seconds) when the cookie is to expire. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0. path: Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory in which the cookie is being set. domain: Specifies the cookie's domain name. To make the cookie available on all subdomains of example.com, set the domain to "example.com". secure: Specifies whether or not the cookie should only be transmitted over a secure, HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE. httponly: If set to TRUE, the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible to scripting languages). Using httponly helps reduce identity theft using XSS attacks. Default is FALSE. The name parameter is the only one that's required. All of the other parameters are optional. ------------------------------------------------------------------------------------------------------------------------------------- Cookies
The following example creates a cookie named "user" with the value "John". The cookie will expire after 30 days, which is written s 86,400 * 30, in which 86,400 seconds = one day. The '/' means that the cookie is available throughout the entire website.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:
<?php $value = "John"; setcookie("user", $value, time() + (86400 * 30), '/');
if(isset($_COOKIE['user'])) { echo "Value is: ". $_COOKIE['user']; } //Outputs "Value is: John" ?>
The setcookie() function must appear BEFORE the <html> tag. The value of the cookie is automatically encoded when the cookie is sent, and is automatically decoded when it's received. Nevertheless, NEVER store sensitive information in cookies. ------------------------------------------------------------------------------------------------------------------------------------- Manipulating Files
PHP offers a number of functions to use when creating, reading, uploading, and editing files. The fopen() function creates or opens a file. If you use fopen() with a file that does not exist, the file will be created, given that the file has been opened for writing (w) or appending (a).
Use one of the following modes to open the file. r: Opens file for read only. w: Opens file for write only. Erases the contents of the file or creates a new file if it doesn't exist. a: Opens file for write only. x: Creates new file for write only. r+: Opens file for read/write. w+: Opens file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. a+: Opens file for read/write. Creates a new file if the file doesn't exist x+: Creates new file for read/write.
The example below creates a new file, "file.txt", which will be created in the same directory that houses the PHP code. $myfile = fopen("file.txt", "w"); -------------------------------------------------------------------------------------------------------------------------- Write to File
When writing to a file, use the fwrite() function. The first parameter of fwrite() is the file to write to; the second parameter is the string to be written.
The example below writes a couple of names into a new file called "names.txt". <?php $myfile = fopen("names.txt", "w");
$txt = "John\n"; fwrite($myfile, $txt); $txt = "David\n"; fwrite($myfile, $txt);
fclose($myfile);
/* File contains: John David */ ?>
Notice that we wrote to the file "names.txt" twice, and then we used the fclose() function to close the file. The \n symbol is used when writing new lines. ------------------------------------------------------------------------------------------------------------------------- fclose()
The fclose() function closes an open file and returns TRUE on success or FALSE on failure. It's a good practice to close all files after you have finished working with them. ------------------------------------------------------------------------------------------------------------------------- Appending to a File
If you want to append content to a file, you need to open the file in append mode.
For example: $myFile = "test.txt"; $fh = fopen($myFile, 'a'); fwrite($fh, "Some text"); fclose($fh);
When appending to a file using the 'a' mode, the file pointer is placed at the end of the file, ensuring that all new data is added at the end of the file. ------------------------------------------------------------------------------------------------------------------------- Appending to a File
Let's create an example of a form that adds filled-in data to a file. <?php if(isset($_POST['text'])) { $name = $_POST['text']; $handle = fopen('names.txt', 'a'); fwrite($handle, $name."\n"); fclose($handle); } ?> <form method="post"> Name: <input type="text" name="text" /> <input type="submit" name="submit" /> </form>
Now, each time a name is entered and submitted, it's added to the "names.txt" file, along with a new line.
The isset() function determined whether the form had been submitted, as well as whether the text contained a value. We did not specify an action attribute for the form, so it will submit to itself. ------------------------------------------------------------------------------------------------------------------------- Reading a File
The file() function reads the entire file into an array. Each element within the array corresponds to a line in the file:
$read = file('names.txt'); foreach ($read as $line) { echo $line .", "; }
This prints all of the lines in the file, and separates them with commas. We used the foreach loop, because the $read variable is an array. -------------------------------------------------------------------------------------------------------------------------- Reading a File
At the end of the output in the previous example, we would have a comma, as we print it after each element of the array. The following code lets us avoid printing that final comma. $read = file('names.txt'); $count = count($read); $i = 1; foreach ($read as $line) { echo $line; if($i < $count) { echo ', '; } $i++; }
The $count variable uses the count function to obtain the number of elements in the $read array. Then, in the foreach loop, after each line prints, we determine whether the current line is less than the total number of lines, and print a comma if it is. This avoids printing that final comma, as for the last line, $i is equal to $count. --------------------------------------------------------------------------------------------------------------------------
|