php basics examples taken from: beginning php 5 and mysql 5 from novice to professional

Post on 24-Dec-2015

220 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

PHP Basics

Examples taken from:Beginning PHP 5 and MySQL 5

From Novice to Professional

hello.php

<html><head><title>PHP Test</title></head><body><?php echo '<p>Hello PHP World</p>'; ?></body></html>

current-date.php

<?php echo date("F j, Y");?>

• Note script – not enclosed in HTML code– does not have execute permision on server– very compact– can be cryptic

Default SyntaxPHP code delimiters

• <h3>Welcome!</h3>• <?php• print "<p>This is a PHP example.</p>";• ?>• <p>Some static information found here...</p>

Short Syntax

<?print "This is another PHP example.";?><?="This is another PHP example.";?><? print "This is another PHP example."; ?>

• Note short tag delimiters– may conflict with XML. – Requires short_open_tag directive

Editor Syntax

<script language="php">print "This is another PHP example.";</script>

• Note – used by some HTML editors (ie. FrontPage) that have problems dealing with the PHP escape syntax.

ASP-Style

<%print "This is another PHP example.";%>

• Note - Microsoft ASP pages use a predefined character pattern to open/close dynamic syntax that is supported by PHP.

Multiple Code Blocks<html><head><title><?php echo "Welcome to my site!";?></title></head><body><?php$date = "May 18, 2003";?><h3>Today's date is <?=$date;?></h3></body></html>

• Note that variable values persist between blocks.

PHP CommentsShell Syntax

<?php# Title: My PHP program# Author: Jasonprint "This is a PHP program";?>

PHP CommentsC Syntax

<?php# Title: My PHP program# Author: Jasonprint "This is a PHP program";?>

PHP CommentsMulti-line C Syntax

<?php/*Title: My PHP ProgramAuthor: JasonDate: October 10, 2005*/?>

boolean print (argument)<?phpprint("<p>I love the summertime.</p>");?>

<?php$season = "summertime";print "<p>I love the $season.</p>";?>

<?phpprint "<p>I love thesummertime.</p>";?>

<?php$season = "summertime";print "<p>I love the ".$season."</p>";?>

Print()

• On the examples just given did you note that:– The parentheses to enclose the argument are

optional.– The how concatenation was used in the last

example.

void echo (string argument1 [, ...string argumentN])

<?php$heavyweight = "Lennox Lewis";$lightweight = "Floyd Mayweather";echo $heavyweight, " and ", $lightweight, " are

great fighters.";?>

boolean printf (string format [, mixed args])

printf("$%01.2f", 43.2); // $43.20

printf("%d beer %s", 100, "bottles"); // 100 beer bottles

printf("%15s", "Some text"); // Some text

string sprintf (string format [, mixed arguments])

• Works like printf() but output is assigned to a string instead of directly to standard output

$cost = sprintf("$%01.2f", 43.2); // $cost = $43.20

Scalar Datatypes

• Boolean• Integer• Float• String

Boolean

$alive = false; # $alive is false.$alive = 1; # $alive is true.$alive = -1; # $alive is true.$alive = 5; # $alive is true.$alive = 0; # $alive is false.

• Note any non-zero value is TRUE.

Integer

42 # decimal-678900 # decimal0755 # octal0xC4E # hexadecimal• Note – if you exceed maxint PHP will

automatically convert the value to a float.

String

• Historically PHP treated strings as arrays of characters

$color = "maroon";echo $color[2]; // outputs 'r‘

• PHP 5 introduces specialized string offset functionality

Compound Datatypes

• Array• Object

Array

Traditional Index$state[0] = "Alabama";$state[1] = "Alaska";$state[2] = "Arizona";...$state[49] = "Wyoming";

Associative Index• $state["Alabama"] =

"Montgomery";• $state["Alaska"] = "Juneau";• $state["Arizona"] = "Phoenix";• ...• $state["Wyoming"] =

"Cheyenne";

Object

class appliance {private $power;function setPower($status) {$this->power = $status;}}...$blender = new appliance;• Note – an object must be explicitly declared in PHP.

Special Datatypes

• Resource• Null

Resource

• Typically used to create variables for using resources, handles.

$fh = fopen("/home/jason/books.txt", "r");

Null

• Means that a value has not been assigned. In PHP, a value is null if:

• It has not been set to any predefined value.• It has been specifically assigned the value Null.• It has been erased using the function unset().• The null datatype recognizes only one value, Null:<?php$default = Null;?>

Type Casting

• Forces a variable to behave as a type other that the one originally indended.

$variable1 = 13;$variable2 = (double) $variable1; // $variable2 is assigned the value 13.0

$variable1 = 4.7;$variable2 = 5;$variable3 = (int) $variable1 + $variable2; // $variable3 = 9

Weakly typed withon-the-fly “best guess” type conversion

<?php$number = "5"; # $number is a string$sum = 15 + $number; # Add an integer and # string to produce integer$sum = "twenty"; # Overwrite $sum with a string.?>

Conversion to Boolean

<?php$total = "1.0";if ($total) echo "The total count is positive";?>• Note – $total is converted to type Boolean for the if

statement– You may see this often in PHP code

Type Related Functions

• boolean settype (mixed var, string type)– Converts the variable var to the datatype type– Type can be array, boolean, float, inteter, null,

object, or string• string gettype (mixed var)– Returns the datatype of the variable var– The return value can be array, boolean, double,

integer, object, resource, string, or unknown.

Type Identifier Functions

• boolean is_array (mixed var)• boolean is_bool (mixed var)• boolean is_float (mixed var)• boolean is_integer (mixed var)• boolean is_null (mixed var)• boolean is_numeric (mixed var)• boolean is_object (mixed var)• boolean is_resource (mixed var)• boolean is_scalar (mixed var)• boolean is_string (mixed var)

Identifiers

• An identifier can consist of one or more characters and must begin with a letter or an underscore.

• Identifiers can consist of only letters, numbers, underscore characters, and other ASCII characters from 127 through 255.

• Identifiers are case sensitive• Identifiers can be any length• Identifier names can be the same as PHP

predefined keywords.

Variables

• A variable name always begins with a dollar sign, $, then followed by the variable name.

• Variable names follow the same naming rules as identifiers.

• Variables do not have to be explicitly declared

Variable Assignment by Value

$color = "red";$number = 12;$age = 12;$sum = 12 + "15"; /* $sum = 27 */

• Note $number and $age reference two different memory locations.

Variable Assignment by Reference<?php$value1 = "Hello";$value2 =& $value1; /* $value1 and $value2 both equal "Hello". */$value2 = "Goodbye"; /* $value1 and $value2 both equal "Goodbye". */?>

• Note– $value1 and $value2 refer to the same memory location– You assign variables by reference by appending an ampersand (&) to

the equal sign.

Another Variable Assignment by Reference

<?php$value1 = "Hello";$value2 = &$value1; /* $value1 and $value2 both equal "Hello". */$value2 = "Goodbye"; /* $value1 and $value2 both equal "Goodbye". */?>

• Note – place the ampersand in front of the variable being referneced.

Variable Scope

• Local variables• Function parameters• Global variables• Static variables

Local Variables

• A variable declared in a function is considered local. That is, it can be referenced only in that function.

• Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

• When you exit the function in which a local variable has been declared, that variable and its corresponding value are destroyed.

Local Variable Example

$x = 4;function assignx () {$x = 0;print "\ $x inside function is $x. <br>";}assignx();print "\ $x outside of function is $x. <br>";

Function Parameters

• Any function that accepts arguments must declare those arguments in the function header.

• Although those arguments accept values that come from outside of the function, they are no longer accessible once the function has exited.

Function Parameter Example

// multiply a value by 10 and return it to the caller

function x10 ($value) {$value = $value * 10;return $value;}

Global Variables

• A global variable can be accessed in any part of the program.

• A global variable it must be explicitly declared to be global in the function in which it is to be modified.

• This is accomplished by placing the keyword GLOBAL in front of the variable that should be recognized as global.

• Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.

Global Variable Example

$somevar = 15;function addit() {GLOBAL $somevar;$somevar++;print "Somevar is $somevar";}addit();

Global Variable Exampleusing PHP’s $GLOBALS array

$somevar = 15;function addit() {$GLOBALS["somevar"]++;}addit();print "Somevar is ".$GLOBALS["somevar"];

Static Variables

• A static variable does not lose its value when the function exits, and will still hold that value if the function is called again.

• You can declare a variable as static by placing the keyword STATIC in front of the variable name

Static Variable Example

function keep_track() {STATIC $count = 0;$count++;print $count;print "<br>";}keep_track();keep_track();keep_track();

PHP’S Superglobal Variables

• Predefined variables that contain environment-specific information.

• $_SERVER• $_GET• $_POST• $_COOKIE• $_FILES• $_ENV• $_REQUEST• $_SESSION• $_GLOBALS

$_SERVER

• Contains information created by the Web server.• the following• The following code will output all predefined

variables pertinent to any given Web server and the script’s execution environment:

foreach ($_SERVER as $var => $value) {echo "$var => $value <br />";}

$_SERVER examples

print "Hi! Your IP address is: $_SERVER['REMOTE_ADDR']";

print "Your browser is: $_SERVER['HTTP_USER_AGENT']";

$_GET

• Contains information pertinent to any parameters passed using the GET method.

$_GET Examples

If the URL http://www.example.com/index.html?cat=apache&id=157

was requestedYou could access$_GET['cat'] = "apache"$_GET['id'] = "157"

$_POST

• Contains information pertinent to any parameters passed using the POST method.

$_POST Examples (1)<form action="subscribe.php" method="post"><p>Email address:<br /><input type="text" name="email" size="20" maxlength="50" value="" /></p><p>Password:<br /><input type="password" name="pswd" size="20" maxlength="15" value="" /></p><p><input type="submit" name="subscribe" value="subscribe!" /></p></form>

$_POST Examples (2)

The following POST variables will be made available via the target subscribe.php script:

$_POST['email'] = "jason@example.com";$_POST['pswd'] = "rainyday";$_POST['subscribe'] = "subscribe!";

$_COOKIE

• Stores information passed into the script through HTTP cookies.

$_FILES

• Contains information regarding data uploaded to the server via the POST method.

$_ENV

• Offers information regarding the PHP parser’s underlying server environment.

Constants• boolean define (string name, mixed value [, bool case_insensitive])

define("PI", 3.141592, case_insensitive);print "The value of pi is ".PI.".<br />";$pi2 = 2 * PI;print "Pi doubled equals $pi2.";

• Note– Constant references are not prefaced with a dollar sign. – You can’t redefine or undefine the constant once it has been defined.– Constants are global.

$GLOBALS

• Contains a comprehensive listing of all variables found in the global scope.

• Can be thought of as the superglobal superset.

$_SESSION

• Contains information regarding all session variables.

$_REQUEST

• Records variables passed to a script via any input method, specifically GET, POST, and Cookie.

Expressions

$a = 5; // assign integer value 5 to the variable $a$a = "5"; // assign string value "5" to the variable $a$sum = 50 + $some_int; // assign sum of 50 + $some_int to

$sum$wine = "Zinfandel"; // assign "Zinfandel" to the variable $wine$inventory++; // increment the variable $inventory by 1

Assignment Operators

$a = 5 Assignment $a equals 5

$a += 5 Addition-assignment $a equals $a plus 5

$a *= 5 Multiplication-assignment $a equals $a multiplied by 5

$a /= 5 Division-assignment $a equals $a divided by 5

$a .= 5 Concatenation-assignment $a equals $a concatenated with 5

String Operators

$a = "abc"."def"; Concatenation $a is assigned the string “abcdef”

$a .= "ghijkl"; Concatenation-assignment $a equals its current

value concatenated with “ghijkl”

Increment/Decrement Operators

• ++$a, $a++ Increment Increment $a by 1• --$a, $a-- Decrement Decrement $a by 1

$inv = 15; /* Assign integer value 15 to $inv. */

$oldInv = $inv--; /* Assign $oldInv the value of $inv, then decrement $inv.*/

$origInv = ++$inv; /*Increment $inv, then assign the new $inv value to $origInv.*/

Logical Operators

• $a && $b And • $a AND $b And• $a || $b Or• $a OR $b Or• !$a Not• NOT $a Not• $a XOR $b Exclusive Or

Equality Operators

$a == $b Is equal to True if $a and $b are equivalent

$a != $bIs not equal to True if $a is not equal to $b

$a === $b Is identical to True if $a and $b are equivalent, and

$a and $b have the same type

Comparison Operators

$a < $b Less than $a > $b Greater than $a <= $b Less than or equal to $a >= $b Greater than or equal to

($a == 12) ? 5 : -1 Ternary If $a equals 12, return value is 5;otherwise, return value is –1

Bitwise Operators

• Skip for now.

String Interpolation

• Strings most commonly enclosed in double quotes.

• The backslash “\” is the escape character.• Escape sequences – are ignored by the browser window.– appear in the source.

Recognized Escape Sequences

\n Newline character\r Carriage return\t Horizontal tab\\ Backslash\$ Dollar sign\" Double quote\[0-7]{1,3} Octal notation\x[0-9A-Fa-f]{1,2} Hexadecimal notation

Single Quotes

• Enclose string within single quotes when the string should be interpreted exactly as stated.

echo 'This string will $print exactly as it\'s \n declared.';

producesThis string will $print exactly as it's \n declared.

Heredoc

• Heredoc syntax offers a convenient means for outputting large amounts of text. Rather than delimiting strings with double or single quotes, two identical identifiers are employed.

Heredoc Example

<?php$website = "http://www.romatermini.it";echo <<<EXCERPT<p>Rome's central train station, known as <a href = "$website">Roma

Termini</a>,was built in 1867. Because it had fallen into severe disrepair in the

late 20thcentury, the government knew that considerable resources were

required torehabilitate the station prior to the 50-year <i>Giubileo</i>.</p>EXCERPT;?>

Heredoc Notes• The opening and closing identifiers must be identical.• The opening identifier must be preceded with three left-angle brackets, <<<.• Heredoc syntax follows the same parsing rules as strings enclosed in double quotes.• That is, both variables and escape sequences are parsed. The only difference is that• double quotes do not need to be escaped.• The closing identifier must begin at the very beginning of a line. It cannot be

preceded• with spaces, or any other extraneous character. This is a commonly recurring point

of• confusion among users, so take special care to make sure your heredoc string

conforms• to this annoying requirement. Furthermore, the presence of any spaces following

the• opening or closing identifier will produce a syntax error.

if

<?php$secretNumber = 453;if ($_POST['guess'] == $secretNumber)

echo"<p>Congratulations!</p>";?>

if-else

<?php$secretNumber = 453;if ($_POST['guess'] == $secretNumber) {echo "<p>Congratulations!!</p>";} else {echo "<p>Sorry!</p>";}?>

elseif

<?php$secretNumber = 453;$_POST['guess'] = 442;if ($_POST['guess'] == $secretNumber) {echo "<p>Congratulations!</p>";} elseif (abs ($_POST['guess'] - $secretNumber) < 10) {echo "<p>You're getting close!</p>";} else {echo "<p>Sorry!</p>";}?>

switch<?phpswitch($category) {case "news":print "<p>What's happening around the World</p>";break;case "weather":print "<p>Your weekly forecast</p>";break;case "sports":print "<p>Latest sports highlights</p>";break;default:print "<p>Welcome to my Web site</p>";}?>

while

<?php$count = 1;while ($count < 5) {echo "$count squared = ".pow($count,2).

"<br />";$count++;}?>

do while

<?php$count = 11;do {echo "$count squared = ".pow($count,2).

"<br />";} while ($count < 10);?>

for

// Example Onefor ($kilometers = 1; $kilometers <= 5;

$kilometers++) {echo "$kilometers kilometers = ".

$kilometers*0.62140. " miles. <br />";}

phpinfo.php

<? phpinfo(); ?>

Function - Definitionfunction function_name (parameters) {function-body}

function generate_footer() {echo "<p>Copyright &copy; 2006 W. Jason Gilmore</p>";}

Once it is defined, you can then call this function as you would any other. For example:

<?phpgenerate_footer();?>

Function - Pass by Value

function salestax($price,$tax) {$total = $price + ($price * $tax);echo "Total cost: $total";}

$total and any changes made to the parameters $price and $tax are only available inside the function.

Function - Pass by Reference<?php$cost = 20.00;$tax = 0.05;function calculate_cost(&$cost, $tax){// Modify the $cost variable$cost = $cost + ($cost * $tax);// Perform some random change to the $tax variable.$tax += 4;}calculate_cost($cost,$tax);echo "Tax is: ". $tax*100."<br />";echo "Cost is: $". $cost."<br />";?>

Prefixing variable name with ampersand makes it pass by reference.

Function - Default Argument Values

function salestax($price,$tax=.0575) {$total = $price + ($price * $tax);echo "Total cost: $total";}

$price = 19.95;$tax = .0800;salestax($price); // uses default tax of .0575salestax($price, $tax); // uses tax of .0800

Function - Optional Argument

function salestax($price,$tax="") {$total = $price + ($price * $tax);echo "Total cost: $total";}

Optional arguments are placed at the end of the list and assigned a default value of nothing.

salestax(42.00);

Function - Optional Arguments

function calculate($price,$price2="",$price3="") {

echo $price + $price2 + $price3;}

calculate(10,"",3);

Function – Return Valuefunction salestax($price,$tax=.0575) {$total = $price + ($price * $tax);return $total;}

function salestax($price,$tax=.0575) {return $price + ($price * $tax);}

<?php$price = 6.50;$total = salestax($price);?>

Function – Return Multiple Values

<?phpfunction retrieve_user_profile() {$user[] = "Jason";$user[] = "jason@example.com";$user[] = "English";return $user;}

list($name,$email,$language) = retrieve_user_profile();echo "Name: $name, email: $email, preferred language: $language";?>

Function – Recursionfunction amortizationTable($paymentNum, $periodicPayment, $balance, $monthlyInterest) {$paymentInterest = round($balance * $monthlyInterest,2);$paymentPrincipal = round($periodicPayment - $paymentInterest,2);$newBalance = round($balance - $paymentPrincipal,2);print "<tr><td>$paymentNum</td><td>\$".number_format($balance,2)."</td><td>\$".number_format($periodicPayment,2)."</td><td>\$".number_format($paymentInterest,2)."</td><td>\$".number_format($paymentPrincipal,2)."</td></tr>";# If balance not yet zero, recursively call amortizationTable()if ($newBalance > 0) {$paymentNum++;amortizationTable($paymentNum, $periodicPayment, $newBalance, $monthlyInterest);} else {exit;}} #end amortizationTable()

<?php# Loan balance$balance = 200000.00;# Loan interest rate$interestRate = .0575;# Monthly interest rate$monthlyInterest = .0575 / 12;# Term length of the loan, in years.$termLength = 30;# Number of payments per year.$paymentsPerYear = 12;# Payment iteration$paymentNumber = 1;# Perform preliminary calculations$totalPayments = $termLength * $paymentsPerYear;$intCalc = 1 + $interestRate / $paymentsPerYear;$periodicPayment = $balance * pow($intCalc,$totalPayments) * ($intCalc - 1) / (pow($intCalc,$totalPayments) - 1);$periodicPayment = round($periodicPayment,2);# Create tableecho "<table width='50%' align='center' border='1'>";print "<tr><th>Payment Number</th><th>Balance</th><th>Payment</th><th>Interest</th><th>Principal</th></tr>";# Call recursive functionamortizationTable($paymentNumber, $periodicPayment, $balance, $monthlyInterest);# Close tableprint "</table>";?>

Function - Libraries<?phpfunction local_tax($grossIncome, $taxRate) {// function body here}function state_tax($grossIncome, $taxRate) {// function body here}?>

Save above in file named taxation.library.php

<?phprequire_once("taxation.library.php");...?>

include()• include (/path/to/filename)

• The include() statement will evaluate and include a file into the location where it is called.

• Including a file produces the same result as copying the data from the file specified into the location in which the statement appears.

• You can also execute include() statements conditionally. For example, if an include() statement is placed in an if statement, the file will be included only if the if statement in which it is enclosed evaluates to true. The include() in a conditional must be enclosed in statement block curly brackets.

include_once()

• include_once (path/to/filename)

• Like include() excepts it first verifies whether or not the file has already been included. If it has already been included then include_once will not execute.

require()

• Require (path/to/filename)

• works like include() except– File is include in script regardless of where

require() is located– If placed in an if statement that is false the file is

still included.– Script execution will stop if a require() fails.

require_once()

• Require_once (path/to/filename)

• Like require() excepts it first verifies whether or not the file has already been included. If it has already been included then require _once will not execute.

Arrays

$states = array (0 => "Alabama", "1" => "Alaska"..."49" => "Wyoming");

$states[0]

$states = array ("OH" => "Ohio", "PA" => "Pennsylvania", "NY" => "New York");

$states["OH"]

Array - Multidimensional

$states = array ("Ohio" => array ("population" => "11,353,140",

"capital" => "Columbus"),"Nebraska" => array("population" =>

"1,711,263", "capital" => "Omaha"))

$states["Ohio"]["population"]

range()

array range(int low, int high [,int step])

$die = range(0,6);// $die = array(0,1,2,3,4,5,6)

$even = range(0,20,2);// $even = array(0,2,4,6,8,10,12,14,16,18,20);

$letters = range("A","F");// $letters = array("A,","B","C","D","E","F");

print_r()

Boolean print_r(mixed variable [, boolean return])

print_r($states);//sends output to standard outArray ( [Ohio] => Columbus [Iowa] => Des Moines [Arizona] => Phoenix )

// setting return to true returns output to caller.

$stateCaptials = print_r($states, TRUE);

Testing for an Array

• boolean is_array(mixed variable)

Adding array elements

$states["Ohio"] = "March 1, 1803“

$state[] = "Ohio";If index is numerical you can append an element

by leaving the index blank

array_push()int array_push(array target_array, mixed variable [, mixed variable...])

$states = array("Ohio","New York");

array_push($states,"California","Texas");

// $states = array("Ohio","New York","California","Texas");

Appends to end of array.Returns TRUE on success.

array_pop()

mixed array_pop(array target_array)

$states = array("Ohio","New York","California","Texas");

$state = array_pop($states); // $state = "Texas“

Returns last element from target_array, resetting array pointer upon completion.

array_shift()

mixed array_shift(array target_array)$states = array("Ohio","New York","California","Texas");$state = array_shift($states);// $states = array("New York","California","Texas")// $state = "Ohio"

Returns first element from target_array, resetting array pointer upon completion.

If numerical keys are used, all corresponding values will be shifted down, whereas arrays using associative keys will not be affected.

array_unshift()int array_unshift(array target_array, mixed variable [, mixed variable...])$states = array("Ohio","New York");array_unshift($states,"California","Texas");// $states = array("California","Texas","Ohio","New York");

Adds elements to the front of the array rather than to the end.

All preexisting numerical keys are modified to reflect their new position in the array, but associative keys aren’t affected.

array_pad()array array_pad(array target, integer length, mixed pad_value)$states = array("Alaska","Hawaii");$states = array_pad($states,4,"New colony?");$states = array("Alaska","Hawaii","New colony?","New colony?");

Increases array size to the length specified by length. This is done by padding the array with the value specified by pad_value. If pad_value is positive, the array will be padded to the right side (the end); if it is negative, the array will be padded to the left (the beginning). If length is equal to or less than the current target size, no action will be taken.

top related