Wednesday, February 22, 2012

PHP


Apache is a web server
Web server (or HTTP server) delivers web pages on the request to clients. This means delivery of HTML documents and any additional content that may be included by a document, such as images, style sheets and JavaScripts.
A client (web browser) initiates communication by making a request for a specific resource using HTTP and the server  responds with the content of that resource or an error message if unable to do so.
HTTP (Hypertext Transfer Protocol)
HTTP functions as a request-response protocol in the client-server computing model.
HTML  HyperText Markup Language
Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT)
hello.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html><head><title>Example</title></head><body>
<?php echo "Hi, I'm a PHP script!";?>
</body></html>
-----------------------------
<?php phpinfo(); ?>
-----------------------------
<?php echo $_SERVER['HTTP_USER_AGENT']; ?>
-----------------------------
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
echo 'You are using Internet Explorer.<br/>';
}?>
form.html
<form action="action.php" method="post">
<p>Your name: <input type="text" name="name" /></p>
<p>Your age:  <input type="text" name="age" /></p>
<p>           <input type="submit" />  </p>
</form>
action.php
Hi 
<?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
--------------------------
// This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
# This is a one-line shell-style comment
--------------------------
$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer

echo gettype($a_bool);//boolean
echo gettype($a_str);//string
if (is_int($an_int))  $an_int += 4;
if (is_string($a_bool)) echo "String: $a_bool";
--------------------------
if ($action == "show_version")  
  echo "The version is 1.23";
if ($show_separators) echo "<hr>\n";
--------------------------
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
 --------------------------
$a = 1.234;    $b = 1.2e3;    $c = 7E-10;
--------------------------
echo 'string';
echo 'string 
with newlines ';
// Outputs: Arnold once said: "I'll be back"
echo '  Arnold once said: "I\'ll be back"  ';
echo ' \\ ';  // \
// Outputs: You deleted C:\*.*?
echo ' You deleted C:\*.*? ';
// Outputs: This will not expand: \n a newline
echo ' This will not expand: \n a newline ';
// Outputs: Variables do not $expand $either
echo ' Variables do not $expand $either ';
--------------------------
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo { var $foo;   var $bar;
    function foo(){ $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3'); } }

$foo = new foo();   $name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
--------------------------
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12];    // 1
--------------------------
class foo { function do_foo() {echo "Doing foo.";} }
$bar = new foo;   $bar->do_foo();
--------------------------
$foo = 'Bob';// Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;  echo $foo;    // $foo is altered too.
--------------------------
$a = 1;   $b = 2;
function Sum(){  global $a, $b;   $b = $a + $b;  
Sum();   echo $b;
--------------------------
$a = 1;  $b = 2;
function Sum(){ 
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];} 
Sum();  echo $b;
--------------------------
var_dump($a);  //Dumps information about a variable
--------------------------
print_r ($a); //Prints human-readable information about a variable
--------------------------
$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
echo $arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
--------------------------
// This array is the same as ...
array(5 => 43, 32, 56, "b" => 12);
// ...this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
--------------------------
$arr = array(5 => 1, 12 => 2);
$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script
$arr["x"] = 42; // This adds a new element to
                // the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr);    // This deletes the whole array
--------------------------
$array = array(1, 2, 3, 4, 5);// Create a simple array.
// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) { unset($array[$i]);}
// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
$array = array_values($array);// Re-index:
$array[] = 7;
--------------------------
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/
$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
--------------------------
$obj = (object) 'ciao';
echo $obj->scalar;  // outputs 'ciao'
--------------------------
$var = NULL;
--------------------------
$a =  'car'; // $a is a string
$a[0] = 'b';  // $a is still a string
echo $a;   // bar
--------------------------
$a = 1;   include 'b.inc'; //$a variable will be available within the included b.inc script
--------------------------
static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope
function test() {  static $a = 0;  echo $a;  $a++;  }
-----------------------------
$a = 'hello';
$$a = 'world'; // $hello = 'world';
-----------------------------
<form action="foo.php" method="post">
Name: <input type="text" name="username" /><br />
Email: <input type="text" name="email" /><br />
<input type="submit" name="submit" value="Submit me!" />
</form>
<?php 
// Available since PHP 4.1.0
echo $_POST['username'];
echo $_REQUEST['username'];
import_request_variables('p', 'p_');
echo $p_username;
// As of PHP 5.0.0, these long predefined variables can be disabled with the register_long_arrays directive.
echo $HTTP_POST_VARS['username'];
// Available if the PHP directive register_globals = on. As of  PHP 4.2.0 the default value of register_globals = off. Using/relying on this method is not preferred.
echo $username;
?>
-----------------------------
// constants
define("FOO", "something");
const CONSTANT = 'Hello World';
-----------------------------
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
$a = 1; $b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5
-----------------------------
$a % $b; //Modulus
-----------------------------
$a == $b //TRUE if $a is equal to $b after type juggling.
$a === $b //TRUE if $a is equal to $b, and they are of the same type. 
-----------------------------
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.
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
-----------------------------
// Get a file into an array.  In this example we'll go through HTTP to get the HTML source of a URL.
$lines = file('http://www.example.com/');
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) 
{ echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";}
// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
-----------------------------
$output = `ls -al`;//execute the contents of the backticks as a shell command
echo "<pre>$output</pre>";
-----------------------------
UNION OF ARRAYS
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
//$c = array("a" => "apple", "b" => "banana",  "c" => "cherry");
for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
-----------------------------
string get_class ([ object $object = NULL ] )
Returns the name of the class of an object
-----------------------------
if ($a > $b)       echo "a is bigger than b";
elseif ($a == $b)   echo "a is equal to b";
else             echo "a is smaller than b";
-----------------------------
foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement
-----------------------------
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) 
    echo "Key: $key; Value: $value<br />\n";
foreach ($arr as $key => $value) 
    echo "Key: $key; Value: $value<br />\n";
-----------------------------
switch ($i) {
case 0: echo "i equals 0"; break;
case 1: echo "i equals 1"; break;
case 2: echo "i equals 2"; break; }
-----------------------------
function add_some_extra(&$string)
{ $string .= 'and something extra.'; }
$str = 'This is a string, '; add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
function makecoffee($type = "cappuccino")
{ return "Making a cup of $type.\n"; }
echo makecoffee();//Making a cup of cappuccino.
echo makecoffee(null);//Making a cup of .
echo makecoffee("espresso");//Making a cup of espresso.
-----------------------------
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
 $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of " . join(", ", $types) . " with $device.\n" ;  }
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
-----------------------------
join() is an alias of implode()
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
-----------------------------
function square($num) { return $num * $num; }
echo square(4);   // outputs '16'.
-----------------------------
function small_numbers() { return array (0, 1, 2); }
list ($zero, $one, $two) = small_numbers();
-----------------------------
$info = array('coffee', 'brown', 'caffeine');
list($drink, $color, $power) = $info;
list($drink, , $power) = $info;
list( , , $power) = $info;
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
-----------------------------
$result = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) { echo " <tr> \n " .
" <td> <a href = \"info.php?id=$id\" > $name </a> </td> \n" .
" <td> $salary </td> \n" .
" </tr> \n "; }
-----------------------------
list($a, list($b, $c)) = array(1, array(2, 3));
-----------------------------
function foo() { echo "In foo()"; }
function bar($arg = '') 
{ echo "In bar(); argument was '$arg'"; }
function echoit($string) { echo $string; }
$func = 'foo';  $func(); // This calls foo()
$func = 'bar';  $func('test');  // This calls bar()
$func = 'echoit'; $func('test');  // This calls echoit()
-----------------------------
class Foo { 
function Variable() { $name = 'Bar'; 
$this->$name(); // This calls the Bar() method }
function Bar() { echo "This is Bar"; }
} //class Foo
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()
-----------------------------
class Foo{ static $variable = 'static property';
static function Variable() { echo 'Method Variable called';} }
echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
$variable = "Variable";
Foo::$variable();  // This calls $foo->Variable() reading $variable in this scope.
-----------------------------
$greet = function($name){ printf("Hello %s\r\n", $name); };
$greet('World');  $greet('PHP');
-----------------------------
class SimpleClass {
// property
public $var = 'a default value';
// method 
public function displayVar() 
{ echo $this->var;}   } //class
-----------------------------
class A{
 function foo(){
  if (isset($this)) {
   echo '$this is defined (';
   echo get_class($this);
   echo ")\n"; } 
  else echo "\$this is not defined.\n";
 }
}
class B{
function bar(){
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();} }
$a = new A();  $a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();  $b = new B();  $b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
-----------------------------
$instance = new SimpleClass();
// This can also be done with a variable:
$className = 'Foo';
$instance = new $className(); // Foo()
-----------------------------

No comments:

Post a Comment