Вы находитесь на странице: 1из 41

PHPintroduction :

PHP is by default installed on the 80 port, official well known port for HTTP.

In early versions, PHP used to stand for Personal Home Page. It was renamed to 'PHP: Hypertext Preprocessor'. It is a scripting language, originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in standalone graphical applications. The structure of PHP has been influenced by C, Perl, Java, C++ and Python. So you may find many similarities while using PHP, if you have experience with any of those languages.
Web content management systems written in PHP include MediaWiki, Joomla, eZ Publish, WordPress,Drupal and Moodle. Basic object-oriented programming functionality was added in PHP 3 and improved in PHP 4.Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance. Php tags start and end o : <?php

?> or the shorthand PHP tag that requires shorthand support to be enabled

On your server... <?


WAMPIntroduction :

?>

WAMP SERVER : wamp latest release is 2.1 but we are using 2.0c
WAMP is an acronym for Windows, Apache, MySQL and PHP. It is a combination of independently created softwares bundled together into a SINGLE installation package to set up a SERVER on your machine with out any hassles. It comes with the GPL License.

Apache HTTP Server:

Widely know as Apache Server is the most widely used webserver out

there. Apache is developed and maintained by an open community of developers under the guidance of the Apache Software Foundation. It is available for wide variety of operating systems like Windows, Mac OS X, Linux, Unix, FreeBSD etc.

MySQL:

It is a relational database management system (RDBMS). In which data is stored in the form

of tables and the relationship among the data is also stored in the form of tables. The program runs as a server providing multi-user access to a number of databases. MySQL is popular for web applications and acts as the database component of the LAMP, BAMP, MAMP, and WAMP platforms (Linux/BSD/Mac/Windows-Apache-MySQL-PHP/Perl/Python), and for open-source bug tracking tools like Bugzilla. Its popularity for use with web applications is closely tied to the popularity of PHP and Ruby on Rails, which are often combined with MySQL.

PHP

and MySQL are essential components for running popular content management systems such as

Drupal, Joomla!, WordPress and some BitTorrent trackers.

In your wamp directory you should see the following folders. a. apache2 This is where the apache web server is installed. Apache will run our php code and scripts on the web browser. b. mysql This is where MySql databse is installed. MySQL is an open source database. PHP and MySQL work really well together. You can use PHP and MySql to store data. c. php You guessed it. This is where php modules are stored. d. www This is the root folder of our web server. This is where you are going to put all your php files and scripts. e. wampserver.exe This file will run the WAMP program. We need to start WAMP everytime we want to work with PHP.
f. When you type in http://localhost in your browser, it executes the index.php file in your www folder. All our php files will go in the www folder.
Writing php code :

<html> <title>my php page</title> <body> <?php echo "hello there!"; ?> </body> </html>

All php code must be embedded within the <?php ?> Echo is a special statement in php for outputing data to the browser. This statement is more often used when we need to print something to the browser. You will learn how to use echo in as we go along. o Echo statement is powerful in a sense that you can put HTML code in it and it will render the text as if it was HTML in your browser. o echo "<b>hello there!</b>"; o you cannot use html code inside <?php ?>, except in the echo statement.

at the end of each PHP statement we need need to put a semicolon, i.e. " ;" . Otherwise PHP will report syntax error.

Save this file with .php ext in the www folder and then execute. Run it with browser and check the view source Echo Examples : o o o o Echo simple echo with html echo variables echo with concatenation

Example : Get system information from PHP o <?php phpinfo(); ?>

Variables : o o o Variables are prefixed with a dollar symbol and a type does not need to be specified in advance. Unlike function and class names, variable names are case sensitive. Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign, then write the variable name and finally assign a value to it. $x = 2; or $x = hello; Var names cannot start with a number. Only letters (upper and lower) , numbers and underscore is allowed in any var.

o o

o PHP variables are case sensitive, that means they could be either lower case or upper case or combination of both.
o It is loosely typed language

o You don't have to worry about declaring the type of the variable. For example strings and integers are declared the same way. o It's good practice to initialize a variable i.e. assign it a value. Uninitialized variables in PHP have a value of either false, empty string or empty array.
o o o Variables of the "resource" type represent references to resources from external sources. gettype(var) : returns the type of the variable settype(): sets the type of the var

<?php $foo = "5bar"; // string $bar = true; // boolean settype($foo, "integer"); // $foo is now 5 (integer) settype($bar, "string"); // $bar is now "1" (string) ?>

Whenconvertingto strings:

NULL is always converted to an empty string. A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string) .

var_dump(): prints the type and value of a variable This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure. <?php $b = 3.1; $c = true; var_dump($b, $c); ?> The above example will output:

float(3.1) bool(true)
o It can also be used to display info abt more than one variable at a time.

print_r() : is also used to print value of var, arrays as keys and values , objects etc. It does not print the type of var only the value. Can be explored more in arrays

Type Juggling
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer. An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer.

Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> To force a variable to be evaluated as a certain type, To change the type of a variable, use settype() function.

Type Casting
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. <?php $foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is a boolean ?> The casts allowed are: (int), (integer) - cast to integer (bool), (boolean) - cast to boolean (float), (double), (real) - cast to float (string) - cast to string (array) - cast to array (object) - cast to object (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1 Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent: <?php $foo = (int) $bar; $foo = ( int ) $bar; ?>

Casting literal strings and variables to binary strings: <?php $binary = (binary) $string; $binary = b"binary string"; ?> Note: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes. <?php $foo = 10; // $foo is an integer $str = "$foo"; // $str is a string $fst = (string) $foo; // $fst is also a string // This prints out that "they are the same" if ($fst === $str) { echo "they are the same"; } ?> It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:
Constants :

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script. A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. define("FOO", "something"); define("FOO2", "something else"); all constants are of global scope. All variables are put in the global scope i.e. $GLOBALS array except if they are declared in a function.vars inside a function are local.

o o o

Operators :
o The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18. When operators have equal precedence, their associativity decides whether they are evaluated starting from the right, or starting from the left.

Associativity left left right


o

Operator */% +-.

Addln info arithmetic arithmetic and string

= += -= *= /= .= %= &= assignment |= ^= <<= >>= =>

Associativity example : echo the sum is .$a+$b where $a=10 and $b=20, the output is 20. Coz . and + , - haveequalprecedenceand assocrules formleft to right. So $a is appendedto the stringwhichnow becomesthe sumis 10 and this is addedto $b. Theintegerrepresentationof this stringis 0 and0+$b= 20.

o
o

$a = 3 * 3 % 5; // (3 * 3) % 5 = 4s
Arithmetic :

Arithmeticoperatorson charactervars :

Asci value is not incremented like C. $a = 'Z'; $a++; turns $a into 'AA'

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged. Flg line has no effect
o o o $c = '^'; $c++; echo $c;

Incrementing or decrementing booleans has no effect.

o o

Assignment Comparison : == equal : Checks for the equality of value

=== identical : checks for the equality of value and also whether both operands are of same type

Increment/decrement : Post increment : $a = $i++; the value is used first and the incremented.

Pre Increment : $a = ++$i; the value is incremented and then used to assign to a.

Logical : // The constant false is assigned to $f and then true is ignored coz of = having higher prec // Acts like: (($f = false) or true) $f = false or true; // The result of the expression (false || true) is assigned to $e // Acts like: ($e = (false || true)) $e = false || true; &&, || , and , or order of precedence : "||" , '=' and then "or". Short circuit operators have greater precedence than normal and , or.

Loops : for, while, do while Conditional statements : if, nested if, if else if Control structures :
o break ends execution of the current for, foreach, while, do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

o while (++$i) {
switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Exit the switch and the while. */ default: break; }

Switch: In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster. <?php switch ($i) { case 0: echo "i equals 0"; break; case 1: echo "i equals 1"; break; case 2: echo "i equals 2"; break; default: echo "i is not equal to 0, 1 or 2"; } ?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

Forms :
o The PHP $_REQUEST Function : The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST function can be used to collect form data sent with both the GET and POST methods. $_POST : The built-in $_POST function is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file). $_GET : The built-in $_GET function is used to collect values from a form sent 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 has limits on the amount of information to send.

User defined Functions : o A function may be defined using syntax such as the following:

o function foo($arg_1, $arg_2, /* ..., */ $arg_n)


{ echo "Example function.\n"; return $retval; } o o Any valid PHP code may appear inside a function, even other functions and class definitions Sequence of function definition and function call does not matter. You can call it in your program before its definition in the php file, but the definition must exist at a later point.

o o Nested functions :

function foo() { function bar() { echo "I don't exist until foo() is called.\n"; } } /* We can't call bar() yet since it doesn't exist. */ foo(); // only foo() and not bar() will be executed /* Now we can call bar(), foo()'s processesing has made it accessible. */ bar();

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. PHP does not support function overloading

Pass by value / reference : By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. o To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition See fnDemo.php

Use of default parameters in functions : if u specify a default value, it is allowed to call a function without any arguments. o You can also pass null or array elements as default value

o function makecoffee($type = "cappuccino")


{ }s o The default value must be a constant expression, not (for example) a variable, a class member or a function call. Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise things will not work as expected if you do not supply any argument in fn call but an arg exists as per fn defintion without any default value, it gives a warning not an error. If the arg has been given a default value in the fn definition, then it uses the default value. return "Making a cup of $type.\n";

Returning values : Values are returned by using the optional return statement o o Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. If the return() is omitted the value NULL will be returned. If, you want to return multiple values, use an array. But return statement cannot be repeated in a function, it can occur only once.

o
o

Variable functions :

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

$func = 'foo'; // a variable $func $func(); // This calls foo() after evaluating value of var $func = 'bar'; $func('test'); // This calls bar()

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When a function is defined in a conditional manner such as the example shown. Its definition must be processed prior to being called. if ($makefoo) { function foo() { echo "I don't exist until program execution reaches me.\n"; } } after this if loop we can call foo()

Arrays :
o o An array is a special variable, which can store multiple values in one single variable. In PHP, there are three kind of arrays: Numeric array - An array with a numeric index Associative array

An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.

array( key => value , ... ) // key may only be an integer or stringy // value may be any value of any type
An array where each ID key is associated with a value. Key cannot be repeated but value can.

PHP automatically uses incrementing numbers for array keys when you create an array or add elements to an array with the empty brackets syntax.
$asc_arr = array("bca" => 121 , "bba" => 122 , "msc" => 141, "mba" => 142);

//alternate way $asc_arr['bba']=122;

Floats in key are truncated to integer.

Multidimensional array - An array containing one or more arrays


Another way to add elements in the array is by equating the string to be inserted with the array variable: this element will be added to the end as it is the empty index.

$arrayvariable[]="String to be inserted to the array But if you write $arrayvariable = hello; then preivuos elements of the array will be overwritten and it will now contain only one str, as index not specified so it is like equating a new array to the old one.

Array Functions :
count(array,mode) : array mode Required. Specifies the array or object to count. Optional. Specifies the mode of the function. Possible values: 0 - Default. Does not detect multidimensional arrays (arrays within arrays) 1 - Detects multidimensional arrays Note: This parameter was added in PHP 4.2

ksort(array,sorttype) : The ksort() function sorts an array by the keys. The

values keep their original keys.


Parameter array sorttype Description

Required. Specifies the array to sort Optional. Specifies how to sort the array values. Possible values: SORT_REGULAR - Default. Treat values as they are (don't change types) SORT_NUMERIC - Treat values numerically

SORT_STRING - Treat values as strings SORT_LOCALE_STRING - Treat values as strings, based on local settings

Sort() : The sort() function sorts an array by the values.


rsort() : Sorts an array in reverse order

This function assigns new keys for the elements in the array. Existing keys will be removed

in_array(search,array,type) : The in_array() function searches an array for a specific value. This function returns TRUE if the value is found in
the array, or FALSE otherwise.
Parameter Description

search array type

Required. Specifies the what to search for Required. Specifies the array to search Optional. If this parameter is set, the in_array() function searches for the search-string and specific type in the array

array_push(array,value1,value2...) : The array_push() function inserts one or more elements to the end of an array.
Parameter Description array value1 value2 Required. Specifies an array Required. Specifies the value to add Optional. Specifies the value to add

array_pop(array) : deletes last element of the array array_slice(array,start,length,preserve) : The array_slice() function

returns selected parts of an array. The original contents of array remain unchanged.
If the array have string keys, the returned array will allways preserve the keys. For other numeric keys, the preserve parameter shud be set to true for preserving keys, else returned arr will hv new keys array start Required. Specifies an array Required. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array. Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.

length

preserve Optional. Possible values: true - Preserve keys false - Default - Reset keys array_splice(array,start,length,array) : The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Parameter Description array start Required. Specifies an array Required. Numeric value. Specifies where the function will start removing elements. 0 = the first element. If this value is set to a negative number, the function will start that far from the last element. -2 means start at the second last element of the array. Optional. Numeric value. Specifies how many elements will be removed, and also length of the returned array. If this value is set to a negative number, the function will stop that far from the last element. If this value is

length

not set, the function will remove all elements, starting from the position set by the start-parameter. array Optional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array.

array_merge(array1,array2,array3...) : function merges one ore

more arrays into one array


array_shift() : shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. array_search() : Searches an array for a given value and returns the key. array_search(value,array,strict) : Parameter Description value array strict Required. Specifies the value to search for Required. Specifies the array to search in Optional. Possible values: true false - Default When set to true, the number 5 is not the same as the string 5 (See example 2)

<?php $a=array("a"=>"5","b"=>5,"c"=>"5"); echo array_search(5,$a,true); ?> Output is b.

unset($arr[5]); // This removes the element from the array. The size of the array also decreases.
Unlike pop which deleted only the last element, you can use unset to delete any element at any position in the array. Unset can be used to delete any normal variable which is not in an array.

unset($arr);

// This deletes the whole array

only using unset on an associative or a non associative array does not re index the array. The entire value and key is removed for an associative array. so if index 2 is removed, the array has indexes 0,1,3 and 4 you can then reassign value to the index 2 which was unset earlier

isset : Determine if a variable is set and is not NULL

array_values : The unset() function allows removing keys from an


array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

array array_values ( array $input ) : returns all the values from the input array and indexes numerically the array.It will remove any user given indexed and put the deafult o,1,2 indexes.

array_keys() returns the keys, numeric and string, from the input
array. array_keys(array,search_value,strict) o search_value : returns only those keys who have value that matches the search_value entered. If specified, then only keys containing these values are returned. strict : Determines if strict comparison (===) should be used during the search the search_value and strict parameter are optional. keys are returned as a array of keys.

o o o

For a non associative array, the array_keys fnction returns the position/index of the key being searched.

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index array_key_exists(value,$arr) : will return true if the value exists in the $arr else returns false. in_array : Checks if a value exists in an array.

in_array(value,array,strict) : searches for the given value in the given array. If strict is set to true it matches the data type also. If strict is false, data type is not matched, only values are. So 5 will be considered equal to 5 if strict is false.

array_combine : array_combine (array $keys , array $values ) Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values. Returns the combined array, FALSE if the number of elements for each array isn't equal.

string implode ( string $glue , array $pieces ) : join array elements with a string Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. $array = array('lastname', 'email', 'phone'); $comma_separated = implode(",", $array);

array explode ( string $delimiter , string $string [, int $limit ] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last -limit are returned. If the limit parameter is zero, then this is treated as 1.

asort Sort an array based on its values and maintain index association. asort($arr);

For multidimensional arrays, refer to class program

File Handling :

In php u can, create a file by directly opening it using the correct mode or using

Read: 'r' Open a file for read only use. The file pointer begins at the front of the file. Write: 'w' Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file. Append: 'a' Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file. A file pointer is PHP's way of remembering its location in a file. Read/Write: 'r+' Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.

Write/Read: 'w+' This is exactly the same as r+, except that it deletes all information in the file when the file is opened. Append: 'a+' This is exactly the same as r+, except that the file pointer is at the end of the file.

A list of possible modes for fopen() using mode


mod e

Description

Open for reading only; place the file pointer at the beginning of the file. Open for reading and writing; place the file pointer at the 'r+' beginning of the file. Open for writing only; place the file pointer at the beginning of 'w' the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+ Open for reading and writing; place the file pointer at the 'r'

A list of possible modes for fopen() using mode


mod e

Description

'

beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. Open for writing only; place the file pointer at the end of the file. 'a' If the file does not exist, attempt to create it. Open for reading and writing; place the file pointer at the end of 'a+' the file. If the file does not exist, attempt to create it. Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level 'x' E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. Create and open for reading and writing; otherwise it has the 'x+' same behavior as 'x'. Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be 'c' useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested). Open the file for reading and writing; otherwise it has the same 'c+' behavior as 'c'.

Creating and deleting files:


You can create a file by using the fopen function in the appropriate mode. fopen(new.txt,w+) file with the unlink() function.

You can remove an existing unlink() accepts a file path: unlink(file.txt);

file_exists() : If the file is found, file_exists(myfile.txt) returns true; otherwise, it returns false.

is_file() : You can confirm that the entity you're testing is a file, as opposed to a directory, with the, is_file() function. is_file() takes one argument, which is the file path and returns a Boolean value. Example : if (is_file(file.jpg)) { print file.jpg is a file; }

is_dir() : checks for dir Reading lines from a file: To read a line from an open file, you can use fgets(). fgets() requires the file resource returned from fopen() as an argument. You may also pass fgets() an integer as a second argument. The integer argument specifies the number of bytes that the function should read if it doesn't first encounter a line end or the end of the file. o fgets() reads the file until it reaches a newline character ("\n"), the number of bytes specified in the length argument, or the end of the file.

$line = fgets($fp, 1024); feof($fp) : The feof() function does this by returning true when the end of the file has been reached and false otherwise. feof() requires a file resource as its argument.

fgetc Gets character from file pointer Fread reads a specified number of characters from the file fread($fp, 7);

fwrite($fp, string, length) : accepts a file resource and a string, and then writes the string to the file.

$fp :

file handle of the file into which you are writing

String : is the string data to be written to the file length ; optional parameter. Length of data to be written. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first. fwrite() returns the number of bytes written, or FALSE on error.

fputs() works in exactly the same way. alias of fwrite. filesize(filename) : takes filename and NOT the resource handle filetype Gets file type file Reads entire file into an array

array file ( string $filename [, int $flags = 0 [, resource $context ]] ) The optional parameter flags can be one, or more, of the following constants: FILE_USE_INCLUDE_PATH - Search for the file in the include_path. FILE_IGNORE_NEW_LINES - Do not add newline at the end of each array element FILE_SKIP_EMPTY_LINES - Skip empty lines

fileatime Gets last access time of file


fseek Seeks on a file pointer.

int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] ) Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence.

whence values are:

o o

SEEK_SET - Set position equal to offset bytes. SEEK_CUR - Set position to current location plus offset.

SEEK_END - Set position to end-of-file plus offset.

Strings : o strlen() : The strlen() function is used to return the length of a string.
o strpos() : The strpos() function is used to search for a character/text within a string. If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE.
echo strpos("Hello world!","world"); // output is 6

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

The optional offset parameter allows you to specify which character in the string to start searching. strrpos Find the position of the last occurrence of a substring in a string

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

o substr :

string substr ( string $string , int $start [, int $length ] ) Returns the portion of string specified by the start and length parameters.

Start :

If start is negative, the returned string will start at the start'th character from the end ofstring. If string is less than or equal to start characters long, FALSE will be returned.
$rest = substr("abcdef", -1); // returns "f" $rest = substr("abcdef", -2); // returns "ef" $rest = substr("abcdef", -3, 1); // returns "d"

Length :

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, false will be returned. If length is given and is 0, FALSE or NULL an empty string will be returned. If length is omitted, the substring starting from start until the end of the string will be returned. $rest = substr("abcdef", 0, -1); // returns "abcde" $rest = substr("abcdef", 2, -1); // returns "cde" $rest = substr("abcdef", 4, -4); // returns false

trim(string) - This function removes the whitespaces from both start and the end of the string. Length does not change in trim function. It does not remove the spaces in between. Ex : $a = a bc; trim($a); // output is a bc. Only the starting and ending spaces are removed

ltrim(string) : This function removes the whitespaces from the left part of the string.

rtrim(string) : This function removes the whitespaces from the right part of the string. o strtolower(string) - This function converts the string to lower case
o

o
o

strtoupper(string) - This function converts the string to upper case


str_replace str_replace(search, replace, string/array,[count]) search : is the value that is to be searched in the given string. Can be an array as well. replace : the value to be replaced in place of search. Can be an array as well. subject : The string on which the search and replace is to be carried out. If it is an array of strings, search and replace will be done on each element of the array. If subject is an array, then the search and replace is performed
with every entry of subject, and the return value is an array as well. So the original array remains unchanged

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules:

If the string to be searched is an array, it returns an array If the string to be searched is an array, find and replace is performed with every array element If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace If find is an array and replace is a string, the replace string will be used for every find value print_r(str_replace("red","pink",$arr,$i)); echo $i; // output = 1 as only 1 replacement was done o strcmp(string1, string2) : The strcmp() function compares two strings.

Returns 0 if the two strings are equal Negative or <0 if string1 is less than string2 Positive >0 if string1 is greater than string2 The strcmp() function is binary safe and case-sensitive.

For case insensitive comparison you can use strcasecmp(<string1>,<string2>); function. It is similar to strcmp() function.

Datetimefunctions: date(string format) : The following characters are recognized in the format parameter string format Example returned Description character values Day d -----

Day of the month, 2 digits 01 to 31 with leading zeros A textual representation of D Mon through Sun a day, three letters Day of the month without j 1 to 31 leading zeros l (lowercase A full textual representation Sunday through 'L') of the day of the week Saturday ISO-8601 numeric representation of the day of 1 (for Monday) N the week (added in PHP through 7 (for Sunday) 5.1.0) English ordinal suffix for the st, nd, rd or th. Works S day of the month, 2 well with j characters 0 (for Sunday) Numeric representation of w through 6 (for the day of the week Saturday) The day of the year z 0 through 365 (starting from 0) Week -----

ISO-8601 week number of year, weeks starting on Example: 42 (the Monday (added in PHP 42nd week in the year) 4.1.0) Month -----

The following characters are recognized in the format parameter string format Example returned Description character values A full textual representation January through F of a month, such as January December or March Numeric representation of a m 01 through 12 month, with leading zeros A short textual M representation of a month, Jan through Dec three letters Numeric representation of a n month, without leading 1 through 12 zeros Number of days in the t 28 through 31 given month Year L --Whether it's a leap year --1 if it is a leap year, 0 otherwise.

Y y Time a A B

ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs Examples: 1999 or to the previous or next 2003 year, that year is used instead. (added in PHP 5.1.0) A full numeric Examples: 1999 or representation of a year, 4 2003 digits A two digit representation Examples: 99 or 03 of a year --Lowercase Ante meridiem and Post meridiem Uppercase Ante meridiem and Post meridiem Swatch Internet time --am or pm AM or PM 000 through 999

The following characters are recognized in the format parameter string format Example returned Description character values 12-hour format of an hour g 1 through 12 without leading zeros 24-hour format of an hour G 0 through 23 without leading zeros 12-hour format of an hour h 01 through 12 with leading zeros 24-hour format of an hour H 00 through 23 with leading zeros i s u Minutes with leading zeros 00 to 59

Seconds, with leading zeros 00 through 59 Microseconds (added in PHP Example: 654321 5.2.2) --Examples: UTC, GMT, Atlantic/Azores 1 if Daylight Saving Time, 0 otherwise. Example: +0200

Timezone --Timezone identifier (added in PHP 5.1.0) Whether or not the date is I (capital i) in daylight saving time Difference to Greenwich O time (GMT) in hours Difference to Greenwich time (GMT) with colon P between hours and minutes (added in PHP 5.1.3) e T Timezone abbreviation

Example: +02:00 Examples: EST, MDT ...

Timezone offset in seconds. The offset for timezones -43200 through west of UTC is always 50400 negative, and for those east of UTC is always positive.

The following characters are recognized in the format parameter string format Example returned Description character values

Full --Date/Time

---

ISO 8601 date (added in

PHP 5)

2004-0212T15:19:21+00:00

r U

RFC 2822 formatted date Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
o

Example: Thu, 21 Dec 2000 16:01:07 +0200 See also time()

time() : returns the unix timestamp for the current time.


Unix timestamp: The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970. Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch. This is very useful to computer systems for tracking and sorting dated information in dynamic and distributed applications both online and client side

cal_days_in_month(calendar_type, month number, year) : Return the number of days in a month for a given year and calendar cal_info(int calendar_type) : Returns information about a particular calendar o Calendar information is returned as an array containing the elements alname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar_type are as follows: 0 or CAL_GREGORIAN - Gregorian Calendar

1 or CAL_JULIAN - Julian Calendar 2 or CAL_JEWISH - Jewish Calendar 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

Errorhandling:
In php there are three error handling types o Simple "die()" statements o Custom errors and error triggers :

Creating a custom error handler is simple. We simply create a special function that can be called

when an error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context) error_function(error_level,error_message,error_file,error_line,error_context) error_level Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels

error_message Required. Specifies the error message for the user-defined error error_file error_line error_context Optional. Specifies the filename in which the error occurred Optional. Specifies the line number in which the error occurred Optional. Specifies an array containing every variable, and their values, in use when the error occurred

These error report levels are the different types of error the user-defined error handler can be used for:

Value

Constant

Description Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. Run-time warnings (non-fatal errors). Execution of the script is

Note

E_ERROR (integer)

E_WARNING

Value

Constant (integer) not halted.

Description

Note

E_PARSE (integer)

Compile-time parse errors. Parse errors should only be generated by the parser. Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. Fatal errors that occur during PHP's initial startup. This is like an since PHP 4 E_ERROR, except it is generated by the core of PHP. Warnings (non-fatal errors) that occur during PHP's initial startup. since PHP 4 This is like an E_WARNING, except it is generated by the core of PHP. Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Compile-time warnings (non-fatal

E_NOTICE (integer)

16

E_CORE_ERROR

(integer)

32

E_CORE_WARNING

(integer)

64

E_COMPILE_ERROR

(integer)

since PHP 4

128

E_COMPILE_WARNIN errors). This is like an E_WARNING, since PHP 4 G (integer) except it is generated by the Zend

Scripting Engine. User-generated error message. This is like an E_ERROR, except it is since PHP 4 generated in PHP code by using the PHP function trigger_error(). User-generated warning message. This is like an E_WARNING, except since PHP 4 it is generated in PHP code by using the PHP function trigger_error(). User-generated notice message. since PHP 4

256

E_USER_ERROR

(integer)

512

E_USER_WARNING

(integer)

1024

E_USER_NOTICE

Value

Constant (integer)

Description This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error().

Note

2048

E_STRICT (integer)

Enable to have PHP suggest changes to your code which will since PHP 5 ensure the best interoperability and forward compatibility of your code.

4096

Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the E_RECOVERABLE_ER error is not caught by a user ROR (integer) defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.
E_DEPRECATED

since PHP 5.2.0

8192

(integer)

Run-time notices. Enable this to receive warnings about code that will not work in future versions.

since PHP 5.3.0

16384

User-generated warning message. This is like an E_DEPRECATED, E_USER_DEPRECATE since PHP except it is generated in PHP code D (integer) 5.3.0 by using the PHP function trigger_error(). All errors and warnings, as supported, except of level E_STRICT. 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

30719

E_ALL (integer)

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini.

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

Error reporting : The error_reporting() function sets the error_reporting directive at


runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. If the optional level is not set, error_reporting() will just return the current error reporting level.

o o

// Report simple running errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Report all errors except E_NOTICE // This is the default value set in php.ini error_reporting(E_ALL ^ E_NOTICE); E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

o The following error types cannot be handled with a user defined function:

Datetimefunctions: date(string format) : The following characters are recognized in the format parameter string format Example returned Description character values Day d -----

Day of the month, 2 digits 01 to 31 with leading zeros A textual representation of D Mon through Sun a day, three letters Day of the month without j 1 to 31 leading zeros l (lowercase A full textual representation Sunday through 'L') of the day of the week Saturday ISO-8601 numeric representation of the day of 1 (for Monday) N the week (added in PHP through 7 (for Sunday) 5.1.0) English ordinal suffix for the st, nd, rd or th. Works S day of the month, 2 well with j characters

The following characters are recognized in the format parameter string format Example returned Description character values 0 (for Sunday) Numeric representation of w through 6 (for the day of the week Saturday) The day of the year z 0 through 365 (starting from 0) Week -----

ISO-8601 week number of year, weeks starting on Example: 42 (the Monday (added in PHP 42nd week in the year) 4.1.0) Month -----

F m M

n t Year L

A full textual representation January through of a month, such as January December or March Numeric representation of a 01 through 12 month, with leading zeros A short textual representation of a month, Jan through Dec three letters Numeric representation of a month, without leading 1 through 12 zeros Number of days in the 28 through 31 given month --Whether it's a leap year --1 if it is a leap year, 0 otherwise.

ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs Examples: 1999 or to the previous or next 2003 year, that year is used instead. (added in PHP 5.1.0)

The following characters are recognized in the format parameter string format Example returned Description character values A full numeric Examples: 1999 or Y representation of a year, 4 2003 digits A two digit representation y Examples: 99 or 03 of a year Time a A B g G h H i s u --Lowercase Ante meridiem and Post meridiem Uppercase Ante meridiem and Post meridiem Swatch Internet time 12-hour format of an without leading zeros 24-hour format of an without leading zeros 12-hour format of an with leading zeros 24-hour format of an with leading zeros hour hour hour hour --am or pm AM or PM 000 through 999 1 through 12 0 through 23 01 through 12 00 through 23 00 to 59

Minutes with leading zeros

Seconds, with leading zeros 00 through 59 Microseconds (added in PHP Example: 654321 5.2.2) --Examples: UTC, GMT, Atlantic/Azores 1 if Daylight Saving Time, 0 otherwise. Example: +0200 Example: +02:00

Timezone --Timezone identifier (added in PHP 5.1.0) Whether or not the date is I (capital i) in daylight saving time Difference to Greenwich O time (GMT) in hours P Difference to Greenwich time (GMT) with colon between hours and minutes e

The following characters are recognized in the format parameter string format Example returned Description character values (added in PHP 5.1.3) T Timezone abbreviation Examples: EST, MDT ...

Timezone offset in seconds. The offset for timezones -43200 through west of UTC is always 50400 negative, and for those east of UTC is always positive.

Full --Date/Time

---

ISO 8601 date (added in PHP 5)

2004-0212T15:19:21+00:00

r U

RFC 2822 formatted date Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
o

Example: Thu, 21 Dec 2000 16:01:07 +0200 See also time()

time() : returns the unix timestamp for the current time.


Unix timestamp: The unix time stamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970. Therefore, the unix time stamp is merely the number of seconds between a particular date and the Unix Epoch. This is very useful to computer systems for tracking and sorting dated information in dynamic and distributed applications both online and client side

cal_days_in_month(calendar_type, month number, year) : Return the number of days in a month for a given year and calendar cal_info(int calendar_type) : Returns information about a particular calendar o Calendar information is returned as an array containing the elements alname, calsymbol, month, abbrevmonth and maxdaysinmonth. The names of the different calendars which can be used as calendar_type are as follows: 0 or CAL_GREGORIAN - Gregorian Calendar 1 or CAL_JULIAN - Julian Calendar 2 or CAL_JEWISH - Jewish Calendar 3 or CAL_FRENCH - French Revolutionary Calendar

If no calendar is specified information on all supported calendars is returned as an array.

SessionHandling:
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. The http protocol that is used widely over the internet is a stateless protocol, i.e. it does not remember the state of the user. Example : you access your email account using http protocol. When you enter your correct username and pwd, you are taken to your inbox. Now on this page if you click on sent mail, this is a second request. But because of stateless nature of http, the server does not remember who this user is. So there must be a mechanism that associates multiple requests from a single user. session_start() : creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. o This function returns TRUE if a session was successfully started, otherwise FALSE.

$_SESSION : An associative array containing session variables

available to the current script. o This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script.

Cookies:

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is used for an origin website to send state information to a user's browser and for the browser to return the state information to the origin site

The state information can be used for authentication, identification of a user session, user's preferences, shopping cart contents, or anything else that can be accomplished through storing text data. Cookies are not software the three major uses of cookies are : o session management : Cookies may be used to maintain data related to the user during navigation, possibly across multiple visits. the session id can be stored in cookies. o personalisation : Cookies may be used to remember the information about the user who has visited a website in order to show relevant content in the future. Many websites use cookies for personalization based on users' preferences. Users select their preferences by entering them in a web form and submitting the form to the server. The server encodes the preferences in a cookie and sends the cookie back to the browser. This way, every time the user accesses a page, the server is also sent the cookie where the preferences are stored, and can personalize the page according to the user preferences. o tracking : Tracking cookies may be used to track internet users' web browsing habits.

Cookies don't have to be an essential part of a website but can provide some of the "little things" that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client's computer so that you can access them next time they visit the website. Session ID's are also usually held in cookies. so a client browser can disable cookies. Also a website may not be using cookies at all. So its not compulsory to use cookies but this is very rare. to set a cookie : o setcookie(name, value, expire, path, domain) : where only name parameter is mandatory others are optional name : name of cookie value : of cookie

expire : expiry time in secs. after expiry time this cookie will not be avalaible

Database handling :

mysql_connect Open a connection to a MySQL Server o mysql_connect(server,username, password)

all are optional parameters

mysql_select_db Select a MySQL database o Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database. mysql_select_db (string $database_name) : parameter is the name of the databse to be selected. Returns TRUE on success or FALSE on failure.

o
o

mysql_query Send a MySQL query o mysql_query ( string $query)

o o

mysql_query() sends a unique query (multiple queries are not supported)


to the currently active database on the server For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

mysql_result Get result data o o Retrieves the contents of one cell from a MySQL result set. string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )

result : The result resource that is being evaluated. This result comes from a call to mysql_query(). row : The row number from the result that's being retrieved. Row numbers start at 0. field : The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If undefined, the first field is retrieved. If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Regular Expressions in PHP :

A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.

The following table contains the list of some metacharacters and their behavior in the context of regular expressions:

Character

Description Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(". Matches the position at the beginning of the input string. Matches the position at the end of the input string. Matches the preceding subexpression zero or more times. Matches the preceding subexpression one or more times. Matches the preceding subexpression zero or one time. Matches exactly n times, where n is a nonnegative integer. Matches at least n times, n is a nonnegative integer. Matches at least n and at most m times, where m and n are nonnegative integers and n <= m. When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched string as possible, whereas the default greedy pattern matches as much of the searched string as possible. Matches any single character except "\n". Matches either x or y. A character set. Matches any one of the enclosed characters. A negative character set. Matches any character not enclosed. A range of characters. Matches any character in

^ $ * + ? {n} {n,} {n,m}

. x|y [xyz] [^xyz] [a-z]

the specified range. [^a-z] \b \B \d \D \f \n \r \s \S \t \v \w \W \un A negative range characters. Matches any character not in the specified range. Matches a word boundary, that is, the position between a word and a space. Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never". Matches a digit character. Matches a nondigit character. Matches a form-feed character. Matches a newline character. Matches a carriage return character. Matches any whitespace character including space, tab, form-feed, etc. Matches any non-whitespace character. Matches a tab character. Matches a vertical tab character. Matches any word character including underscore. Matches any nonword character. Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol ().

PHP has functions to work on complex string manipulation using RegEx. PHP is an open source language for producing dynamic web pages. PHP has three sets of functions that allow you to work with regular expressions.
o

The most important set of regex functions start with preg. These functions are a PHP wrapper around the PCRE library (Perl-Compatible Regular Expressions).

The oldest set of regex functions are those that start with ereg. They implement POSIX Extended Regular Expressions, like the traditional UNIX egrep command. The last set is a variant of the ereg set, prefixing mb_ for "multibyte" to the function names. While ereg treats the regex and subject string as a series of 8-bit characters, mb_ereg can work with multi-byte characters from various code pages

We are going to see the POSIX extended regex. The following are the RegEx

functions provided in PHP.


ereg : Regular expression match.
o o int ereg (string $pattern , string $string [, array &$regs ]) Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

ereg_replace :

o o o

Replace regular expression This function scans string for matches to pattern, then replaces the matched text with replacement. string ereg_replace ( string $pattern , string $replacement , string $string ) $pattern : A POSIX extended regular expression.
$replacement : If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will

be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.
$string : The input string.

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Вам также может понравиться