PHP BesantTech

14
1. What is PHP? Server-side, scripting language [not a programming language] o Scripting language does something only in response to events o Programming language does something even not response to events JavaScript is another popular scripting language but it is a client-side. Server-side = Web Server, Client-side = User Browser So we need a web server to run PHP. It doesn’t mean it compile the code before execute like C, Java PHP designed to use with HTML o It returns HTML to browser. PHP code is our Input and Web pages are our Output. o File Extension - .php [Because server has to know we are talking about PHP] o We also include HTML code in that file and it returns as it is. It provides more flexibility than HTML alone. o HTML is static by nature. We saw the same page every time we visit. o PHP is dynamic. The page content can change based on conditions such as interactions with the user or data in the database. PHP syntax is similar to C, Java, and PERL. o Lot similar to ASP [Microsoft version of PHP][Active Server Page] 2. History of PHP Version 1: 1994 [Rasmus Lerdorf] o Set of CGI binaries in the C programming language. o To maintain his personal web page. Version 2: 1995 o “Personal Home Page Tools” It was the first public release. Version 3: 1998 [Joined Andi Gutmans and Zeev Suraski] o “PHP: Hypertext Preprocessor” It still supported by web browser. But it doesn’t now actively maintain. Version 4: 2000 o Updated completely from version 3. o Formed a company “ZEND”. It actively guides development. o It still supported by updates and bug fixes Version 5: 2004 o It also a big update compared to previous version. o Object Oriented Language and better database connectivity included. o Latest version is 5.4. 3. Why Use PHP? Several advantages compared to other web technologies. Open Source / Free software. o Anyone can develop the advanced version using the PHP apart from ZEND. o It is a cross platform compatible. Cross platform to develop, to deploy, and to use.

description

PHP

Transcript of PHP BesantTech

Page 1: PHP BesantTech

1. What is PHP?

Server-side, scripting language [not a programming language]

o Scripting language does something only in response to events

o Programming language does something even not response to events

JavaScript is another popular scripting language but it is a client-side.

Server-side = Web Server, Client-side = User Browser

So we need a web server to run PHP. It doesn’t mean it compile the code before

execute like C, Java

PHP designed to use with HTML

o It returns HTML to browser. PHP code is our Input and Web pages are our

Output.

o File Extension - .php [Because server has to know we are talking about PHP]

o We also include HTML code in that file and it returns as it is.

It provides more flexibility than HTML alone.

o HTML is static by nature. We saw the same page every time we visit.

o PHP is dynamic. The page content can change based on conditions such as

interactions with the user or data in the database.

PHP syntax is similar to C, Java, and PERL.

o Lot similar to ASP [Microsoft version of PHP][Active Server Page]

2. History of PHP

Version 1: 1994 [Rasmus Lerdorf]

o Set of CGI binaries in the C programming language.

o To maintain his personal web page.

Version 2: 1995

o “Personal Home Page Tools”

It was the first public release.

Version 3: 1998 [Joined Andi Gutmans and Zeev Suraski]

o “PHP: Hypertext Preprocessor”

It still supported by web browser. But it doesn’t now actively

maintain.

Version 4: 2000

o Updated completely from version 3.

o Formed a company “ZEND”. It actively guides development.

o It still supported by updates and bug fixes

Version 5: 2004

o It also a big update compared to previous version.

o Object Oriented Language and better database connectivity included.

o Latest version is 5.4.

3. Why Use PHP?

Several advantages compared to other web technologies.

Open Source / Free software.

o Anyone can develop the advanced version using the PHP apart from ZEND.

o It is a cross platform compatible.

Cross platform to develop, to deploy, and to use.

Page 2: PHP BesantTech

It means we can put PHP code in Windows server, Linux server and

MAC server.

Powerful, robust and scalable.

Web development specific

Can be Object Oriented, Especially Version 5

Great documentation in many languages. [www.php.net/docs.php]

Large, active developer community. [Over 40 million websites]

World’s most popular web server Apache.

o 4th most popular programming language of all. [Java, C, C++]

But all are compiled languages.

Ahead of PERL, PYTHON, C#, JavaScript.

4. Installation

Web Server [Apache – 75% of web users use & 20% - Microsoft IIS]

PHP [5.2.1]

Database [MySQL 5.0]

Text Editor [Notepad++]

Web Browser [Firefox or Chrome]

Best Combination is LAMP, MAMP, WAMP and XAMPP.

5. First Steps

After having all the above things we are ready to dive in.

We want to know our web server is up and running. So a simple php code explains

that clearly.

o <?php phpinfo(); ?>

<?php – begin command for php.

?> - end command for php.

Bad form - <? ?> or <?= ?>

Example01 – basic.html

<html>

<head>

<title>Basic Example</title>

</head>

<body>

Basic Things First

</body>

</html>

Replace body content with <?php phpinfo(); ?> and save

Example02 – helloworld.php

<html> <head> <title>Basic Example</title> </head> <body> <?php echo “Hello World!!”; ?>

Page 3: PHP BesantTech

</body> </html>

Hello World!! – Object, ; - Instruction Separator, echo – similar to print

After run in browser “view source” in browser

Replace “echo” with “print”

Concatenation example [ <?php echo “Hello” . “ World!!”; ?> ]

Perform simple math functions [ <?php echo 3+3; ?> ]

Operational Trail

D

To become good programmers we need to practice “comments”

o Single-line commenting - // or #

o Multi-line commenting - /* */

o <?php //Single line comment # Like this also /*Multi line commenting Are like this Too */

6. Exploring Data Types

Variables o “Symbolic Representation of a value” o It may vary over time. o Variable Names

Starts with a $ Followed by a letter or underscore[_] It can contain letter, number, underscore, or dashes. No Spaces allowed. Case sensitive.

o Example Variable Names $item [personal preference] $Item $myVariable

Page 4: PHP BesantTech

$this_variable [personal preference] $this-variable [looks like minus sign, so don’t use it] $product3 $_book [php itself use this type to define some set of variable] $__bookPage [need to count how many underscore may not

productivity] o Example03 – variables.php

<?php $var1 = 10; echo $var1; // $myVariable and $myvariable are different $my_variable = "Hello Besant"; $my_Variable = "Hello World Again"; echo $my_Variable; echo "<br />"; ?> <?php // variables values are variable; $var1 can be assigned a new value $var1 = 100; echo $var1; ?>

Strings o Example04 – strings.php

<?php // Simple string, surrounded by single quotes. // (included HTML still works just like HTML when output) echo 'Hello World<br />'; // Simple string, surrounded by double quotes. (best practice) echo "Hello World<br />"; // Strings can be assigned to variables $my_variable = "Hello World"; echo $my_variable; echo "<br />"; // and concatenated with other strings or variables containing strings echo $my_variable . " Again"; ?> <br /> <?php // PHP will substitute the value of a string for a variable inside double-quotes echo "$my_variable Again.<br />"; // curly brackets can help make this substitution clearer // sometimes required to help PHP know that it is a variable // e.g. "{$hour}am" is clear while $houram is not // (best practice) echo "{$my_variable} Again.<br />"; // Variable substitution does not take place inside single quotes

Page 5: PHP BesantTech

echo '$my_variable Again.<br />'; ?>

String Functions o Example05 – string_functions.php

<?php $firstString = "The quick brown fox"; $secondString = " jumped over the lazy dog."; ?> <?php // Concatentation $thirdString = $firstString; $thirdString .= $secondString; echo $thirdString . "<br/>"; $fourthiString = $firstString . $secondString . " yes"; echo $fourthiString; ?> <br /> Lowercase: <?php echo strtolower($thirdString); ?><br /> Uppercase: <?php echo strtoupper($thirdString); ?><br /> Uppercase first-letter: <?php echo ucfirst($thirdString); ?><br /> Uppercase words: <?php echo ucwords($thirdString); ?><br /> <br /> Length: <?php echo strlen($thirdString); ?><br /> Trim: <?php echo $fourthString = $firstString . trim($secondString); ?><br /> Find: <?php echo strstr($thirdString, "brown"); ?><br /> Replace by string: <?php echo str_replace("quick", "super-fast", $thirdString); ?>

<br /> Repeat : <?php echo str_repeat($thirdString,4); ?><br/> Make Substring : <?php echo substr($thirdString,0,1); ?><br/> Find Position : <?php echo strpos($thirdString,"The"); ?><br/> Find Character : <?php echo strchr($thirdString, "over"); ?><br/>

Numbers o Example06 – numbers.php

<?php $var1 = 3; $var2 = 4; ?> Basic Math: <?php echo ((1 + 2 + $var1) * $var2) / 2 - 5; ?><br /> <br /> <?php // You can perform math operations directly on values ?> +=: <?php $var2 += 4; echo $var2; ?><br /> -=: <?php $var2 -= 4; echo $var2; ?><br /> *=: <?php $var2 *= 3; echo $var2; ?><br /> /=: <?php $var2 /= 4; echo $var2; ?><br /> <br /> Increment: <?php $var2++; echo $var2; ?><br /> Decrement: <?php $var2--; echo $var2; ?><br />

Numbers: Floating Point Numbers o Example07 – float.php

<?php

Page 6: PHP BesantTech

// Floating Point Numbers (floats) are "numbers with a decimal" $var1 = 3.14 ?> <?php

// Floats can occur when two numbers don't divide evenly echo 4/3; ?> Floating point: <?php echo $myFloat = 3.14; ?><br /> Round: <?php echo round($myFloat, 1); ?><br /> Ceiling: <?php echo ceil($myFloat); ?><br /> Floor: <?php echo floor($myFloat); ?><br />

Array o Example – array.php

<? /* Think of an array like an expandable file folder where you can put items in each of the pockets There are no limits to how many pockets it can have (not that you'll need to worry about at least) Then you can reference those items by the pocket number (or "index") (This is the "value" of that "position" in the array) Be careful! Pockets are numbered starting at 0 (0,1,2,3...) so the index of the 2nd pocket is 1 */?> <?php // defining a simple array $array1 = array(4,8,15,16,23,42); // referencing an array value by its index echo $array1[0]; // arrays can contain a mix of strings, numbers, even other arrays $array2 = array(6,"fox", "dog", array("x", "y", "z")); // referencing an array value that is inside another array echo $array2[3][1]; ?> <br /> <?php // Changing values in an array that has already been defined // It's just like variables but you use the index to reference the array position $array2[3] = "cat"; echo $array2[3]; ?> <br /> <?php // You can also assign labels to each pocket (called "keys"), $array3 = array("first_name" => "Kevin", "last_name" => "Skoglund"); // which will allow you to use the key to reference the value in that array position. echo $array3["first_name"] . " " . $array3["last_name"] . "<br />"; $array3["first_name"] = "Larry"; echo $array3["first_name"] . " " . $array3["last_name"] . "<br />"; ?> <br /> A good way to see the values inside an array during development:<br />

Page 7: PHP BesantTech

<pre><?php print_r($array2); ?></pre>

Array Functions o Example – arrayfunctions.php <?php $array1 = array(4,8,15,16,23,42); ?> Count: <?php echo count($array1); ?><br /> Max value: <?php echo max($array1); ?><br /> Min value: <?php echo min($array1); ?><br /> <br /> Sort: <?php sort($array1); print_r($array1); ?><br /> Reverse Sort: <?php rsort($array1); print_r($array1); ?><br /> <br /> <?php // Implode converts an array into a string using a "join string" // Explode converts a string into an array using a "divide string" ?> Implode: <?php echo $string1 = implode(" * ", $array1); ?><br /> Explode: <?php print_r(explode(" * ", $string1)); ?><br /> <br /> In array: <?php echo in_array(15, $array1); // returns T/F ?><br />

Booleans o Example – booleans.php <?php /* Booleans are used to represent the concepts of true and false. They are most often used for testing if a statement is true or false and they'll play a bigger role when we discuss logical expressions. Note that there is a difference between boolean true/false and the strings "true"/"false". */ $bool1 = true; $bool2 = false; // When booleans are displayed, PHP will attempt to convert them into a string // You'll get either "1"/"0" or "1"/"" instead of true/false ?> $bool1: <?php echo $bool1; ?><br /> $bool2: <?php echo $bool2; ?><br /> <br /> <?php /* NULL is used to represent the concept of nothing or the state of being empty In the below example three variable have been set, then boolean tests are performed and the results are output as a string */ $var1 = 3; $var2 = "cat"; $var4 = NULL; // isset tests whether a variable has been set // It returns true or false as a result of the test. ?> $var1 is set: <?php echo isset($var1); // result: true ?><br /> $var2 is set: <?php echo isset($var2); // result: true ?><br /> $var3 is set: <?php echo isset($var3); // result: false ?><br /> <?php unset($var1); ?>

Page 8: PHP BesantTech

$var1 is set: <?php echo isset($var1); // result: false ?><br /> $var2 is set: <?php echo isset($var2); // result: true ?><br /> $var3 is set: <?php echo isset($var3); // result: false ?><br /> <br /> <?php // empty test whether a variable is empty ?> $var1 empty: <?php echo empty($var1); // result: true ?><br /> $var4 empty: <?php echo empty($var4); // result: true ?><br />

Typecasting o Example – typecasting.php <?php // PHP will try to convert between types (strings, number, arrays, etc.) as best it can // Sometimes it will make educated guesses as to what you mean // For example, if you add a string and a number like this: $var1 = "2 brown foxes"; $var2 = $var1 + 3; echo $var2; ?> <br /> <?php // gettype will retrieve an item's type echo gettype($var1); echo "<br />"; echo gettype($var2); echo "<br />"; // settype will convert an item to a specific type settype($var2, "string"); echo gettype($var2); echo "<br />"; // Or you can specify the new type in parentheses in front of the item $var3 = (int) $var1; echo gettype($var3); echo "<br />"; ?> <?php // You can also perform tests on the type (which return booleans) ?> is_array: <?php echo is_array($var1); // result: false ?><br /> is_bool: <?php echo is_bool($var1); // result: false ?><br /> is_float: <?php echo is_float($var1); // result: false ?><br /> is_int: <?php echo is_int($var1); // result: false ?><br /> is_null: <?php echo is_null($var1); // result: false ?><br /> is_numeric: <?php echo is_numeric($var1); // result: false ?><br /> is_string: <?php echo is_string($var1); // result: true ?><br />

Constants o Example – constants.php <?php /* Constants can't change their values after being defined Constant names use all capital letters and no dollar sign */ // Assignment to a variable $max_width = 980; // Assignment to a constant define("MAX_WIDTH", 980); // Referencing the value of a constant echo MAX_WIDTH; echo "<br />";

Page 9: PHP BesantTech

// Trying to change a constant will give an error: // MAX_WIDTH += 1; // But changing a variable will not. $max_width += 1; echo $max_width; /* Note that once a page is returned, a constant CAN be redefined by another PHP page. For example: Browser Request 1 -> page1.php -> SIZE defined as 10 -> PHP page finishes -> Page 1 Returned Browser Request 2 -> page2.php -> SIZE defined as 20 -> PHP page finishes -> Page 2 Returned SIZE must remain 10 throughout page1.php, but when the 2nd request comes in SIZE is not defined */ ?>

7. Control Structures – Logical Expressions

If , else if, else Statements o Example – logical.php <?php /* if, elseif, else if (expression) statement; does NOT require semicolons except after statements {} go around multi-line if-statements {} are optional for single-line if-statments but I strongly suggest them expressions always evaluate to a boolean value (true/false) expressions can use comparison operators (==, !=, >, <, >=, <=) */ ?> <?php $a = 5; $b = 4; if ($a > $b) { echo "a is larger than b"; } elseif ($a == $b) { // if 1st expression is false, elseif performs a 2nd test echo "a equals b"; } else { // if all expressions are false, else gives an alternative statement echo "a is smaller than b"; } ?> <br /> <?php // Expressions can also use logical operators to combine expressions // && is a logical AND // || is a logical OR $c = 1;

Page 10: PHP BesantTech

$d = 20; if (($a > $b) && ($c > $d)) { echo "a is larger than b AND "; echo "c is larger than d"; } if (($a > $b) || ($c > $d)) { echo "a is larger than b OR "; echo "c is larger than d"; } else { echo "neither a is larger than b or c is larger than d"; } ?> <br /> <?php // ! is a logical NOT and it negates an expression unset($a); if (!isset($a)) { // read this as "if not isset $a" or "if $a is not set" $a = 100; } echo $a; ?> <br /> <?php // Use a logical test to determine if a type should be set if (is_int($a)) { settype($a, "string"); } echo gettype($a); ?>

Switch Statements o Example – logical2.php <?php

/* switch Useful when there are many possible actions based on the value of single variable */ $a = 2; switch ($a) { case 0: echo "a equals 0"; break; case 1: echo "a equals 1"; break; case 2: echo "a equals 2"; break; default: echo "a is not 0, 1, or 2"; break; } ?>

Page 11: PHP BesantTech

Loops : while

o Example – whileloops.php

<?php /* while loops while(expression) statement; {} around multi-line statements (like if-statements) watch out for infinite loops */ // This loop outputs 0-10 $count = 0; while ($count <= 10) { echo $count . ", "; $count++; } echo "<br />Count: {$count}"; ?> <br /> <?php // Loops can be combined with if-statements $count = 0; while ($count <= 10) { if ($count == 5) { echo "FIVE, "; } else { echo $count . ", "; } $count++; } echo "<br />Count: {$count}"; ?>

Loops : for

o Example – forloops.php

<?php /* for loops for (expr1; expr2; expr3) statement; semicolons separate three expressions: expr1 executed at start (initialize) expr2 evaluated at the start of each loop, continues as long as it is TRUE expr3 executed at the end of each loop {} around multi-line statements (like if-else) watch out for infinite loops */ ?> <?php // Outputs 1-10 for ($count=0; $count <= 10; $count++) { echo $count . ", ";

Page 12: PHP BesantTech

} ?>

Loops : foreach

o Example – foreachloops.php

<?php /* foreach loops foreach (array_expression as $value) statement; foreach (array_expression as $key => $value) statement; Works only on arrays! */ ?> <?php $ages = array(4, 8, 15, 16, 23, 42); ?> <?php // using each value foreach($ages as $age) { echo $age . ", "; } ?> <br /> <?php // using each key => value pair foreach($ages as $position => $age) { echo $position . ": " . $age . "<br />"; } ?> <br /> <?php // Just for fun... $prices = array("Brand New Computer"=>2000, "Training Fees"=>7000, "Learning PHP" => "priceless"); foreach($prices as $key => $value) { if (is_int($value)) { echo $key . ": Rs." . $value . "<br />"; } else { echo $key . ": " . $value . "<br />"; } } ?>

Loops : continue

o Example – continue.php

<?php /* continue Imagine that every loop has an implicit "continue" at the end

Page 13: PHP BesantTech

You can also have an explicit "continue" which will loop back to the top immediately i.e. skip the remaining statements and start the next cycle of the loop Useful if you can quickly determine that the rest of the loop contents won't apply If you can, it could speed up your loop! */ ?> <?php // skips the number 5 for ($count=0; $count <= 10; $count++) { if ($count == 5) { continue; } echo $count . ", "; } ?>

Loops : break

o Example – break.php

<?php /* break Breaks out of a loop immediately without performing remaining statements or further loop cycles */ // Notice that the for loops had a comma after 10 // We could fix that this way: for ($count=0; $count <= 10; $count++) { echo $count; if ($count == 10) { break; } echo ", "; } ?>

Loops : pointers

o Example – pointers.php

<?php // Pointers and while loops revisited $ages = array(4, 8, 15, 16, 23, 42); ?> <?php // Arrays have pointers that point to a position in the array // We can use current, next and reset to manipulate the pointer echo "1: " . current($ages) . "<br />"; next($ages); echo "2: " . current($ages) . "<br />"; reset($ages); echo "3: " . current($ages) . "<br />"; ?> <br /> <?php

Page 14: PHP BesantTech

// while loop that moves the array pointer // It is important to understand this type of loop before working with databases while ($age = current($ages)) { echo $age . ", "; next($ages); } ?>