PHP – scandir, foreach, is_dir, is_file, nested

近期工餘時間都忙於一個學習專案,因為想出一個自己想做的一個課題,慢慢將佢實現,而從中所學到的會比只看書所學到的會更多(唔洗講都一定要用google),而我依家個學習專案係做一個有前後台的網站,無錯,就係好似wordpress咁有cms,當然我嗰個係超陽春(用wordpress做比喻,我自己都覺得過份咗,哈哈),做到一個可刪除檔案的頁面時又遇到問題,就係點樣可以將folder內的folder(sub-folder)內的檔案都可以找出來刪除呢,而又要去除其中的’.’與’..'(一點與兩點,代表自己directory及上一個directory),搞咗好耐,以下就分享下我嘅做法(這裡用顯示folder 或 file代替):

nested('../../../files/news');   //呼叫 nested 函式

function nested ($arg){   //開始 nested 函式
 $dir = scandir($arg);   //用 scandir() 把指定directory內的folder及file名以arry型式放入 $dir
 foreach ($dir as $value)   //用 foreach() 把array內的元素游走一次
 {
   if(($dir[0] == $value) || ($dir[1] == $value))   //去除 directory 內的 '.'與'..' 自己directory及上一個directory
     continue;
 
   if (is_dir($arg.'/'.$value))   //用 is_dir() 確定是否folder
   {
     echo $arg.'/'.$value." ---- is a folder<br>";   //如是folder,印出
     nested($arg.'/'.$value);   //如是folder,再呼叫函式自己以確定內裡(sub-folder)的是folder或file
   }
   elseif (is_file($arg.'/'.$value))   //用 is_file() 確定是否file
     echo $arg.'/'.$value." ---- is a file<br>";   //如是 file,印出
   else
     echo $arg.'/'.$value." ---- Not file or folder<br>";   //如不是folder或file(仲有咩?),印出
 }
}

當然,上返php官網都有好多勁人post咗好多example上去,但係對我黎講就有啲難理解,以下係相關網站:

PHP官網: http://php.net/manual/en/function.scandir.php

教學網站(簡體): http://www.w3school.com.cn/php/func_directory_scandir.asp

ps. 如果在自己的Linux電腦測試,記得要留意permission問題,即係folder(777,755,…)果啲,要比apache server有寫入權限,而selinux亦都要設定嗰個folder可以被讀寫權限,我都搞咗幾日,以下係我參考的網站:

CentOS 7 + SELinux + PHP + Apache – cannot write/access file no matter what

** 本文同時會張貼在我的google blog:  https://leotseblog.blogspot.com **

 

PHP,MySQL,JavaScript入門好書介紹

圖片來源: http://lpmj.net/4thedition/

今次想介紹一本好書,就係O’Reilly出版,Robin Nixon寫嘅 “Learning PHP, MySQL, & JavaScript” 已經出到第四版,依本書可以話係我對PHP及MySQL網頁編程嘅啟蒙書,我係在公共圖書館借返黎的,當時係借中文譯版第二版,而點解我會覺得依本書係一本好書呢? 因為佢會由教用server開始,裝XAMMP(windows,Mac,Linux都有提點裝),介紹編輯器,PHP與MySQL的互動,當然仲有介紹JavaScript, Ajax, HTML5, CSS, JQuery等等,最重要佢有提一啲編程資安的資訊,跟住本書一步一步做到最後會做咗成個網站出黎(資質所限,我當然還沒有做到),所以一本咁全面嘅書係好值得介紹比想學及初學網頁編程嘅朋友們.當然我己經在灣仔電腦城二樓賣電腦書嗰間舖頭買咗第四版中譯本返屋企喇XD.

相關連結:

書本網站連結: http://lpmj.net/4thedition/

Amazon網站連結: https://www.amazon.com/gp/product/1491918667/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491918667&linkCode=as2&tag=lephmyanja-20&linkId=EB4KF46RFKL4PXWM

博客來網站連結: http://www.books.com.tw/products/0010685274

** 本文同時會張貼在我的google blog:  https://leotseblog.blogspot.com **