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

Sunday, May 27, 2007

PHP Basics

PHP Variables

Using Php Variables
Php Variables are are used for storing values, such as strings, numbers। Once stored they can be called from anywhere within the script।

Note :Variables can not have spaces and only contain alpha-numeric characters and underscores. $myVar or $my_Var both is correct.

PHP Switch Statement

Php Switch statement is very useful, it works like if/else statement & reduce the complication of numerous conditions in the script.

Syntax :

switch (expression)
{
case 1
code .. //execute code if expression = 1
break;
case 2
code … //execute code if expression = 2
break;
default:
code…//execute code if expression not matched
}

Example :

$value = 6;

switch ($value)

{

case 1:

echo “Value 1″;

break;

case 2:

echo “Value 2″;

break;

case 3:

echo “Value 3″;

break;

default:

echo “Value is ” . $value . ” not matched!”;

}

?>


The while Statement

The while statement is useful, when you want to loop a code until it’s conditions are met.

Syntax : 

while (condition)
code ….


Example :

“);}
echo “Value is “. $val .”. condition not met!
“;
$val++;
}
?>
Output of this code is :
Value is 0. condition not met!

Value is 1. condition not met!
Value is 2. condition not met!
Value is 3. condition not met!
Value is 4. condition not met!
Value is 5. condition not met!
Value is 6. condition not met!
Value is 7. condition not met!
Value is 8. condition not met!
Value is 9. condition not met!
Value is 10. condition met!
Above code loops until the value is 10.


The do while Statement

The do/While repeat through the code, until the condition is met.

Syntax :
do { code … } while (condition);
Example :
“; } while ($val<3);>
Output of this code : Value is 1 Value is 2 Value is 3

PHP For Statement

PHP For statement is used when you want to loop the code for number of times,
until condition is met.

Syntax :

for (initialization; condition; increment)
{
code …
}


Example :

”;

}

?>
Output of this Php code is :
This is the text.
This is the text.
This is the text.


PHP Functions

PHP functions re very useful, because once coded, it can be called from anywhere within the script or from outside. Note, code block must start with function word.

Example 1 : Shows how to call function within the php Script.

function MyFirstEchoFunction()

{

echo “Hi this is the function called!
”;

echo “And this is text created by function!”;

}

MyFirstEchoFunction()

?>

Another way of calling functions is using include()..
Php Include() lets you import any php or text file in your script.

Example 2 : Create a php file somthing like “test.php” and write this code:

test.php code :

function MyFirstEchoFunction()

{

echo “Hi this is the function called!
”;

echo “And this is text created by function!”;

}
MyFirstEchoFunction()

?>

Now create destination file, something like “call.php”

Call.php code :

include(”test.php”); //This is the target php file
MyFirstEchoFunction() //We just called the function coded in test.php

?>

Isn’t this nice? The output of this file is :
Hi this is the function called!
And this is text created by function!



PHP Objects

Purpose PHP Equivalent
Writing HTML
print $str;
echo $str;
print_r $debug_str;
Form, Cookie and QueryString variables. These variables are available automatically as global variables if you have configured the following in PHP.ini:
variables_order="EGPCS"
register_globals=On

For security, I would recommend disabling register_globals (set it to OFF). Then the variables are only available in the arrays:
$_POST, $_COOKIE and $_GET.

See examples below.

Redirecting to another location Header(”Location: $url”);
Cookie Handling
setcookie($cookiename, $newval);
$avar = $_COOKIE[$cookiename];
Application Variables Not available. Can be simulated with a database.
Session Variables In PHP4 or later, we mark certain variables as session variables using session_register($sessionname), and we call session_start( ) at the beginning of the .php page to restore the session variable values.Note that we pass the name of the variable, and not the variable itself into session_register( ).
session_register('avar');
$avar = 99;
session_start();
/* 99 in $avar is overwritten now */
print $avar;
Form Variables $_POST[”formvar”];
$_GET[”getvar”];Alternately, GET and POST vars can be converted automatically to PHP variables. However this is a security risk if hackers are aware of the variable names used in your code.
Server Variables For ISAPI modules, the server varibles are stored in the $_SERVER array. For CGI, they are stored as environment variables, available from the $_ENV array or getenv( ). An example:$_SERVER[”HTTP_HOST”] using ISAPI module

$_ENV[”HTTP_HOST”] using CGI module

See PHP, FastCGI and IIS for a more detailed discussion of high performance PHP on IIS.

Database Access ADO can be simulated using the ADOdb database library. This PHP library emulates ADO, and is designed by the author of this article.Limitations: only supports forward scrolling read-only cursors.
Buffering
ob_start();
print "abc";
ob_end_flush();

Function and Class Syntax

PHP
Function Example
function inc($val)
{ return $val + 1;}

Procedures are functions that return no value.

Class Example
class parent {
var property;
function parent() { }
function method() { }
}

/* inheritance */
class child extends parent {
var property='new value';
}
Scope of Variables Variables defined outside a function or class are available globally; variables defined in a class or function are available locally.Unlike other languages, you must declare a global variable in a function or class before you use the variable, using the keyword global.
$globalvar = 1;
function show_global( )
{
global $globalvar;
print $globalvar;
}
Call by Reference Use & keyword in function parameters.
Default Parameters Yes.function A(param1=”abc”)
Returning by Reference By default, return is by value. For objects and arrays, we want to return by reference for superior performance. Use
function &amp; getarray123() {
$val = array(1,2,3);
return $val;
}

Then in the calling code, use

 $val = &getarray123();

PHP Language Summary

This is a summary of the PHP language.

Some nice things i found about PHP:

* No need to purchase additional ActiveX controls for email, gif manipulation, pdf handling, etc. Batteries included.
* Runs well on both IIS and Apache, Windows and Linux. Cross-platform power.
* Good performance. PHP is faster than VBScript and JScript, based on the Bagley benchmarks.
* Even if you are a VB programmer, provided you have some Javascript experience, you are already half-way up the learning curve, as PHP looks like Javascript with $ signs in front of variables.
* For those of you who miss ADO (i did), there’s ADOdb, a database abstraction library that works like ADO. And ASP2PHP is an automated VB to PHP converter.
* I recommend this PHP installer for IIS (ok, ok, I admit wrote it). The default PHP installer at php.net is not tuned for high performance IIS usage - this one is.


Feature PHP
Example (print 1 to 10 on a web page)


for ($i=1; $i<=10; $i++) print “$i ”;

?>

Script Tags
If short tags are enabled in PHP.ini:
If ASP tags are enabled in PHP.ini:
<% %><%= return expression %>
End of statement semicolon (;) is compulsory
Comments
// PHP comment 1
/* This is a

multi-line

Comment */
# PHP comment 3
Variables Prefixed by $
Need to declare variables? No, and every variable is preinitialised to type NULL, which is equivalent to false, the empty string and 0.$AVAR = 123;
Loosely Typed Variables Yes. This means that the type of a variable can be changed at run-time.
To change variable type, use typecasting or settype( )
Case-Sensitivity Yes for variables, no for function-names and reserved words
Strings Delimited by single-quotes, double-quotes or PERL heredoc style.
$avar = 'this is a string';

$avar = "this is a string";

$avar = <<
String Concatenation The . (dot) symbol.$s = ‘A’ . ‘B’;
String Evaluation Yes, variables embedded in strings are evaluated if string delimited by double-quotes.$a = “A”;
$b = “$a B”;
/* now $b == ‘A B’ */
Common string constants Line feed: “\n”
Carriage return: “\r”Note that single-quoted ‘n’ is not converted to a line-feed for PHP. Only double-quoted strings are evaluated.
HTML encoding functions htmlspecialchars($str) Converts < > & and ” to their HTML entity equivalents, eg. <>urlencode( ) All punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding. Spaces converted to +.urldecode( )All punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding. Spaces converted to +.
Regular Expressions Built-in.if (preg_match (”/php/i”, $str))
print (”php found”);
Dates
$adate = time();

$adate=mktime(0,0,0,1,30,2000);print date('d-m-Y',$adate);
Arrays Declare with
$avar = array(1,’two’);For indexing use [ ]. Arrays begin with zero element.Use sizeof(array) function to get size of array.Arrays can be iterated over using:
$val = reset($arr);

$max = sizeof($arr);

for ($i=0; $i<$max; $i++) { print "$val "; $val = next($arr); }/* or more simply */ foreach ($arr as $element) print "$element ";
Associative Arrays Yes
$avar = array();

$avar['newton']='isaac';

echo $avar['newton'];

Note: You can append new elements to arrays with
$avar[] = ’string to add’;

True and False Has constants true and false.The following also evaluate to false:
0   /* zero */

"" /* empty string */

"0" /* string with zero */
Equality
== true if equal

!= not equal=== true if equal & same type

!== not identical

Note that some functions can return 0 or false (false is typically used to indicate failure) depending on the context. For these functions, you will need to use === to determine whether 0 or false was returned. Some problematic functions: strpos, strrpos, strstr, stristr, strrchr

Assignment statements Allows C style shortcut assignments. For example, to append a string to a variable:$avar .= ‘append to end’;
Sending HTML to Browser print $avar;
echo “The avar variable ‘$avar’ is a string”;
If statements
if (strlen($avar) == 0) {

$avar = "abc";

} else

$avar .= 'end';
While statements
while ($a > 0) {$a -= 1;}
For loops
for ($i=0,$m=9; $i<$m; $i++){  print $i;  }
Switch/Case
switch($aColor) {

case 'red': do1;break;

case 'green': do2;break;

default: do3; break;

}