php basic
TRANSCRIPT
PHP Basic
About Me
$orienter = new stdClass;$orienter->name = Vibol YOEUNG;$orienter->company = Webridge Technologies$orienter->email = [email protected]
What is PHP?
PHP stands for PHP: Hypertext Preprocessor and is a server-side language. This means that when a visitor opens the page, the server processes the PHP commands and then sends the results to the visitor's browser.
How PHP work?
What can php do?
Allow creation of shopping carts for e-commerce websites.
Allow creation of CMS(Content Management System) Website.
Allow creation of forum website
Allow creation of Web application
Installation
Following things are required for using php on windowsApache Server or IIS Server
MySql
PhpWampServer is a Windows web development environment. With this we can create web applications with Apache, PHP and the MySQL database. Even PHPMyAdmin is provided to manage your databases.
Basic PHP Syntax
Standard Tags: Recommended
Short tags
HTML or script tags
code goes here
Comments
PHP has two form of comments
1.Single-line comments begin with a double slash (//) or sharp (#).2. Multi-line comments begin with "/*" and end with "*/". SyntaxEx.// This is a single-line comment# This is a single-line comment /* This is a multi-line comment. */
Introducing Variables
A variable is a representation of a particular value, such as hello or 87266721. By assigning a value to a variable, you can reference the variable in other places in your script, and that value will always remain the same (unless you change it).
Naming Your Variables
Variable names should begin with a dollar($) symbol.
Variable names can begin with an underscore.
Variable names cannot begin with a numeric character.
Variable names must be relevant and self-explanatory.
Naming Your Variables
Here are some examples of valid and invalid variable names:$_varname valid
$book valid
sum invalid: doesnt start with dollar sign($) $18varname invalid: starts with number; it doesnt start with letter or underscore
$x*y invalid: contains multiply sign which only letters, digits, and underscore are allowed.
Variable Variables
$a = hello;$$a = world;echo $a ${$a};produce the same out put asecho $a $hello;Out put: hello world
Data type
You will create two main types of variables in your PHP code: scalar and array. Scalar variables contain only one value at a time, and arrays contain a list of values or even another array.
Constant Variable
A constant is an identifier for a value that cannot change during the course of a scrip.
define("CONSTANT_NAME", value [, true | false]);
Example
define(MYCONSTANT, This is my constant);echo MYCONSTANT;
Some predefined constants include
__FILE__ Return the path and file name of the script file being parsed. __LINE__ Return the number of the line in the script being parsed. __DIR__ Return the path of the script file being parsed. DIRECTORY_SEPARATOR Return the \ (on Windows) or / (on Unix) depending on OS(Operating System) PHP_VERSION Return the version of PHP in use. PHP_OS Return the operating system using PHP.
Some predefined constants include
Example:
defined() Checks whether a given named constant exists
Using Environment Variables in PHP
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.- $_SERVER['SERVER_ADDR']: Return address: ex. 127.0.01- $_SERVER['SERVER_NAME']: Return server name: ex. Localhost- $_SERVER['HTTP_USER_AGENT']: Return User Agent which request
Function testing on variable
is_int( value ) Returns true if value is an integer, false otherwise
is_float( value ) Returns true if value is a float, false otherwise
is_string( value ) Returns true if value is a string, false otherwise
is_bool( value ) Returns true if value is a Boolean, false otherwise
is_array( value ) Returns true if value is an array, false otherwise
is_null( value ) Returns true if value is null, false otherwise
isset ( $var [, $var [, $... ]] ) return true if a variable is set and is not NULL. If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right
unset( $var ) Unset a given variable
is_numeric($var) Returns true if a variable contains a number or numeric string (strings containing a sign, numbers and decimal points).
Getting Variables from Form in PHP
In case: method="get": To return data from a HTML form element in case form has attribute method=get, you use the following syntax:$_GET['formName'];You can assign this to a variable:$myVariable = $_GET['formName'];
Getting Variables from Form in PHP
In case: method="post": To return data from a HTML form element in case form has attribute method=post, you use the followingsyntax:$_POST['formName'];You can assign this to a variable:$myVariable = $_POST['formName'];
Getting Variables from Form in PHP
In case: method=get or method="post": To return data from a HTML form element in case form has attribute method=get or method=post, you use the followingsyntax:$_REQUEST['formName'];You can assign this to a variable:$myVariable = $_REQUEST['formName'];
Getting Variables from Form in PHP
Example: A BASIC HTML FORM
Import External PHP File
include() generates a warning, but the script will continue execution
include_once() statement is identical to include() except PHP will check if the file has already been included, and if so, not include (require) it again.
include() except PHP will check if the file has already been included, and if so, not include (require) it again.
require() generates a fatal error, and the script will stop
require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
Import External PHP File
ExampleError Example include() Function
Import External PHP File
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 executed! This is because a Warning does not stop the script execution.
Import External PHP File
ExampleError Example require() Function
Import External PHP File
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 is 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 after an error.
Operator
Assignment Operator(=)
Arithmetic Operator+ Add values
- Subtract values
* Multiple values
/ Device values
% Modulus, or remainder
Concatenation Operator(.)+=
-=
/=
*=
%=
. =
Operator
Comparison Operator== Equal: True if value of value1 equal to the value of value2
=== Identical: True if value of value1 equal to the value of value2 and they are of the same type
!= Not equal
Not equal
!== Not identical
< Less then
> Greater then
= Greater then or equal to
Logical Operator
Logical operatorand : $a and $b true if both $a and $b are true
&&: the same and
or: $a and $b true if either $a and $b are true
||: the same or
xor: $a xor $b true if either $a and $b are true, but not both.
!: !$a true if $a is not true
Control Structure
Conditional Statementsif ( expression ) // Single Statement or if ( expression ) { //Single Statement or Multiple Statements } or if ( expression ) : //Single Statement or Multiple Statements
endif;
Control Structure
Using else clause with the if statementif ( expression ) // Single Statement else // Single Statementorif ( expression ) { // Single Statement or Multiple Statements
} else {// Single Statement or Multiple Statements
}orif ( expression ) : // Single Statement or Multiple Statements
else: // Single Statement or Multiple Statements
endif;
Switch Statement
switch ( expression ) { case result1: execute this if expression results in result1 break;
case result2: // execute this if expression results in result2 break;
default: // execute this if no break statement // has been encountered hither to
}
Switch Statement
switch ( expression ) : case result1: execute this if expression results in result1 break;
case result2: // execute this if expression results in result2 break;
default: // execute this if no break statement // has been encountered hither to
endswitch;
Ternary Operator
( expression )?true :false;example$st = 'Hi';$result = ($st == 'Hello') ? 'Hello everyone in the class': 'Hi every body in class';print $result;
Looping statement
While statementwhile ( expression ) { // do something
} Or while ( expression ) : // do something
endwhile;
Looping statement
do while statement
do { // code to be executed
} while ( expression );
Looping Statment
For statemement
for (initialize variable exp; test expression; modify variable exp) // Single Statement Or for (initialize variable exp; test expression; modify variable exp){ // Single Statement or Multiple Statements
} Or for (initialize variable exp; test expression; modify variable exp):// Single Statement or Multiple Statements endfor;
Looping statement
Break statement: Use for terminate the current for, foreach, while, do while or switch structure
Function
function is a self-contained block of code that can be called by your scripts. When called, the function's code is executed.Define functionfunction myFunction($argument1, $argument2) {// function code here
}
Array
There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables. The first column is the key, which is used to access the value.
Array
Numeric arrayNumerically indexed arrays can be created to start at any index value. Often it's convenient to start an array at index 1, as shown in the following example: $numbers = array(1=>"one", "two", "three", "four"); Arrays can also be sparsely populated, such as: $oddNumbers = array(1=>"one", 3=>"three", 5=>"five");
Array
Associative arrayAn associative array uses string indexesor keysto access values stored in the array. An associative array can be constructed using array( ), as shown in the following example, which constructs an array of integers:
$array = array("first"=>1, "second"=>2, "third"=>3); // Echo out the second element: prints "2" echo $array["second"];
The same array of integers can also be created with the bracket syntax: $array["first"] = 1; $array["second"] = 2; $array["third"] = 3;
Using foreach loop with array
The foreach statement has two forms:foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statementExample:// Construct an array of integers $lengths = array(0, 107, 202, 400, 475); // Convert an array of centimeter lengths to inchesforeach($lengths as $cm) { $inch = $cm / 2.54;echo "$cm centimeters = $inch inches\n";
} foreach($lengths as $index => $cm) {$inch = $cm / 2.54; $item = $index + 1; echo $index + 1 . ". $cm centimeters = $inch inches\n";
}
Basic array function
count(mixed var): function returns the number of elements in the array varThe following example prints 7 as expected:$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"); echo count($days); // 7
number max(array numbers)
number min(array numbers)$var = array(10, 5, 37, 42, 1, -56);
echo max($var); // prints 42 echo min($var); // prints -56
File Upload
Before you start uploading files, check a few values in your php.ini file. Look for this section of text:
;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; ;
Whether to allow HTTP file uploads. File_uploads = On ; Temporary directory for HTTP uploaded files (will use system default if not ; specified). upload_tmp_dir = /tempMaximum allowed size for uploaded files. Upload_max_filesize = 2M
File Upload
Before you can use PHP to manage your uploads, you need first construct an HTML form as an interface for a user to upload his file. Have a look at the example below and save this HTML code as index.php. enctype for sent data Choose a file to upload:
File Upload
Processing the Form Data (PHP Code)$_FILES["uploaded_file"]["name"]: the original name of the file uploaded from the user's machine $_FILES["uploaded_file"]["type"]: the MIME type of the uploaded file (if the browser provided the type)
$_FILES["uploaded_file"]["size"]: the size of the uploaded file in bytes
$_FILES["uploaded_file"]["tmp_name"] : the location in which the file is temporarily stored on the server
$_FILES["uploaded_file"]["error"]: an error code resulting from the file upload
Sessions
A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.
Note: The session_start() function must appear BEFORE the tag:
Example:
Sessions
Destroying session- If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable:
- You can also completely destroy the session by calling the session_destroy() function: Note: session_destroy() will reset your session and you will lose all your stored session data.
Cookies
A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
Syntax: setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Cookies
Tip: The value of a cookie named "user" can be accessed by $HTTP_COOKIE_VARS["user"] or by $_COOKIE["user"].Example:
PHP Classes
Reminder a function
Reusable piece of code.Has its own local scope.
function my_func($arg1,$arg2) {>}
Conceptually, what does a function represent?
give the function something (arguments), it does something with them, and then returns a result
Action or Method
What is a class?
Conceptually, a class represents an object, with associated methods and variables
Class Definition
An example class definition for a dog. The dog object has a single attribute, the name, and can perform the action of barking.
Class Definition
class dog {
Define the name of the class.
Class Definition
public $name;
Define an object attribute (variable), the dogs name.
Class Definition
public function bark() {
echo Woof!;
}
Define an object action (function), the dogs bark.
Class Definition
Similar to defining a function..
A class is a collection of variables and functions working with these variables.
Class Usage
Class Usage
require(dog.class.php);
Include the class definition
Class Usage
$puppy = new dog();
Create a new instance of the class.
Class Usage
$puppy->name = Rover;
Set the name variable of this instance to Rover.
Class Usage
echo {$puppy->name} says ;
Use the name variable of this instance in an echo statement..
Class Usage
$puppy->bark();
Use the dog object bark method.
Using attributes within the class..
If you need to use the class variables within any class actions, use the special variable $this in the definition:
class dog {
public $name; public function bark() { echo $this->name. says
Woof!;
}}
Constructor methods
A constructor method is a function that is automatically executed when the class is first instantiated.
Create a constructor by including a function within the class definition with the __construct name.
Remember.. if the constructor requires arguments, they must be passed when it is instantiated!
Constructor Example
Constructor function
Constructor Example
Constructor arguments are passed during the instantiation of the object.
Class Scope
Like functions, each instantiated object has its own local scope.
e.g. if 2 different dog objects are instantiated, $puppy1 and $puppy2, the two dog names $puppy1->name and $puppy2->name are entirely independent..
OOP Concepts
Modifier
In object oriented programming, some Keywords are private, protected and some are public in class. These keyword are known as modifier. These keywords help you to define how these variables and properties will be accessed by the user of this class.
Private
Properties or methods declared as private are not allowed to be called from outside the class. However any method inside the same class can access them without a problem.
Private
Example 1:
Result: Hello world
Private
Example 2:
This code will create error:Fatal error: Cannot access private property MyClass::$private in C:\wamp\www\e-rom\Code\private.php on line 11
Private
Example 3:
This code will create error:Notice: Undefined property: MyClass2::$private in C:\wamp\www\e-rom\Code\private1.php online 14
Protected
When you declare a method (function) or a property (variable) as protected, those methods and properties can be accessed byThe same class that declared it.
The classes that inherit the above declared class.
Protected
Example 1:
Result: Hello Mr. Bih
Protected
Example 2:
Fatal error: Cannot access protected property MyChildClass::$protected in C:\wamp\www\e-rom\Code\public2.php on line 18
Public
scope to make that variable/function available from anywhere, other classes and instances of the object.The same class that declared it.
The classes that inherit the above declared class.
Public
Example 1:
Result:This is a man.This is a manThis is a man.
Extending a Class (Inheritance)
when you extend a class, the subclass inherits each public and protected method from the guardian class. Unless a class overrides those techniques, they will hold their unique functionality
Extending a Class (Inheritance)
Example:
Encapsulation
its the way we define the visibility of our properties and methods. When youre creating classes, you have to ask yourself what properties and methods can be accessed outside of the class.
Encapsulation
Example:
Polymorphism
This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
Polymorphism
Example:
Interface
Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeletons which are implemented by developers.
Interface
Example:
Abstract class
An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this:
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility
Abstract class
Example:
Static Keyword
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
Static Keyword
Example:
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Final Keyword
Example:
Fatal error: Cannot override final method Animal::getName()
Thanks for your time.