2007年11月9日 星期五

php基本教學

1. General
// include tag, ; to separate command
phpinfo(); // return php setting info
print("hello"); // print
print "hello"; // print, without ()
\" // \ is escape code
\n\r\t // new line, return, tab
(\r\n) // line change character
// # // comment
/* */ // multiple line comment
c:\windows\php.ini // configuration
c:\php\php.ini-dist // original config

2. Variable
$name // variable name start with $, case sensitive
// no initialize nor declare
// number, string, array and object
string // "$name" translate, '$name' not
$variable="happy"; // assignment
$number=(integer) 5; // casting
HOSTNAME // predefined environmental variables,
check phpinfo() for the list

3. Forms

form_variable // parsed to $form_variable, no decode needed
// when same variable is assigned in php,
form_variable with same name is discarded
4. Numbers

printf ("%01.2f",$amount); // formatted print a number. 0-place holder
1-digit to left of decimal point
2-digit to right of decimal point
sprintf // formatted print to a variable, not screen
$number++; // increment
round($amount); // built-in functions, round to integer (4~5)
round($amount,1); // round to 1 d.p.
ceil(),floor() // integer
abs() // absolute
srand((double) microtime()*1000000); // seed the rand() function
$randnum=rand(); // run srand() first to ensure randum
$randnum=rand(0,10); // random number with limits

5. Strings
$string=trim($string); // trim space at begin and end
ltrim(), rtrim() // trim either end
$str1.$str2 // . concatenation
urlencode($str); // encode string for url, %20 for space
urldecode();
addslashes($str); // encode string for database, escape
addcslashes($str,"\^$?.+*[|]{}"); // encode string for certain characters
stripslashes($str);
stripcslashes($str);
crypt($str); // encrypt, cannot be decrypt for password store
encrypt(); // encrypt, can be decrypt
decrypt(); // decrypt
md5(); // similar to crypt
strtok($str,"\t"); // substr token, until tab
substr($str,0,10); // substr by position
strlen($str); // string length

6. control structure
if () statement; // single statement
if () {}; // multiple statement
if ($str) // if $str exist and not zero
if (isset($str)) // if $str exist, zero also return true
== != <= >= // comparison operator
AND && OR || NOT XOR // logical operator
if () {} elseif () {} else {} // else and else if
date("A") date("H") // return server datetime - AM, hour
switch ($str) { // switch conditional
case "val1":
statements1;
break;
case "Val2":
statements2;
break;
default:
statements3;
break;
}
while () {} // while loop
do {} while () // do first while loop
for ($i=0; $i<10; $i++) {} // for loop

7. Array
$list=array("apple","orange"); // simple array with index
$list[0]; // call first item
$list=array(1=>"apple",2=>"oragne"); // array with index assignment
$list=array("mon"=>"apple,
"tue"=>"orange"); // array with key is string
$list["mon"]; // call item with key
print $list // return a word "array" to know existence
$list[]="mango"; // append new item to end of array
count($list) // return number of items
$newarray=merge($list1,$list2) // merge two arrays

$line=each($list) // array with key = "key" and "value" for each item in a loop
$line["key"] $line["value"] // call key and value of that item in a loop

sort($list) rsort($list) // sort values in ascend and descend
ksort($list) krsort($list) // sort keys in ascend and descend keeping values correlated
asort($list) arsort($list) // sort values in ascend and descend order keeping keys correlated
reset($list); // reset pointer to top in an array after sorting

$array=explode("\t",$str); // get array from tab separated line (split)
$str=implode("\t",$array); // get string from array with tab between (join)

$list=array($array1,$array2,$var1,30); // array can have different element include other array
$list[0][2]; // call an multi-D element
print "happy {$list[0][2]}"; // multi-D element need {} when print

8. Regex
\ // escape
. // match any single char
a{3,5} // match at least 3, at most 5 a's
a? // "a{0,1}"
a+ // "a{1,}"
a* // "a{0,}"
^a$ // begin and end
(ab) (a|b) // group char, both , or
[a-z] [A-Z] [0-9] // class
[a-zA-Z0-9] // join class
[^a] // not a class
[[:alpha:]] // predefined class
[[:digit:]] [[:alnum:]] [[:space:]] [[:upper:]] [[:lower:]] [[:punct:]]
.+@.+\..+ // regex for email address

ereg("pattern","string"); // return boolean
eregi("pattern","string"); // return boolean, case insensitive
ereg_replace("pat","replace","str"); // replacing matched pattern
eregi_replace(); //
\\1 \\2 // back referencing str in ()


9. Function

function FUNAME ($arg1,$arg2=12) { // function definition, with $arg2 set a default value
global $var // make a local variable within a function accessible to outside, vice versa
return $value // return value
}

10. Files and Directories

r W a // mode: read, write, append
$filepointer=fopen($file,"mode"); // open file with a pointer
fwrite($filepointer,"text"); // write text
fclose($filepointer); // close file
is_writeable($file); // test file writeable before open

$array=file($file); // read file into array

mkdir("path","0666") // new directory

// upload file html tag


if ($upfile) { // save file only if file is posted
print ("filename: $upfile_name

");
print ("filetype: $upfile_type

");
print ("filesize: $upfile_size

");
copy($upfile,"upload/$upfile_name"); // save the file
unlink($upfile); // release the temp file handle
}

rename($oldname,$newname); // rename file or directory
filesize($file); // return file size in byte
$handle=opendir("path");
readdir ($handle); // read one file name at a time
closedir ($handle);
is_file($file); // test if file valid

11. Database - mySQL

$link=mysql_connect("localhost","user","password"); // connect mysql with handle
mysql_close($link); // close connection
mysql_create_db("dbname",$link); // create new db in connection $link
mysql_db_query("dbname",$query,$link); // $query is SQL statement

$result=mysql_db_query(); // read data to $result
while ($row=mysql_fetch_array($result)) {} // get each record to $row array

12. Cookie
// cookie must be sent before html, in the header
setcookie("user","siuho",time()+"1800","path","domain","secure"); // set cookie
$user // read cookie value
setcookie("user","",time()-60"); // delete a cookie

13. Web Application
include("file.php"); // include php script file, only take effect when called
require("file.php"); // include php script file, always loaded
// please mind the order of appearance of variables in parent and include file
date("format",$timestamp); // return format (compulsory) defined. default current time
A - AM/PM
a - am/pm
d - 01-31
D - Sun-Sat
F - January-December
g - 1-12 // hour without leading zero
G - 0-23
h - 01-12 // hour with leading zero
H - 00-23
i - 00-59 // minute with leading zero
j - 1-31
l - Sunday-Saturday
m - 01-12 // month with leading zero
M - Jan-Dec
n - 1-12 // month without leading zero
s - 00-59 // second with leading zero
S - st,nd,rd,...
t - 28-31 // number of days in the month
U // seoonds since the epoch
w - 0-6 // day of the week
y - 00-99 // year as 2 digit
Y - 2002,... // year as 4 digit
z - 0-365 // day of the year

mktime(hour,min,sec,mon,day,year); // create timestamp variable, arg in digit

// php header function, before sending html
header("Location:page.php") // redirection
header("Set-cookie:name=value;expires=expiration"); // send cookie

mail($to,$subject,$content,"From:contact@siuho.com"); // send email

print() or die(); // die function for error message

沒有留言: