Facebook, Flickr, Wikipedia, SugarCRM, Dotproject, Drupal, Interspire
php settings file: php.ini (use phpinfo(); to show it's content)
Constants (can only defined once)
define("SYS_OWNER", "someone");
define("SYS_OWNER", "anotherone"); //this will raise error
Superglobal arrays: _COOKIE, _SESSION, _GET
Cookies
setcookie("cookieName", $val, time()+60*60*24);
$cookieVal = $_COOKIE["cookieName"];
Session (browser tabs are treated as same session)
session_start();
$_SESSION['today'] = date("Y-m-d");
$retrieveSessionVal = $_SESSION['today'];
Form Data
var variableVal = $_GET["variableName];
var variableVal = $_POST["variableName];
var variableVal = $_REQUST["variableName"]; //will return value set by all GET/POST/REQUEST, if of same name, precedence base on setting in php.ini directive "variable_order", say GPC, means Cookie taking precedence over Post, which take precedence over Get.
Function using default value:
function getRate($param1 = 10, $param2 = 15){ };
Pass by reference
function getRate(&$rate) { };
Include & Require
include "some_lib.php";
which is same as:
require "some_lib.php";
except that if file being include is absent, the latter will raise error while the former will not.
include_once "some_lib.php";
require_once "some_lib.php";
built-in functions: http://php.net/manual/en/indexes.functions.php
var_dump() - dump info of variable
String
HEREDOC construct:
$string = <<;< "RightHere"
Once upon a time, Sally's mother said "My dear"....
.......
RightHere;
NOWDOC: without resolution of variable content. differentiate from HEREDOC by the single quote
$string = <<;< 'RightHere'
Once upon a time, $someone mother said "My dear"....
.......
RightHere;
String Function (Best of)
trimming: ltrim, rtrim, trim
upper/lower case: strtoupper, strtolower
string length: strlen
word count: str_word_count
search string: strstr, stristr (case insensitive), strpos, str_replace
string modification: strip_tags, addslashes, stripslashes, str_shuffle, md5
html encode/decode(< to <): htmlentities, html_entity_decode
pattern matching: preg_match
string substitution: preg_replace
string splitting: preg_split
Array
indexed array:
$myarray[0]=1; $myarray[1]=2;
associative array:
$myarray['first'] = 1; $myarray['second'] = "B";
$myarray = array('first' =>1, 'second' =>'B');
traversing array:
foreach($myarray as $key => $value){...}
Datetime function
$timezone = ini_get('data.timezone'); //get time zone from server's .ini file
$dtz = new DateTimeZone($timezone);
$dt = new DateTime('2015-02-03 16:33:22', $dtz);
$dt->format('Y-m-d h:i:s');
Array Function (Best of)
array_splice, e.g.:
$array1 = array('first'=>1, 'second'=>2, 'third'=>3, 'fourth'=>4, 'fifth'=>5, 'sixth'=>6);
$array2 = array_splice($array1, 2, 3); //extract 3 element start from position 2
outcome:
$array1 = array('first'=>1, 'second'=>2, 'sixth'=>6);
$array2 = array('third'=>3, 'fourth'=>4, 'fifth'=>5);
unset, e.g.:
unset($array1['third']); //simply extract and remove element of key 'third'
sorting: sort (sort by value and reissue key sequentially), rsort, asort(sort by value), arsort (reverse), ksort (sort by key), krsort (reverse), usort (sorty by self-defined funciton)
math-type function: array_sum, count
array_unique (identify & remove duplication), array_rand (random), shuffle, array_merge
searching: in_array, array_search
extract (extract array elements to variables)
array_walk (apply function on every element of the array) e.g.
array_walk($testgrade, 'add10'); //add10 is the function which add 10 to incoming value
Object
e.g. in myClass.inc :
class myClass{
private $tag;
function __construct(){...} //magic method: trigger each time the class is instantiated
public function Begin(){ ...}
} //end class
$myclass = new myClass();
$myclass->Begin();
Database Interface
1. MySQLi (i stands for improved extension)
$mydb = new mysqli('localhost', 'username', 'password', 'dbname');
$sql = 'select * from guests';
$result = $mydb->query($sql);
while( $row = $result->fetch_assoc() ){ echo $row['lastname']; }
$result->close();
$mydb->close();
2. PDO - PHP data object (work with almost all kinds of database: MSSQL, MySQL, Oracle, SQLite, etc.)
configuration: add following in php.ini
extension=php_pdo.dll
extension=php_pdo_mysql.dll
$dsn = 'mysql:dbname=website;host=localhost';
$mypdo = new PDO($dsn, 'username', 'pwd');
$sql = 'select * from guests';
$result = $mypdo->query($sql);
while( $row = $result->fetch(PDO::FETCH_ASSOC) ){ echo $row['lastname']; }
$result->close();
$mypdo->close();
or use prepared statement:
$statement = $mypdo->prepare('select * from guests order by ?');
$mypdo->execute('lastname');
Session
session_start();
$lastInput = $_SESSION['lastInput'];
Other built-in function in PHP
mail() - sending email, require('class.phpmailer.php');
fpdf - generate pdf file, require('../../fpdf/fpdf.php');
jpgraph - generate graphical report, require('../../jpgraph/jpgraph.php');
captchas - generate antispam image, require('../../jpgraph/jpgraph_antispam.php');
working with XML
$xml_doc = new SimpleXMLElement($xml_data);
Security
1. Escape output, so that someone can't leave a hyperlink in ur site
htmlspecialchars($string, ENT_QUOTES);
2. Cross-site scripting, e.g. input <script> alert('hello');</script> in search box;
3. SQL injection
4. password encryption
use sha1: sha1($string);
salt & pepper encryption:
sha1(sha1($salt).$string_to_encrypt.sha1($pepper)); //where $salt & $pepper are hard-coded values
5. Security tips on PHP
- - turn off error display in php.ini
- - make sure register_globals is turned off in php.ini (register_globals create variables in memory based on a submitted HTML form)
- - use SSL where required
- - keep included lib, SQLite files and settings files outside document root
for more, read Chris Shiflett's Essential PHP Security
IDE: Komodo, Zend Studio for Eclipse, PhpED
get current time
$current_time_int = time();
display in formatted string:
$formatted_time = format_date(time(),'short');
沒有留言:
張貼留言