Ethical Hacking Programming, Blogging, Hosting, All Computer Software, PC Software Download, JAVA in hindi, HTML, PHP, C, C++, Free Learning, Software's Download, Technical Videos, Technical Tricks and Tips, How Make Money

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Learn PHP Full Programming Course Free In English PDF Book free


Contents

Preface
.
.
.
.
.
.
.
5
Miscellaneous Things You Should Know
.
.
.
9
Operators
.
.
.
.
.
.
.
19
Control Structures
.
.
.
.
.
.
25
Global Variables
.
.
.
.
.
.
33
Variable Functions   .
.
.
.
.
.
35
String Functions
.
.
.
.
.
.
41
Array Functions
.
.
.
.
.
.
71
Date/Time Functions .
.
.
.
.
.
103
Mathematical Functions
.
.
.
.
.
111
MySQL Functions
.
.
.
.
.
.
115
Directory & File System Functions   .
.
.
.
127
Output Control (Output Buffer)
.
.
.
.
139
Sessions
.
.
.
.
.
.
.
145
Regular Expressions  .
.
.
.
.
.
149

Common Language Index
.
.
.
.
.
159
Function Index .
.
.
.
.
.
.
161


 Download Link Here



Share:

Learn Php free in english

PHP Reference: Beginner to Intermediate PHP chapter 2 Class 3.



FOR


for (expr1; expr2; expr3) {
// If expr2 is TRUE, do this
}

When started, the for loop executes expr1 once at the beginning. Next, expr2 is evaluated. If expr2 is true, the code inside the for loop is executed. When the for loop reaches the end, expr3 is executed before looping and checking expr2 again.

Example:

for ($x = 1; $x <= 5; $x++){

echo $x;
}


See Also:

break – Stops the for loop and exits it immediately

continue – Stops the current iteration of the for loop, and expr3 is executed before checking expr2 again


Alternative syntax for a for statement:

for (expr1; expr2; expr3):

// If expr2 is TRUE, do this endfor;

An example of continue and break in a for loop:

for ($v=0;$v<=10;$v++){

echo $v;
if ($v == 5){
continue;
}
if ($v == 8){

break;
}

echo ',';
}

0,1,2,3,4,56,7,8




foreach

foreach ($array as $value){
// Do something

}

// Another form, for keys and values foreach ($array as $key => $value){

// Do something

}

The foreach loop goes through all items in an array, assigning a temporary variable name for value and, if chosen, the key as well so they can be used within the executed code inside the loop.

Examples:

$array = array('John' => 20, 'Jane' => 24, 'Joseph' => 28); foreach ($array as $value){

echo "$value, ";
}


20, 24, 28,

foreach ($array as $name => $age){

echo "$name - $age";
echo '<br />'; // XHTML for a line break
}


John - 20
Jane - 24
Joseph - 28

See Also:

Pass by Reference – Using the ampersand ( & ) to alter an array through foreach



break [$integer]

$integer – [optional] Specifies the number of nested loops to break out of

Exits and stops execution of the current (default) for, foreach, while, do-while, or switch loop.

Example:

$counter = 0;
while (1 == 1){ // Will run forever
while (0 == 0){ // Will also run forever
$counter++; // Increment $counter plus 1
echo $counter;

if ($counter == 5){
break 2;

}
}

echo 'First while loop'; // Never displayed because of break 2; break; // Never run, but if it did, would end the first while loop
}

continue [$integer]

$integer – [optional] Specifies the number of nested loops to skip out of Note: The $integer does not supply the number of iterations to skip, it always only stops the current iteration from continuing any further.

Skips the rest of the current loop iteration and if applicable, continues to the next iteration of the loop3.

Example:

for ($x=1;$x<=10;$x++){
if ($x == 5){
continue;

} // The echo never occurs if $x == 5 echo $x;

}



return [$variable]

$variable – [optional] The variable to be returned from a function

If used as part of a regular script and not part of a function, it works the same as exit() or die(). Return is more commonly used as part of a function to assign a value to the results of a function back at the original function call.

See Also:

Functions – Provides an example of returning a $variable as part of a function

exit() – Terminate the current script immediately

include(file)

file - $string

Include and evaluate the file as part of the current script/page. This is an easy way to store common variables, functions4, or lines of HTML that will be included by multiple scripts/pages. Failure of the function generates an error.

Example:

include('somefile.inc');


In the case of a switch, continue has the same effect as break

Functions should only be included once. Consider using include_once() or require_once()

include_once(file)


require_once(file)

file - $string

Include and evaluate the file as part of the current script/page. If the file has already been included, it will ignore the request. This is an easy way to store common variables, functions or lines of HTML that will be included by several scripts / pages.

Failure of the function generates an error and terminates the script immediately.

Example:

require_once('somefile.php');



 Functions should only be included once. Consider using require_once()


Share:

Learn php language Control Structures

PHP Reference: Beginner to Intermediate PHP chapter 2 Class 2. 


Control Structures


The heart of PHP is the control structures. Variables and arrays are lonely without them as they facilitate comparisons, loops, and large hands telling you to go that way and do it this way. Okay, I made that last part up. Here we go!



If, ElseIf, Else

if (expr) {

// If expr is TRUE, do this, then exit the IF loop }elseif (expr2) {

// If expr is FALSE, and expr2 is TRUE, do this, then exit the loop }else{

// If all expr's are FALSE, do this, then exit
}

There can be only one instance of else in an if statement, but multiple elseif expressions are allowed prior to the else statement.

Example:

$x = 1;

if ($x < 1){
echo '$x is less than 1';

}elseif ($x == 1){ // Note the double equals, for comparison echo '$x is equal to 1';
}else{

echo '$x is neither equal to 1 or less than 1';
}


$x is equal to 1

See Also:

switch – A simpler, more organized usage than multiple if/elseIf combinations

break – Stops a loop and exits regardless of if the statement evaluates as true

Alternative syntax for an if statement:

if (expr):

// If expr is TRUE, do this, then exit the IF loop elseif (expr2):
// If expr is FALSE, and expr2 is TRUE, do this, then exit the

loop else:

// If all expr's are FALSE, do this, then exit
endif;




Switch

switch (expr) {
case value:

// Do this if value matches break;
case value2:

// Do this if value2 matches break;

default: // [optional]

// Do this if no other cases match. Does not have to be at the end break;
}

expr – A $string, $integer, or $float to be compared against

A switch evaluates the expr against any number of cases or options, specifying the behavior for each case.

Cases can be 'stacked' to allow the same portion of code to be evaluated for different cases:

switch (expr) {
case value:
case value2:
// Do this if value or value2 matches
}

The switch is evaluated line-by-line, and therefore if there was no break command, the case declaration would effectively be ignored and the code would continue to be processed until the switch ends or a break; is reached.

$x = 1;

switch ($x) {
case 1:

echo '1'; // Note the lack of a break; case 2:

echo '2'; // Without the break, this is processed line-by-line
}


Finally, the default statement is optional, but defines what to do if no cases are matched. It can be used in troubleshooting to identify when you failed to include a case for an expected output.

Examples:

$x = 2;
switch ($x) {
case 1:
echo '1';
break;

case 2:
echo '2';

break;
case 3:
echo '3';
break;
}



$x = 'howdy';

switch ($x) {
case 'hi':

echo 'Hi there';
break;

default: // Can be anywhere, all cases evaluated before it is used echo 'Greetings';
break;

case 'hello':
echo 'Hello there';

break;
}


Greetings

See Also:

break – Stops a loop and exits regardless of if the statement evaluates as true


Alternative syntax for a switch statement:

switch (expr):
case value:

// Do this if value matches break;

case value2:

// Do this if value2 matches break;

default: // [optional]

// Do this if no other cases match. Does not have to be at the end break;
endswitch;




while

while (expr) {

// If expr is TRUE, do this, then evaluate expr again
}


The while loop checks the expr and if it evaluates as true, the script runs through the entire contents of the while until it finishes, then it evaluates the expr again and repeats until the expr evaluates as false.

Example:

$x = 1;
while ($x <= 3){

echo "$x, ";
$x++; // increments $x by adding 1. Short-hand version
}


1, 2, 3,

See Also:

do-while – Same as while, except the expr is evaluated after the first action break – Stops a loop and exits regardless of a TRUE statement evaluation continue – Stops the iteration of the loop, and the expr is evaluated again


Alternative syntax for a while statement:

while (expr):

// If expr is TRUE, do this, then evaluate expr again endwhile;




do-while

do {

// Do this
} while (expr);

The do-while loop performs whatever is inside the do statement, checks the expr, then if it evaluates as TRUE, runs through the entire contents of the do until it finishes, evaluating the expr again, and repeating until the expr evaluates as FALSE.

Example:

$x = 1;
do {

echo "$x, ";
$x++; // Makes $x = 2, therefore the while will evaluate as false

} while ($x <= 1); 1,


See Also:

while – Similar to do-while, except the expr is evaluated first

break – Stops a loop and exits regardless of if the statement evaluates as true continue – Stops the iteration of the loop, and the expr is evaluated again

Share:

PHP Reference: Beginner to Intermediate PHP chapter 2 Class 1

Operators

When comparing or processing variables and other values you use operators. Without them, PHP would be more of a word jumble instead of a language. In some unique cases, operators slightly alter the relationship between two variables or their function within PHP. Without further adieu, here they are.



Basic Operators

Add ( + ): $a = 1; $a = $a + 5; // $a is equal to 6

Subtract ( - ): $s = 10; $s = $s - 5; // $s is equal to 5
Multiply ( * ): $m = 2; $m = $m * 10; // $m is equal to 20

Divide ( / ): $d = 20; $d = $d / 5; // $d is equal to 4
Modulus ( % ) Provides the remainder after division:

$u = 5; $u = $u % 2; // $u is equal to 1



Assignment Operators

Add ( += ): $a = 1; $a += 5; // $a is equal to 6

Subtract ( -= ): $s = 10; $s -= 5; // $s is equal to 5
Multiply ( *= ): $m = 2; $m *= 10; // $m is equal to 20

Divide ( /= ): $d = 20; $d /= 5; // $d is equal to 4
Modulus ( %= ) Provides the remainder after division:

$u = 5; $u %= 2; // $u is equal to 1

Concatenate ( .= ) Join onto the end of a string:
$c = 5; $c .= 2; // $c is now a string, '52'

See Also:

Concatenate – Join together in succession


Comparison Operators
Greater Than ( > ): 2 > 1
Less Than ( < ): 1 < 2
Greater Than or Equal To ( >= ): 2 >= 2 3 >= 2
Less Than or Equal To ( <= ): 2 <= 2 2 <= 3

Short-Hand Plus or Minus one

Also known as:
Increment ( $integer++; )

Decrement ( $integer--; )

Example:

$a = 1;

$a = $a + 1; // $a is now equal to 2 $a++; // $a is now equal to 3
$a--; // $a is now equal to 2 again, same as $a = $a – 1;



@ - Suppress Errors

Placing the commercial at symbol (@) before a function tells PHP to suppress any errors generated by that function.

Examples:

include('DoesNotExist.txt');

Warning: include(DoesNotExist.txt) [function.include]: failed to open
stream: No such file or directory

@include('DoesNotExist.txt');

// blank output below because the error was suppressed





& - Pass by Reference

References allow two variables to refer to the same content. In other words, a variable points to its content (rather than becoming that content). To pass from context, two variables allow to indicate the same content under different names. Apersander (&) is placed in front of the referencing variable.
Examples:

$a = 1;
$b = &$a; // $b references the same value as $a, currently 1

$b = $b + 1; // 1 is added to $b, which effects $a the same way echo "b is equal to $b, and a is equal to $a";

b is equal to 2, and a is equal to 2





Use this for functions when you want to change only the original variable and want to re-double it with your new value again in the same variable name.

function add(&$var){ // The & is before the argument $var $var++;
}

$a = 1;
$b = 10;

add($a);
echo "a is $a,";
add($b);
echo " a is $a, and b is $b"; // Note: $a and $b are NOT referenced

a is 2, a is 2, and b is 11

You can also do this to alter an array with foreach:

$array = array(1,2,3,4);

foreach ($array as &$value){
$value = $value + 10;
}

unset ($value); // Must be included, $value remains after foreach loop print_r($array);

Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 )



Ternary Operator

The Ternary Operator is a short-hand form for evaluating what to do when an expression is evaluated as either TRUE or FALSE. The conditional returns either the TRUE or FALSE output. Basic format is as follows:

(expr) ? ValueIfTrue : ValueIfFalse ;

Examples:

$boolean = TRUE;

$result = ($boolean) ? 'Is True' : 'Is False'; echo $result;

Is True

// $result is not yet set

$result = (isset($result)) ? $result+1 : 10; echo " \$result = $result.";

$result = (isset($result)) ? $result+1 : 10; echo " \$result = $result.";


$result = 10. $result = 11.

The Equal Sign

Assignment ( = ): Assigns the value on the right to the variable on the left
Equality ( == ): Checks if the left and right values are equal

Identical ( === ): Checks if the left and right values are equal AND identical


Example:

$a = 1; // Sets the value of $a as 1 by assignment

$b = TRUE; // Sets the value of $b to the boolean TRUE if ($a == $b){
echo 'a is equal to b.';

}
if ($a === $b){

echo 'a is identical and equal to b.';
}


a is equal to b.



Not ( ! ), Not Equal to ( != ), Not Identical to ( !== )

Used in conditional statements to evaluate as true a FALSE result of an expression or if a value is NOT equal to the second value.

Example:

$a = 1;

if (!isset($a)){ // If the variable $a is NOT set then...

echo '$a is not set'; // The expression is TRUE if it is NOT set // Since there is no ELSE statement, nothing is displayed
}
if ($a != 0){

echo '$a does not equal zero';
}


$a does not equal zero

See The Equal Sign above for equality versus identical



Concatenate (The Period)

A period is used to join dissimilar items as part of a string in the same order as they are listed. In many cases this is used to reference the value of a function or of an array, which cannot be referenced within double quotations ( "" ) when being assigned to a $string variable.

Example:

$array = array( 1 => 'Hello' );
$string = 'World';

echo '$string in single quotes, followed by ' . $array[1] . "$string";


$string in single quotes, followed by HelloWorld


Comparison Operators (non-arithmetic)

and ( && )
or ( || )

xor ( xor ) - Or, but not All


Examples:

if (1 == 1 && 2 == 2){

echo 'And is True';
}


And is True

if (1 == 1 || 2 == 2){

echo 'At least one of these is True';
}


At least one of these is True

if (1 == 1 xor 2 == 10){

echo 'One of these is True, but not both';
}


One of these is True, but not both

Share:

PHP Reference: Beginner to Intermediate PHP chapter 1 Class 2

PHP Reference: Beginner to Intermediate PHP5

If multiple pages will see the same functions, then make a different one

functions.php file (name it whatever you like) and require() or
require_once() with pages that will need to use those functions. For speed

and file size, page specific functions should be included directly on the
necessary page.


exit([$string])

die([$string])

Stops the current script and outputs the optional $string.

Example:

$result = @mysql_connect('db', 'user', 'pw')

or die('Unable to connect to database!'); echo 'If it fails, this will never be seen';


Unable to connect to database!

Note: The above output would only display if it failed. If the @ was not present before mysql_connect(), PHP would output a warning as well.



eval($string)

Evaluates a string as if it was code. This can be used to store code in a database and have it processed dynamically by PHP as if it were part of the page. All appropriate aspects of code must be included, such as escaping items with a backslash (\) and including a semicolon (;) at the end of the string.

Example:

$name = 'Mario';

$string = 'My name is $name.'; // Note the single quotes echo $string;

$code = "\$evalstring = \" $string \" ;";

// Effect of backslash escape: $code = "$evalstring = " $string " ;"; eval($code); // eval($evalstring = " My name is $name " ;);

// $evalstring is the same as $string, except with double quotes now echo $evalstring;


My name is $name. My name is Mario.



sleep($integer)

Pauses PHP for $integer amount of seconds before continuing.

Example:

sleep(2); // pause for 2 seconds

usleep($integer)Pauses PHP for $integer amount of microseconds before continuing.

Example:

usleep(1000000); // pause for 1 second





uniqid([$scalar [, entropy]])

entropy – [optional] $boolean default: FALSE, 13 character output

Generate a unique ID based on the $scalar. If no input is given, the current time in microseconds is used automatically. This is best used in combination with other functions to generate a more unique value. If the $scalar is an empty string ('') and entropy is set to TRUE, a 26 character output is provided instead of a 13 character output.

Examples:

$id = uniqid();
echo $id;


47cc82c917c99

$random_id = uniqid(mt_rand());
echo $random_id;


63957259147cc82c917cdb

$md5 = md5($random_id);

echo $md5;


ea573adcdf20215bb391b82c2df3851f

See Also:

md5() – MD5 algorithm based encryption



setcookie(name [, value] [, time] [, path] [, domain] [, secure] [, httponly])

name – $string
value – [optional] $string

time – [optional] $integer default: till the end of the session
path – [optional] $string default: current directory

domain – [optional] $string default: current domain (e.g.
http://www.example.com)

secure – [optional] $boolean default: FALSE, does not require a secure connection

httponly – [optional] $boolean default: FALSE, available to scripting languages

PHP Reference: Beginner to Intermediate PHP5

Sets a cookie2, visible to the server on the next page load. To send then default value, use a set of single quotes ('') for each argument you want to skip except the time argument, which should use 0 to send the default value. In most cases, providing the name, value, time, and domain will cover most uses (with '' for path).

Examples:

setcookie('Cookie','Set till end of this session',0);

// This will display properly after the page has been reloaded print_r($_COOKIE);


Array ( [Cookie] => Set till end of this session )

setcookie('Cookie','Set for 60 seconds for all subdomains of example.com, such as www., mail., etc.',time()+60,'','.example.com'); print_r($_COOKIE);


Array ( [Cookie] => Set for 60 seconds for all subdomains of example.com, such as www., mail., etc. )

Some common times used for expiration: time()+60*60*24 is equal to 1 day time()+60*60*24*30 is equal to 30 days

time()-1 is one second in the past, used to expire/delete a cookie
setcookie('Cookie','',time()-1);

// expires the Cookie named 'Cookie'. Note the empty string for value



urlencode($string)

Changes the formatting of $string to the proper format for passing through a URL, such as part of a GET query, returning the new string.

Example:

$string = 'Hello There! How are you?'; echo urlencode($string);


Hello+There%21+How+are+you%3F



urldecode($string)

Changes the formatting of $string from the URL compatible (such as a GET query) format to human readable format, returning the new string.

Example:

$string = 'Hello+There%21+How+are+you%3F'; echo urldecode($string);


Hello There! How are you?



Must be sent prior to any headers or anything else is sent to the page (including the <html> tag). See ob_start() for an easy way to make this work

get_magic_quotes_gpc()

Returns 0 if it is off, 1 otherwise.

Used to determine if magic quotes is on. This check is used for code portability and determining if the addition of backslashes is necessary for security purposes and preventing SQL injection. Magic_quotes_gpc processes GET/POST/Cookie data and, if turned on, automatically processes the above data every time with addslashes().

Example:

if (get_magic_quotes_gpc()){

echo 'Magic Quotes is on!';
}else{

echo 'Magic Quotes is NOT on, use addslashes()!';
}


// This is the default setting for PHP5 installations Magic Quotes is NOT on, use addslashes()!

See Also:

addslashes() – Add backslashes to certain special characters in a string stripslashes() – Remove backslashes from certain special characters in a string



phpinfo([option])

option – [optional] Used with a specific $integer or $string to display only a portion of phpinfo(). Specific options excluded for simplicity.

By default, phpinfo() will display everything about the PHP installation, including the modules, version, variables, etc.

Example:

phpinfo();



Display All PHP Errors and Warnings

To catch programming errors, mistakes, or make sure that PHP is not making any assumptions about your code, troubleshooting is best done with all PHP errors being displayed. The following two lines of code will enable this mode:

error_reporting(E_ALL);
ini_set('display_errors', '1');

mail(to, subject, message [, headers] [, parameters])

to – $string
subject – $string

message – $string
headers – [optional] $string

parameters – [optional] $string

This uses the sendmail binary which may not be configured or available


Example:

$to = 'johndoe@example.com';

$subject = 'Hello';
$message = 'Hi John Doe';
$headers = 'From: janedoe@example.com' . "\r\n" .
'Reply-To: janedoe@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);



exec(command [, output] [, return])

command – $string to execute the external program

output – [optional] Variable name to assign all the output of the command as an array

return – [optional] Variable name to assign the return status as an $integer.
Works only when output is also present.

The function will return the last line of the executed program's output. If the program fails to run and both output and return are both present, return will be most commonly set to 0 when successfully executed and 127 when the command fails.

Example (Linux specific program):

$lastline = exec('cal', $output, $return);
echo '<pre>'; // For better formatting of print_r()

print_r($output);
var_dump($lastline, $return);


Array

(
[0] => March 2008
[1] => Su Mo Tu We Th Fr Sa
[2] => 1
[3] =>  2 3  4  5  6  7  8

[4] =>  9 10 11 12 13 14 15
[5] => 16 17 18 19 20 21 22
[6] => 23 24 25 26 27 28 29
[7] => 30 31
)
string(5) "30 31"
int(0)



header($string [, replace_flag] [, http_response_code])

replace_flag – [optional] $boolean default: TRUE, replace similar header http_response_code – [optional] $integer

Sends an HTTP header specified as $string.

Note: Header() must be used prior to any other output is sent to the user/browser.
Use ob_start() to workaround this.

Examples:

header('Location: http://www.someotherplace.com');


// Redirects the user to the provided URL header('HTTP/1.0 404 Not Found');

// Sends the HTTP status code 404


See Also:

ob_start() – Start the output buffer



Classes & Object Oriented PHP

While this is outside of the scope of this book, I have included a few notes here on basic usage to extend the flexibility of this book.

Class Structure: ( brackets[] delineate optional syntax )

class class_name [extends base_class]{

var variable_name; // Defines a variable function function_name([arguments]) {

// Stuff to do goes here
}
}

Refer to the containing class – use the reserved variable $this

Declare a class: $variable = new class_name();

Creating an object: $variable->function_name();

Static call to an object: class_name::function_name();

Share:

Follow On YouTube