You are on page 1of 11

Tng hp kin thc PHP

Dng if ( ! defined(BASEPATH)) exit(No direct script access allowed); l dng Security


bo v file ca cc bn, n khng cho truy cp thng vo file m phi thng qua file
index.php mc ngoi cng.
Khai bao : var $CI = & get_instance();

Ly do: Khi s dng th vin, helper ,model , view bn trong controller ch cn s dng
$this->load-> nhng khi s dng ngay bn trong helper hoc library th chng ta khng
th s dng $this c m chng ta cn khi to dng siu i tng mi bng cach s
dng & get_instance().
- To file helper yu cu inh dng ten_helper
Load helper $this->load->helper(); tn k bao gm _helper
- To file library yu cu tn file ging tn class
Load libarary $this->load->library();
- To model yu cu tn file ging tn class
Load file model t 1 th mc cn truyn ng dn tng i
$this->load->model(blog/queries)
Load model v i tn model qua tham s th 2
$this->load->model (model_name,ten_thay_doi)
Load database $this->load->database(options,true/false)
Hm tai file $this->load->file(filepath/filename,true/false) false tra v trnh duy t, true
tra v chui
-Load ngn ng $this->load->language(ten file,ten folder) ,hm tt $this->lang>load(ten,tham so thu 2 co the co hoac khog(de lua chon goi ngon ngu)khng co se lay
goi mac dinh trong config languge
-Load file config $this->load->config(ten) ,hm tt $this->config->load()
- t cac goi ng dng trong th mc application/third_party
S dng trong controller :
$this->load->add_package_path(APPPATH.'third_party/foo_bar/');
$this->load->library('foo_bar')
$this->load->remove_package_path(APPPATH.'third_party/foo_bar/');
1.Xy dng th vi n load template /vlogplus/application/libraries/template.php
- To library class template
* To phng thc set ($file,$data)
+ x ly vi thng tin trong layout
if (strpos($file, '/header') == TRUE)
if (strpos($file, '/left') == TRUE)
if (strpos($file, '/right') == TRUE)
{ Tra li cac bin gia tri $data[]}
Return $this->load->view($file,$data,TRUE); s dng tai file view v. $file l tn file
mun tai khng cn ui .php, $data l mang ho c project chng se i qua b hm PHP
extra view co th hiu c, thng s th 3 m c inh l false nu l false d li u tra
v cho trnh duy t nu l true d li u tra v dng chui
* To phng thc render($file,$part=array(){$this->load->view($file,$part)}
2. Goi layout trong controller

To phng thc renderLayout($data,$file)


$header = $this->template->set('layout/web/header', $data);
$left = $this->template->set('layout/web/left', $data);
$center = $this->template->set('web/' . $file, $data);
$right = $this->template->set('layout/web/right', $data);
$footer = $this->template->set('layout/web/footer');
$layout = array( 'header' => $header,'left' => $left,'center' => $center,'right' => $right,
'footer' => $footer );
$this->template->render('layout/web/layout/index', $layout);
3.Tng hp cac hm trong PHP
-Hm x ly thi gian
Kiu datetime trong mysql : Y-m-d H:i:s '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
Kiu date trong mysql : Y-m-d '1000-01-01' to '9999-12-31'
Kiu timestamp lu tr t gi hi n tai sang UTC v chuyn i ngc li khi ly ra
Kiu char di c inh, khoang trng phia trc bi loi bo v t ng thm vo bn
phai u di
Nh n ngy gi hi n ti $date= date(Y-m-d H:i:s),l la ngy trong tun:Monday,a hien
thi am hoac pm
Hm time() tra v trc tip s giy thi gian hi n tai vi /1/1970 00:00:00
Hm mktime()tra v trc tip s giy thi gian bt k vi /1/1970 00:00:00
Chuyn sang s giy t thi im 1/1/1970 00:00:00
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");
echo(strtotime("next Monday") . "<br>");
echo(strtotime("last Sunday"));
-Set thi gian mc inh h thng
date_default_timezone_set(Asia/Ho_Chi_Minh)
- Ham x ly vi chui
Hm ct chui : substr(string, start, end)
+substr($string,-1) ly phn t cui cung
Chuyn sang vit hoa mb_strtoupper(string,'UTF-8')
Chuyn sang vit thng mb_strtolower(string,'UTF-8')
Gii hn s t word_limiter($string,$limit)
Hm gii hn s ch trong chui, chuyn sang du 3 chm character_limiter($string,40)
Hm m s ki t chui strlent($string)
Hm loi bo cac the html khoi chui strip_tags($string)
Hm exit tng ng hm die ->xut chui v dng chng trnh
Hm json_decode($json_string,$assoc) chuyn chui json sang dng mang ho c i
tng. $assoc =true tra v dng mang, $assoc= false tra v dng i tng. Mc inh l
false.
Hm str_replace($chuoi can thay,$chuoi thay the,$chuoigoc)
- So sanh
So sanh == khng so sanh kiu d li u nn dn n kt qua sai.
So sanh === bao gm ca so sanh kiu DL nn kt qua ng

- X ly vi file
Hm file() oc ton b file v tra v 1 mang
B1: M file dung @ tranh bao li ra mn hnh nu file cha tn ti @fopen($path,"r")
B2:M file v to file khi file cha tn ti fopen($path,"w+")
Cac ch m file:
R: ch oc
R+: oc v ghi
W : ch ghi ,n i dung se bi xoa nu nh co n i dung, cha co to mi
W+ oc v ghi
A : m file ch ghi, cha co to mi v ghi ni d li u vo
A+: m file oc v ghi, cha co to mi v ghi ni d li u vo
B: m ch binary
B3:Ghi vo file fwrite($file,$string)
\r\n xung dong trong h thng window
\n xung dong h thng UNIX
\r xung dong h thng old MAC
Ho c xung dong s dng PHP_EOL
B4. oc file
oc file theo tng ki t fgetc($file)
oc file theo tng dong fgets($file)
Kim tra oc n ki t cui cung cua file cha feof($file)
Ly kich thc file cn oc filesize($path)
oc ht tt ca file fread($file, filesize($path))
B5. ong file fclose($file)
Kim tra file co tn ti khng file_exists($path).
Kim tra file co quyn ghi khng is_writable($path)
Ly n i dung m t file bt k k dung hm fread: files_get_contents($path) nu
$path l 1 link kt qua l file html cua trang web o
Ghi n i dung vo file k dung fwrite: file_put_contents($path,$content)
i tn file: rename($name1,$name2)
Copy file copy($path_resource,$path_des)
Xoa file unlink ($path)
Kim tra folder co tn ti khng is_dir($path)
To folder mi mkdir($path)
L nh khac trong php
1 In_array(giatrikiemtra,array(,)) Kim tra 1 phn t co thu c mang khng
2 Gi thu vi n session $this->load->library(session)
To thng bao flash session, hin thi duy nht cho thao tac tip theo v t ng c xoa
sau o
$this->session->set_flashdata(key,message)
Goi thng bao $this->session->flashdata(key)
3. to bin session
$this->session->set_userdata(array())
Goi bin session $this->session->userdata($bien)

4.Remove bin session


$this->sesson->unset_userdata($bien)
5. xoa tt ca session hi n co
$this->session->sess_destroy();
6.phng thc magic
__CLASS__ tra v tn cua chinh class goi no
__FUNCTION__ tra v tn cua chinh hm goi no
Array_slice(array,start,length,true/false) ct mang ti vi tri yu cu
+start <0 vi tri -1 l ki t cui cung,true gi li khoa,false khng gi lai khoa
7.Hm tach chui thnh mang v nh p mang thnh chui
explode(ki tu de phan tach,$str)
implode(ki tu de phan tach,$arr)
8.Goi 1 bin trong config ,goi file config trong autoload
$this->config->item(ten config)
9.Ep kiu d li u (int) $bin
10.Lin quan n url
url hi n ti hm : current_url()
url gc hm : http:// .$_SERVER[HTTP_HOST] = $_SERVER[SERVER_NAME]
vlogplus.vn/localhost
<?php echo $this->input->server('REQUEST_URI'); ?> tra v thnh phn url trc du
hoi vd: http://www.vlogplus.vn/backend/users/manager kt qua l backend/user/manager
11. ma hoa base64_encode v base64_decode co th giai ma c
64 l s ki t biu din A-Z,a-z,0-9,+,/
12. to random string random_string(alpha,4)
13. floor() lm tron xung, ceil() lm tron ln, random(s,s ch s sau th p phn mun
ly) lm tron theo s mun ly
14 end($array) ly phn t cui cung cua mang
15 parse_url($url) phn tach url ra thnh 1 mang thng s cha host v path
Parse_url($url, PHP_URL_QUERY) ly phn t sau du ? trn ng dn
Vd: parse_url('https://www.youtube.com/watch?v=2mAcwkJanSg',PHP_URL_QUERY);
Kt qua v=2mAcwkJanSg
parse_str($String, $params) tach chui a vo mang $params
vd parse_str(v=2mAcwkJanSg, $params) kt qua $params = Array ( [v] =>
2mAcwkJanSg )
Hm intval(chuoi) loc ra s nguyn loi bo chui sau s nguyn, nu bt u bng ch,
kt qua bng 0
16. set_time_limit() t thi gian ti a chy 1 script,thng s =0 l bo qua xet,dung
hn ch vong l p v hn ho c thi gian ti a request 1 trang web
17 ini_set('memory_limit', '256M'); tng b nh cho memory ,co tac ng duy nht ti
script ang chy
18. hi n format 1 s
Number_format(number) m c inh 1 thng s hi n du ,
Number_format(number,so_chu_so_phanthapphan,dau_ngan_thapphan,dau_phan_ngh
in)
19 setcookie : setcookie(name,giatri,time(s),path);
18 CURL h tr truyn d li u qua giao thc protocol

Khi to curl_init()
Set cu hnh curl_setopt($ch-i tng curl, CURL_tenecauhinh,gia tri cua cu hnh)
Thc thi curl_exec($ch-i tng curl);
ong cu hnh curl_close($ch)
VD: ly anh t website khac v
function curl_download($Url,$saveTo)
{
$fp= fopen($saveTo,'w+');
$ch= curl_init($Url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
$result= curl_close($ch);
return $result;}
Tng hp cac l nh SQL trong codeigniter
$this->load->database(ten database muon kt ni trong file config,TRUE) s dng true
se tra v i tng database,true l m c inh
To 1 query v goi $this->db->query($query)
G p where v get: $this->db->get_where(table,array(),$from,$to)
Ly phn t max $this->db->select_max(field)->get(table)
$this->db->select_min(field)->get(table)
$this->db->select_avg(field)->get(table)
$this->db->where_in($bien,$mang)
1.L nh select tra v d li u l 1 kt qua duy nht u tin di dng i tng
$this->db->select()->where(,)->get(table)->row();
1.L n h select tra v d li u l 1 kt qua duy nht u tin di dng i mang
$this->db->select()->where(,)->get(table)->row_array();
2.L nh select tra v d li u l 1 mang i tng
$this->db->select()->where(,)->get(table)->result();
3.L nh select tra v d li u l mang chng mang
$this->db->select()->where(,)->get(table)->result_array();
4. m s lng kt qua tra v
$query->num_rows()
Ho c
$this->db->count_all_results(table)
5.m s c t tra v,ap dng khi kt qua tra v l i tng
$query->num_fields()
6.Giai phong b nh kt qua cua query
$query->free_result()
7.Ly kt qua t bang
$this->db->get(table)->result()
8.L nh update
$this->db->where()->update(table,$data)
Ho c

$this->db->set()->where()->update($table)
9 Lnh insert
$this->db->insert(table,$data)
Kim tra kt qua insert
$this->db->insert_id()
9 kim tra l nh query
$this->db->affected_row()
10. L n
h delete 1 hng
$this->db->where()->delete(table)
11. Sp xp theo th t v gii hn
$this->db->order_by(,ASC/DESC/RANDOM)
$this->db->limit(from,to);
12 Tm kim ging trong csdl
$this->db->like(field,keyword)
13 Lnh ni bang
$this->select()->from(table1)->where(,)->join(table2,table1.field1=table2.field2)
Trong o
select(table1.*,table2.field,table2.field) ly tt ca field trong table1 v cac field cn ly
trong table2
14. X ly OR khi khng h tr or_where
$this->db->where((field=$bien1 OR filed2=$bien1)
Require_one(file defined.php vo index)
Tm hiu v preg_match
Preg_match($pattern,$subject,$matches)
$pattern l pattern so sanh
$subject l chui mun so khp
$matches kt qua tra v khi so khp ng
Vd: if (preg_match('/^[0-9]+$/', '123', $maches)){
var_dump($maches);

kt qu array

0 => string '123' (length=3)

$pattern bt u v kt thc bng / so khp khng hon ton


$pattern = '/abc/';
$subject = 'mabcd';
if (preg_match($pattern, $subject)){
echo 'Chui regex so khp';
}

Kt qua vn ng v co chui abc


$pattern bt u ^ v kt thc vi $ so khp hon ton
$pattern = '/^abc$/';
$subject = 'mabcd';
if (preg_match($pattern, $subject)){
echo 'Chui regex so khp';

Kt qua sai
$pattern : [a-z] [A-Z] [0-9]
$pattern l hoc 1 trong cac ki t moc vung[a2b]
$pattern xac inh chiu di cua chui [a-z]{min,max}
$pattern xac inh chiu di cua chui [a-z]{length}
du . i din cho ki t bt k, so sanh vi du . thm \.
du * i din khng co hoc nhiu ki t
du + i din co 1 hoc nhiu ki t
ki t ? i din co 1 hoc khng co ki t no
(.+) ki t bt k 1 hoc nhiu ln
(.+?) xut hin 1 ln ngn chn thuc tinh ham n Greedy (ly tng kt qua ch k duyt
ht chui mi ly.

\d - Ch s bt k ~ [0-9]

\D - K t bt k khng phi l ch s (ngc vi \d) ~ [^0-9]

\w - K t t a-z, A-Z, hoc 0-9 ~ [a-zA-Z0-9]

\W - Ngc li vi \w (ngha l cc k t khng thuc cc khong: a-z, A-Z, hoc 0-9)


~[^a-zA-Z0-9]

\s - Khong trng (space)

\S - K t bt k khng phi l khong trng.

preg_match('/([a-z]+)([0-9]+)/', 'freetuts2014', $matches);


Array
(
[0] => freetuts2014
[1] => freetuts
[2] => 2014
)

Kim tra hoc /^A|B$/

-hm preg_replace($pattern,$replace,$subject)
$pattern chui tm kim so sanh
$replace chui thay th
$subject chui gc cn thay th
Xoa the h1
$partern = '/(<h1>)|(<\/h1>)/';hoc <\/?h1>
$subject = '<h1>Welcome to freetuts.net</h1>';
$replacement = '';
echo preg_replace($partern, $replacement, $subject);

Tim hiu v redis


-Nosql l none sql h quan tri d li u khng rng bu c,lu d li u theo kiu key->value
v d li u tn ti di kiu json
Thit bi di ng k th s dng kiu SQL v b nh ,tc x ly thp
Ci t redis
+ci driver trn server
+thm dong extension= redis.so vo file php.ini
+kt ni $redis= new Redis() ,$redis->connect(host,port)
- Port config m c inh kt ni ti redis l port 6379
+Cu hnh cac tham s trong file config database
M c inh:
$active_group = 'default';
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
->chuyn sang:
$active_group = 'db';
$db['db']['hostname'] = tn host (s dng c ca tn min v ia ch IP);
$db['db']['username'] = 'Tn tk';
$db['db']['password'] = MK;
$db['db']['database'] = 'ten kt ni cua database ';
->s dng cho nosql -redis
Master
$db['master']['hostname'] =;
$db['master']['username'] = '';
$db['master']['password'] =;
$db['master']['database'] =;
Slave
$db['slave']['hostname'] =;
$db['slave']['username'] = ';
$db['slave']['password'] = ';
$db['slave']['database'] =;
-Cach set key redis
$key= __CLASS__.___FUNCTION__.
$redis->incr($key) nu $key khng tn ti set gia tri bng 0 trc khi tng v sau o co
gia tri bng 1

Tng s thc $redis->incrByFloat($key,1.5) tng thm 1.5 nu $key cha tn ti


Nh n $key bt ky $redis->randomKey()
t thi gian tn ti cho $key : $redis->setTimeout($key,$time(s))
Reset $key: $redis->setex($key,time,$value)
Sleep(time(s)) ch trong time giy
Tra v chui con: getRange()
Ex :
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5); /* 'string' */
$redis->getRange('key', -5, -1); /* 'value' */

Chuyn chui con setRange()


$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis"); /* returns 11 */
$redis->get('key'); /* "Hello redis" */

Ly v time tn ti cua $key : $redis->ttl(key)


* Kiu d li u Sets
sAdd thm phn t ti set, nu phn t a tn ti return 0/FALSE,nu cha tra v s
phn t trong sets
Ex:
$redis->sAdd('key1' , 'member1'); /* 1, 'key1' => {'member1'} */
$redis->sAdd('key1' , 'member2', 'member3'); /* 2, 'key1' => {'member1',
'member2', 'member3'}*/
$redis->sAdd('key1' , 'member2'); /* 0, 'key1' => {'member1', 'member2',
'member3'}*/

sCard tra v s phn t trong set,


$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2',
'member3'}*/
$redis->sCard('key1'); /* 3 */
$redis->sCard('keyX'); /* 0 */

sDiff tra v phn t khac nhau gia cac Set


$redis->delete('s0', 's1', 's2');
$redis->sAdd('s0',
$redis->sAdd('s0',
$redis->sAdd('s0',
$redis->sAdd('s0',

'1');
'2');
'3');
'4');

$redis->sAdd('s1', '1');
$redis->sAdd('s2', '3');
var_dump($redis->sDiff('s0', 's1', 's2'));
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "2"
}

sIsMember kim tra value co l gia tri lu trong key khng


$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');

$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2',


'member3'}*/
$redis->sIsMember('key1', 'member1'); /* TRUE */
$redis->sIsMember('key1', 'memberX'); /* FALSE */

sMembers tra v n i dung cua set

$redis->delete('s');
$redis->sAdd('s', 'a');
$redis->sAdd('s', 'b');
$redis->sAdd('s', 'a');
$redis->sAdd('s', 'c');
var_dump($redis->sMembers('s'));
array(3) {
[0]=>
string(1) "c"
[1]=>
string(1) "a"
[2]=>
string(1) "b"
}

sRem,sRemove loi bo phn t t set,return s phn t bi bo


$redis->sAdd(key1 ,
$redis->sAdd(key1 ,
$redis->sAdd(key1 ,
member3}*/
$redis->sRem(key1,

member1);
member2);
member3); /* key1 => {member1, member2,
member2, member3); /*return 2. key1 => {member1} */

Kiu Sorted sets


zAdd thm phn t ho c update score nu a tn ti
zAdd($key,$score,$value)
$redis->zAdd(key, 1, val1);
$redis->zAdd(key, 0, val0);
$redis->zAdd(key, 5, val5);
$redis->zRange(key, 0, -1); // array(val0, val1, val5)

zCard,zSize tra li s phn t


$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zSize('key'); /* 3 */

zCount($key,$from,$to) tra v phn t co score nm trong gii hn


$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zCount('key', 0, 3); /* 2, corresponding to array('val0', 'val2') */

zIncrBy tng score cua thnh phn


$redis->delete('key');
$redis->zIncrBy('key', 2.5, 'member1'); /* key or member1 didn't exist, so member1's
score is to 0 before the increment */
/* and now has the value 2.5 */
$redis->zIncrBy('key', 1, 'member1'); /* 3.5 */

zRange($key,$from,$to,withscrores=false) tra v phn t co score thu c phm


vi,withscore=true tra v kt qua bao gm ca score
$redis->zAdd('key1', 0, 'val0');

$redis->zAdd('key1', 2, 'val2');
$redis->zAdd('key1', 10, 'val10');
$redis->zRange('key1', 0, -1); /* array('val0', 'val2', 'val10') */
// with scores
$redis->zRange('key1', 0, -1, true); /* array('val0' => 0, 'val2' => 2, 'val10' => 10) */

zRangeByScore, zRevRangeByScore
zRangeByScore($key,$start,$end,$option=array())
option 2 bin withscores=>TRUE, limit=>array(offset,count)
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zRangeByScore('key', 0,
$redis->zRangeByScore('key', 0,
'val2' => 2) */
$redis->zRangeByScore('key', 0,
$redis->zRangeByScore('key', 0,
1)); /* array('val2' => 2) */

3); /* array('val0', 'val2') */


3, array('withscores' => TRUE); /* array('val0' => 0,
3, array('limit' => array(1, 1)); /* array('val2') */
3, array('withscores' => TRUE, 'limit' => array(1,

zRem,zDelete xoa phn t vi member c a ra


$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zDelete('key', 'val2');
$redis->zRange('key', 0, -1); /* array('val0', 'val10') */

zRevRange
$redis->zAdd('key', 0, 'val0');
$redis->zAdd('key', 2, 'val2');
$redis->zAdd('key', 10, 'val10');
$redis->zRevRange('key', 0, -1); /* array('val10', 'val2', 'val0') */
// with scores
$redis->zRevRange('key', 0, -1, true); /* array('val10' => 10, 'val2' => 2, 'val0' => 0)
*/

zScore tra v score cua member


$redis->zAdd('key', 2.5, 'val2');
$redis->zScore('key', 'val2'); /* 2.5 */

Tm hiu v memcached
Cu hnh:
To file config.php trong config
To th vi n memcache_library trong libraries
Goi trong controller $this->memcache_library->
Xoa tt ca phn t trong memcache $this->memcache_library->flush()
Get phn t $this->memcache_library->get($key)
Thm phn t vo key $this->memcache_library->add($key,$value)

You might also like