Run PHP

  • 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:
    http://mysitetest.com/home
    My refer into:
    http://mysitetest.com/refer
    My product info:
    http://mysitetest.com/product
    My contact info:
    http://mysitetest.com/contact
    ';
    $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
        else:
            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
    $a=array("red","green");
    array_push($a,"blue","yellow");
    // sum items
    array_sum($num_list)
     
    // 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';
$a="gre";$b="at";
 
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
line2";
$super_long = <<<EOT
super long text here
EOT;
 
# logics
$varName="value"; 
if($i==0) funA();
elseif($i==1) funB();
else if($i==1) funB(); // both ok
else funC();
 
//loop
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_start(); 
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
 
if(isset($_SESSION['cart']))
    unset($_SESSION['cart']); 
 
session_destroy();
 
//array and 5.4
$cars=array("Volvo","BMW","Toyota");
$cnt=sizeof($cars);
 
// 2D array, 1D array, define, append, print
$emptyArray = array(array());
 
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
 
$stack[]="3rd Apple";
$stack[]="4th Apple";
 
sizeof($stack);
$arr[$i]; // access
<?php 
/* Redirect browser */
header("Location: targetURL.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>

ref: http://php.net/manual/en/function.mysql-connect.php

<?php
//Connect To Database 
$hostname="localhost"; 
$username="root"; 
$password=""; 
$dbname="mydb"; 
$usertable=""; 
mysql_connect($hostname,$username, $password); 
mysql_select_db($dbname); 
?>
<?  include("connectdb.php"); ?>
<?  
// open this directory 
$myDirectory = opendir(".");
 
// get each entry
while($entryName = readdir($myDirectory)) {
	$dirArray[] = $entryName;
}
 
// close directory
closedir($myDirectory);
 
//	count elements in array
$indexCount	= count($dirArray);
Print ("$indexCount files<br>\n");
 
// sort 'em
sort($dirArray);
 
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\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>");
		print("<td>");
		print(filetype($dirArray[$index]));
		print("</td>");
		print("<td>");
		print(filesize($dirArray[$index]));
		print("</td>");
		print("</TR>\n");
	}
}
print("</TABLE>\n");
// ref: http://www.liamdelahunty.com/tips/php_list_a_directory.php
?>
// 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) ){
$i++;
}
if($i>0){
header("Location: checkdone.php?nameID=".$emailid."&report=exist");
exit;
}
<?php
//check system on off swith
include("connectdb.php");
 
$result=mysql_query("SELECT * FROM switchdb WHERE sname = 'syson';");
while( $row=mysql_fetch_array($result)){
	$syson=$row['svalue'];
}
?>
<?php
if($syson==0){
?>
	<b>html here for off</b>
<?php
}
else{
?>
	<b>html here for on</b>
<?php
}
?>
<? include("connectdb.php"); ?>
<?php
$result=mysql_query("UPDATE switchdb SET svalue = '1' WHERE sname = 'syson' LIMIT 1 ;");
?>
<html>
<body>On Now;<?php echo $result ?>
<br><input type=button value="Back" onClick="history.go(-1)">
</body>
</html>

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
    $emailid=""; 
    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__'>
    	<tr>
    	<th>Entry ID
    	</th><th>Name
    	</th><th>Date
    	</th><th>Amount
    	</tr>
    ";
     
    // Generate table entries
    $result=mysql_query("SELECT * FROM entryList ORDER BY entryID;");
    $i=0;
    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>";
    	$i++;
    }
     
    echo"</table>";
  • get table unique item count, like for Food Ordering, how many drinks totally and for each type (coke, tea)
    <?
    $drinkList=array();
    while( $row=mysql_fetch_array($result) ){
        // check whether they need drink or not
        if(strlen($row['drink'])>0){
            // html the drink
            echo "Drink : ".$row['drink']."<br><br>";
            // count drink, array of entry('drinkName',number)
            $tmpS=sizeof($drinkList);
            $found=0;
            for($j=0;$j<$tmpS;$j++){
                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
                }
            }
            if($found==0){
                $drinkList[$tmpS]=array($row['drink'],1); // if not entried, create and put 1
            }
        }
    }
    ?>
    <?
    // the html display part
    echo "We need <br>";
    for($i=0;$i<sizeof($drinkList);$i++){
    echo "<b>".$drinkList[$i][0]."</b>: <font style='color:red'>".$drinkList[$i][1]."</font> ";
    }
    ?>
echo "
<script type='text/javascript'>
function checkform(){
if(document.forms['__FormName__'].elements['__EntryName__'].value==''){
	alert('Please enter: __EntryName__');
	return false;
	}
else if(document.forms['__FormName__'].elements['__Type__'].value ==''){
	alert('Please enter: __Type__');
	return false;
	}
else {return true}
}
</script>
 
<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__'>
<option></option>
<option>Easy</option>
<option>Average</option>
<option>Hard</option>
</select><br>
 
<input type=submit value='__ButtonName__'>
<input name='__action__' type=hidden value='__action__'>
</form>
";
  • 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.

ref:

  • php method
    • list of browser request data
      $_SERVER["HTTP_ACCEPT_LANGUAGE"]
      $_SERVER["HTTP_ACCEPT_CHARSET"]
      $_SERVER['HTTP_CLIENT_IP']
      $_SERVER['HTTP_X_FORWARDED_FOR']
      $_SERVER['REMOTE_ADDR']
      // ref: http://svn.gna.org/viewcvs/clansuite/website-clansuite.com/index.php?view=markup&pathrev=1749
    • HTTP_ACCEPT_LANGUAGE
      $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'>"); 
      else 
        print("<meta http-equiv='refresh' content = '0;URL = eng/index.htm'>"); 
       
      // alternative
      <?php
      $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 
      else 
        var lang = navigator.userLanguage 
       
      //cut down to first 2 chars of country code 
      var lang = lang.substr(0,2) 
       
      if (lang == "en") 
      window.location.replace('url') 
       
      else if (lang == "zh-cn") 
      window.location.replace('url') 
       
      else if (lang == "zh-tw") 
      window.location.replace('url') 
       
      else 
      window.location.replace('url') 
  • 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