• Php can be runned as a PHP server
  • Php can be runned as interactive command shell like python
    php -a

PHP common scripts

  • text to list and process
    $info = '
    My Home info:
    My refer into:
    My product info:
    My contact info:
    $info_list = explode("\n",$info); // Python: info_list = info.split('\n')
    foreach ($info_list as $each) {
        if(preg_match('/^http/', $each)) echo '<a href="'.trim($each).'">'.$each.'</a>';
        else echo '<p>'.$each.'</p>';
    /* # basically for loop and strip white ends and re instead of startswith() in python
    for each in info_list:
        if each.startswith('http'):
            print '<a href="'+each.strip()+'">'+each+'</a>' # note the "" in php will parse variable, while '' won't
            print '<p>'+each+'</p>'
  • list to text
    $array = array('lastname', 'email', 'phone');
    $comma_separated = implode(",", $array);
    echo $comma_separated; // lastname,email,phone
  • show IP
    echo $_SERVER["REMOTE_ADDR"]; 
  • list related operation
    // item in list
    if (in_array("Glenn", $people))
    echo "Match found";
    // add items
    // sum items
    // iterate item like python enumerate
    foreach (array_values($lst) as $i => $val) {
        echo "$i $val \n";
/* comment */
// comment
# coment

/*----------string---------- */
$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.
$a = '12345';
// This works:
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
echo "qwe{$a}rty"; // qwe12345rty, using braces
// Does not work:
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
$great = 'fantastic';
echo "This is { $great}"; // Won't work, outputs: This is { fantastic}
echo "This is {$great}"; // Works, outputs: This is fantastic
echo "This is ${$a.$b}"; // Works, outputs: This is fantastic
// multi line string
$xml = "line1
$super_long = <<<EOT
super long text here
# logics
if($i==0) funA();
elseif($i==1) funB();
else if($i==1) funB(); // both ok
else funC();
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
function a($n){
  echo $n;
// echo vs print
// print return 1 while echo no return
// echo is faster
date("m.d.Y"); // 03.10.2001
date("Ymd"); // 20010310
date("H:i:s"); // 17:16:18
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
//array and 5.4
// 2D array, 1D array, define, append, print
$emptyArray = array(array());
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
$stack[]="3rd Apple";
$stack[]="4th Apple";
$arr[$i]; // access
/* Redirect browser */
header("Location: targetURL.php");
/* Make sure that code below does not get executed when we redirect. */


//Connect To Database 
mysql_connect($hostname,$username, $password); 
<?  include("connectdb.php"); ?>
// open this directory 
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {
	$dirArray[] = $entryName;
// close directory
//	count elements in array
$indexCount	= count($dirArray);
Print ("$indexCount files<br>\n");
// sort 'em
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
		print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
// ref:
// check record existing
$result=mysql_query("SELECT nameID FROM myTable WHERE nameID = '".$nameVar."' AND date = '".date("Ymd")."' ORDER BY nameID;");
$i=0; //count record
while( $row=mysql_fetch_array($result) ){
header("Location: checkdone.php?nameID=".$emailid."&report=exist");
//check system on off swith
$result=mysql_query("SELECT * FROM switchdb WHERE sname = 'syson';");
while( $row=mysql_fetch_array($result)){
	<b>html here for off</b>
	<b>html here for on</b>
<? include("connectdb.php"); ?>
$result=mysql_query("UPDATE switchdb SET svalue = '1' WHERE sname = 'syson' LIMIT 1 ;");
<body>On Now;<?php echo $result ?>
<br><input type=button value="Back" onClick="history.go(-1)">

php post vs get form data

  • Post will hide the form data from url address
    <form action="process.php" method="post"><select name="item">
    $item = $_POST['item'];
  • Get will show form data in url address
    <form action="process.php" method="get"><select name="item">
    $item = $_GET['item'];
  • more secure way of send form data into SQL
    //Lets make it safer before we use it
    $item = htmlentities($_POST['item']);
  • request and secure
    if(isset($_REQUEST['emailid'])) $emailid=htmlentities($_REQUEST['emailid']);
    // initialize and check existing
  • self posting
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
  • table print
    // print table header
    echo "
    	<table id='__tableName__' name='__tableName__'>
    	<th>Entry ID
    // Generate table entries
    $result=mysql_query("SELECT * FROM entryList ORDER BY entryID;");
    while( $row=mysql_fetch_array($result) )
    	echo "<tr>";
    	echo "<td><b>".$row['entryID']."</b></td>";
    	echo "<td>".$row['entryName']."</td>";
    	echo "<td>".$row['date']."</td>";
    	echo "<td>".$row['amount']."</td>";
    	echo "</tr>";
  • get table unique item count, like for Food Ordering, how many drinks totally and for each type (coke, tea)
    while( $row=mysql_fetch_array($result) ){
        // check whether they need drink or not
            // html the drink
            echo "Drink : ".$row['drink']."<br><br>";
            // count drink, array of entry('drinkName',number)
                if($drinkList[$j][0]==$row['drink'] && $found==0) {
                    $drinkList[$j][1]=$drinkList[$j][1]+1; // if already entried, then add 1
                    $found=1;break; // save time
                $drinkList[$tmpS]=array($row['drink'],1); // if not entried, create and put 1
    // the html display part
    echo "We need <br>";
    echo "<b>".$drinkList[$i][0]."</b>: <font style='color:red'>".$drinkList[$i][1]."</font> ";
echo "
<script type='text/javascript'>
function checkform(){
	alert('Please enter: __EntryName__');
	return false;
else if(document.forms['__FormName__'].elements['__Type__'].value ==''){
	alert('Please enter: __Type__');
	return false;
else {return true}
<form style='visibility:visible;' name='__FormName__' action='index.php' method='post' onsubmit='return checkform()' id='__FormName__' >
<input name='__EntryName__' length='128'>Entry Name<br>
Entry Type: <select name='__Type__'>
<input type=submit value='__ButtonName__'>
<input name='__action__' type=hidden value='__action__'>
  • get form data
    $__EntryName__=""; if(isset($_REQUEST['__EntryName__'])) $__EntryName__=htmlentities($_REQUEST['__EntryName__']);
    $__Type__=""; if(isset($_REQUEST['__Type__'])) $__Type__=htmlentities($_REQUEST['__Type__']);

sql create entry

$result=mysql_query("INSERT INTO entryList (entryName,type,date) VALUES('$entryName','$type','$date')");
  • md5: 128-bit hash (32 hexadecimal characters)
  • sha1: 160-bit hash (40 hexadecimal characters)

A common basic is

  1. stretching the length of password before hashing, which results hacker to use impossible huge size of rainbow table.
  2. your last encryption function should not be a hash function, thus, they can't reverse hash it from (Common limit number of) hash algorithm.


  • php method
    • list of browser request data
      // ref:
      $lan = substr(?$HTTP_ACCEPT_LANGUAGE,0,5) // get first 5 letter of return value
      if ($lan == "zh-cn") || ($lan == "zh-tw")
        print("<meta http-equiv='refresh' content = '0;URL = cn/index.htm'>"); 
        print("<meta http-equiv='refresh' content = '0;URL = eng/index.htm'>"); 
      // alternative
      $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4);
      if (preg_match("/zh-c/i", $lang))  
      echo "chinese";  
      else if (preg_match("/zh/i", $lang))  
      echo "traditional chinese";  
      else if (preg_match("/en/i", $lang))  
      echo "English";  
      else if (preg_match("/fr/i", $lang))  
      echo "French";  
      else if (preg_match("/de/i", $lang))  
      echo "German";  
      else if (preg_match("/jp/i", $lang))  
      echo "Japanese";  
      else if (preg_match("/ko/i", $lang))  
      echo "Korean";  
      else if (preg_match("/es/i", $lang))  
      echo "Spanish";  
      else if (preg_match("/sv/i", $lang))  
      echo "Swedish";  
      else echo $_SERVER["HTTP_ACCEPT_LANGUAGE"];  
    • javascript version
      var type=navigator.appName 
      if (type=="Netscape") 
        var lang = navigator.language 
        var lang = navigator.userLanguage 
      //cut down to first 2 chars of country code 
      var lang = lang.substr(0,2) 
      if (lang == "en") 
      else if (lang == "zh-cn") 
      else if (lang == "zh-tw") 
  • detect browser
    if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 8.0"))  
    echo "Internet Explorer 8.0";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 7.0"))  
    echo "Internet Explorer 7.0";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 6.0"))  
    echo "Internet Explorer 6.0";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox/3"))  
    echo "Firefox 3";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox/2"))  
    echo "Firefox 2";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"Chrome"))  
    echo "Google Chrome";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"Safari"))  
    echo "Safari";  
    else if(strpos($_SERVER["HTTP_USER_AGENT"],"Opera"))  
    echo "Opera";  
    else echo $_SERVER["HTTP_USER_AGENT"];  

PHP application development workflow

structure of single-page-applicaiton

  • service interface rendering section
    1. secure level check
      1. display interface
        1. user action a: require display data
        2. user action b: require create data
        3. user action c: require edit data
        4. user action d: require delete data
  • service handling section
    1. secure level check
      1. handle a: present display format require form or direct process
      2. handle b: present creation form
      3. handle c: present update form
      4. handle d: present delete confirmation
      5. feedback loop a: get display requirement and process
      6. feedback loop b: get creation data entry and process
      7. feedback loop c: get updated data entry and process
      8. feedback loop d: get delete confirmation and process
  • service process section
    1. secure level check
      1. loop exe a: display data in required format
      2. loop exe b: execute Creation SQL
      3. loop exe c: execute Update SQL
      4. loop exe d: execute Delete SQL
  • service exception response section
    1. secure level report
      1. access denied
      2. execute report:
        1. report a: display done
        2. report b: entry created
        3. report b: (error) please make sure all fields are filled correctly
        4. report c: entry updated
        5. report c: (error) please make sure all fields are filled correctly
        6. report d: entry deleted
  • detect jpg in directory

When PHP is running out of efficiency

  • I have been starting reading about Python in web development, as I read about this
  • “when you start writing bigger web applications, most of your code has nothing to do with HTML, and PHP’s HTML-friendly features just seem to get in the way.” - ref