Recent Articles / Archives

MySQL 編碼函式

MySQL 內建提供了一些編碼函式,以下會介紹 ENCODE() 及 DECODE() 的作用及用法:

ENCODE(str,pass_str)
將字串 str 加密,並使用 "pass_str" 作為加密鑰匙,例如:

mysql> select encode("testing string", "mykey");
+ - - - - - - - - - - - - - - - - - +
| encode(”testing string”, “mykey”) |
+ - - - - - - - - - - - - - - - - - +
| �k��y����ۙ�( |
+ - - - - - - - - - - - - - - - - - +
1 row in set (0.00 sec)

 
DECODE(crypt_str,pass_str)
decode() 的作用就是對 encode() 加密的內容解碼,其中 crypt_str 是經過 encode() 加密的二進字串,而 pass_str 就是解密鑰匙。如果使用的鑰匙與加密時的鑰匙不同,回傳的結果便不會正確,用法如下:

mysql> select decode(encode("testing string", "mykey"), "mykey");
+ - - - - - - - - - - - - - - - - - - - - - - - - - - +
| decode(encode(”testing string”, “mykey”), “mykey”) |
+ - - - - - - - - - - - - - - - - - - - - - - - - - - +
| testing string |
+ - - - - - - - - - - - - - - - - - - - - - - - - - - +
1 row in set (0.01 sec)
August 31, 2007 · 程式設計分享 · No Comments Yet

PHP 讀取多重選項清單

在製作 HTML 表單的清單時,可以用 multiple 屬性讓使用者透過 Ctrl 鍵一次過選擇多個選項,例如:

HTML:
  1. <form method="post">
  2. <select name="box" multiple="multiple">
  3. <option value="1">1</option>
  4. <option value="2">2</option>
  5. <option value="3">3</option>
  6. </select>
  7. </form>

但上面的 HTML 碼所傳送的 value 不能給 PHP 正確讀取,因為當同時選擇多個選項時,PHP 只可以讀取一個 value。要修正可以更改 select 的名稱,例如:

HTML:
  1. <form method="post">
  2. <select name="box[]" multiple="multiple">
  3. <option value="1">1</option>
  4. <option value="2">2</option>
  5. <option value="3">3</option>
  6. </select>
  7. </form>

當傳送給 PHP 後,使用者所選取的選擇會放到 $_POST['box'] 陣列內。

August 29, 2007 · 程式設計分享 · No Comments Yet

PHP 檢查信用卡號碼

現在網上購物越來越普及,所以對信用卡號碼的檢查也變得重要。要檢查信用卡號碼,一般可以用 LUHN 演算法來實現。現在大部份的主要信用卡也是使用 LUHN 演算法,包括 Visa, Master Card, American Express 及 Discover 等。LUHN 演算法只可以檢查信用卡號碼的合法性,而不會檢查信用卡其他資訊,包括是否過期。使用方法為:

1. 檢查信用卡號碼是否 16 位。
2. 將信用卡號碼切割成 16 個個別數字。
3. 將上面切割得的所有數字,由左至右起計,每逄單數位置的數值乘 2。
4. 將加總後所有結果都切割成個別數字再相加。
5. 將上面求得的總數求出 10 的餘數,如果餘數是 0 便表示信用卡號碼正確,否則便是錯誤。

以下是 PHP 使用 LUHN 演算法檢查信用卡號碼的函式:

PHP:
  1. <?php
  2. /* luhn_checker(): This is a small PHP function for checking valid *
  3. * credit card with LUHN algorithm                                  *
  4. *                                                                  *
  5. * Last updated: 26 August 2007                                     *
  6. * This is a free PHP script under GNU GPL version 2.0 or above     *
  7. * Copyright (C) 2007 Sam Tang                                      *
  8. * Feedback/comment/suggestions : http://www.real-blog.com/        */
  9.  
  10. function luhn_checker($card_num){
  11.     // 將非數字的字串移除
  12.     $card_num = preg_replace("/\D|\s/", "", $card_num);
  13.  
  14.     $sum = 0;
  15.     for($i=0; $i<strlen($card_num); $i++){
  16.         $digit = substr($card_num, $i, 1);
  17.         if(($i % 2) == 0){
  18.             // 在單數位置的數值乘 2
  19.             $digit = $digit * 2;
  20.         }
  21.  
  22.         if ($digit> 9)  $digit = $digit - 9;
  23.         $sum += $digit;
  24.     }
  25.  
  26.     if(($sum % 10) == 0 && strlen($card_num) == 16){
  27.         return TRUE;
  28.     }else{
  29.         return FALSE;
  30.     }
  31. }
  32.  
  33. /* Example
  34. if(luhn_checker("1234567812345678")){
  35.     echo "Correct!";
  36. }else{
  37.     echo "Wrong card number!";
  38. }
  39. */
  40. ?>

檔案下載: luhn_checker

August 26, 2007 · 程式設計分享 · No Comments Yet

PHP 列出目錄內容

以下是用 PHP 列出目錄內容的方法,當然也可以略為修改以程式碼改為 function 使用:

PHP:
  1. <?php
  2. // 定義要開啟的目錄
  3. $dir = "/var/www/vhosts/dir";
  4.  
  5. // 用 opendir() 開啟目錄,開啟失敗終止程式
  6. $handle = @opendir($dir) or die("Cannot open " . $dir);
  7.  
  8. echo "<b>Files in " . $dir . ":</b><br/>";
  9.  
  10. // 用 readdir 讀取檔案內容
  11. while($file = readdir($handle)){
  12.     // 將 "." 及 ".." 排除不顯示
  13.     if($file != "." && $file != ".."){
  14.         echo "$file<br/>";
  15.     }
  16. }
  17.  
  18. // 關閉目錄
  19. closedir($handle);
  20. ?>

August 26, 2007 · 程式設計分享 · No Comments Yet

Python 連接 MySQL

MySQL 是十分流行的開源資料庫系統,很多網站也是使用 MySQL 作為後台資料儲存,而 Python 要連接 MySQL 可以使用 MySQL 模組。MySQLdb 模組可以讓 Python 程式連線到 MySQL server, 執行 SQL 語句及擷取資料等。

開始前要確定系統內的 Python 有安裝 MySQLdb 模式,你可以 Python command line interpreter 檢查,在指令模式輸入 python,然後便可以開始檢查:

Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named MySQLdb
>>> exit()

 
如果見以上面的 "ImportError: No module named MySQLdb" 一句,便表示系統沒有安裝,到 MySQLdb 官方網站 下載 MySQLdb,並用以下方法安裝:

$ tar zxvf MySQL-python-1.2.2.tar.gz
$ cd MySQL-python-1.2.2
$ python setup.py build
$ python setup.py install

 
安裝好 MySQLdb 後便可以編寫程式碼,以下是簡單的例子:

CODE:
  1. #!/usr/bin/python
  2.  
  3. # 引入 MySQL 模組
  4. import MySQLdb
  5.  
  6. # 連接到 MySQL
  7. db = MySQLdb.connect(host="localhost", user="db_user", passwd="db_pass", db="db_name")
  8. cursor = db.cursor()
  9.  
  10. # 執行 SQL 語句
  11. cursor.execute("SELECT * FROM db_table")
  12. result = cursor.fetchall()
  13.  
  14. # 輸出結果
  15. for record in result:
  16.     print record[0]

August 20, 2007 · 程式設計分享 · No Comments Yet


PHP 透過 SMTP 發送郵件

PHPMailer 是一個功能豐富的函式庫,以下是用 PHPMailer 通過遠端 SMTP 認證發送郵件的例子:

PHP:
  1. <?php
  2. // 建立 PHPMailer 物件及設定 SMTP 登入資訊
  3. require("../phpMailer/class.phpmailer.php");
  4. $mail = new PHPMailer();
  5. $mail->IsSMTP(); // send via SMTP
  6. $mail->Host = "remote.smtp.server"; // SMTP servers
  7. $mail->SMTPAuth = true; // turn on SMTP authentication
  8. $mail->Username = "me@localhost"; // SMTP username
  9. $mail->Password = "123456"; // SMTP password
  10.  
  11. $mail->From = "myemail@localhost";
  12. $mail->FromName = "My Name";
  13.  
  14. // 執行 $mail->AddAddress() 加入收件者,可以多個收件者
  15. $mail->AddAddress("to@email.com","Josh Adams");
  16. $mail->AddAddress("to2@email.com"); // optional name
  17.  
  18. $mail->AddReplyTo("jyu@aemtechnology.com","AEM");
  19.  
  20. $mail->WordWrap = 50; // set word wrap
  21.  
  22. // 執行 $mail->AddAttachment() 加入附件,可以多個附件
  23. $mail->AddAttachment("path_to/file"); // attachment
  24. $mail->AddAttachment("path_to_file2", "INF");
  25.  
  26. // 電郵內容,以下為發送 HTML 格式的郵件
  27. $mail->IsHTML(true); // send as HTML
  28. $mail->Subject = "testing email";
  29. $mail->Body = "This is the <b>HTML body</b>";
  30. $mail->AltBody = "This is the text-only body";
  31.  
  32. if(!$mail->Send())
  33. {
  34.     echo "Message was not sent <p>";
  35.     echo "Mailer Error: " . $mail->ErrorInfo;
  36.     exit;
  37. }
  38.  
  39. echo "Message has been sent";
  40. ?>

August 20, 2007 · 程式設計分享 · Comments (1)

開發 PHP5 的多工應用

一直我也以為 PHP 沒有支援像 Java 或 C++ 的 threading 的功能,所以不可以寫到 multi-task (多工) 的應用程式。例如當應用程式需要擷取其他網站的內容,應用程式會延遲執行,直至完成擷取遠端的資料為止。原來現在已經可以用 stream_select 及 stream_socket_client 實現 PHP multitasking。

這篇在 developerWorks 的文章介紹了在 PHP 的 multitasking 及 threading:

Develop multitasking applications with PHP V5

昨天的股市真的如坐過山車,我只在收市看見點數跌二百多點,那時以為跌得不多,誰知原來曾跌過 1285 點。無論如何,自己也沒有在這次調整估貨,反而會看看星期一有沒有買貨的機會。我的兩隻千里馬招商銀行 (3968) 及平安保險 (2318) 公佈了中期業績,也交出了理想的成績單,對於有實質盈利支持的股份,在跌市時才也會較有信心。

August 18, 2007 · 程式設計分享 · Comments (1)

讓 crontab 自動排程執行 php

要用 crontab 自動執行 php 程式,可以這樣做:

方法一
1. 在 php 程式的第一行加入:

#!/usr/local/php/bin/php -q

例如:

PHP:
  1. #!/usr/local/php/bin/php -q
  2. <?php
  3. $foo = 123;
  4. ?>

請留意,我的 php 是安裝在 /usr/local/php,請根據你的 php 執行檔位置作出修改。

2. 將 php 程式給予可執行權限:

chmod +x testing.php

3. 執行 crontab -e,然後加入以下內容:

00 00 * * * /path/to/testing.php > /dev/null 2>&2

以上語法會在每天的零時零分執行 /path/to/testing.php

方法二
另一個方法是不用在 php 程式的第一行加入 "#!/usr/local/php/bin/php -q",可以省略第一步及第二步,直接執行 crontab -e,並輸入以下內容:

00 00 * * * usr/local/php/bin/php -q /path/to/testing.php > /dev/null 2>&2

這個方法的結果跟方法一的結果相同。

August 9, 2007 · 程式設計分享 · Comments (1)

User-Agents 列表

這個列表提供了多種 browsers, search engines spiders, web directories, download managers, link checkers, proxy servers, web filtering tools, harvesters, spambots, badbots 的 User-Agents 字串。當要開發一些程式辨認 user agents 時,這個列表會十分有用,尤其是一些自己沒有使用的 OS 下的 browsers。

List of User-Agents (Spiders, Robots, Crawler, Browser)

PHP4 將停止開發

PHP5 已經推出了 3 年,而 PHP 的開發團隊也一直建議將 PHP4 的程式轉換到 PHP5,而 PHP6 也已經在開發中。PHP.net 正式宣佈將會在今年年底停止開發 PHP4,之後便不會再推出 PHP 4.4.x 的新版本,而 PHP4 的安全性更新會直至到 2008 年 8 月 8 日。

PHP5 最大的問題是兼容性,舊有的 PHP4 應用程式大都不能正確在 PHP5 的伺服器上執行。因為現時大多數網站的現有應用程式是用 PHP4 開發,所以使到很多網存商不將 PHP 的版本升級。

PHP.net 提供幾篇不同的升級指引,對重寫 PHP 應用程式很有幫助:

PHP 4 to PHP 5
PHP 5.0.x to PHP 5.1.x
PHP 5.1.x to PHP 5.2.x

July 15, 2007 · 程式設計分享 · No Comments Yet


Zend Framework 1.0.0 釋出

Zend Framework 1.0.0 已經釋出,我也相信 Zend Framework 是最好的 PHP5 framework。但可惜它是 PHP5 的 framework,現時我多數的 projects 還是用 PHP4 來開發。(未知 Zend 是否想借此推動更多人轉用 PHP5)

Zend Framework 提供了開發網頁應用程式的一些常用功能,例如 authentication/authorization classes, input filtering, Advanced I18N 支援, 資料庫存取及相容 Lucene 搜索引擎等。

下載 Zend Framework 1.0.0

July 4, 2007 · 程式設計分享 · No Comments Yet

PHP 編寫 BBCode 函式

現在一些主流的論壇或 Blog 回應,也是用 BBCode 作為更改文字式樣的語法。因為 BBCode 一般上只可以定義粗體、斜體、加底線、文字顏色及插入超連結等,而不可以插入 html tags 及 javascript,以下是用 PHP 製作 BBCode 函式的方法。

首先第一步是要將 html tags 轉換,例如 '<' 轉換成 '&lt;',這個可以用 htmlentities() 函式實現:

PHP:
  1. <?php
  2. function bbcode_convert($string){
  3.     return htmlentities($string, ENT_QUOTES);
  4. }
  5. ?>

然後便要編寫字體式樣的部份,包括有[b]、[i]、[u]、[ur] 及 [img],這裡開始要用正規表達式來做:

PHP:
  1. <?php
  2. function bbcode_convert($string){
  3.     // 移除 HTML tags
  4.     $string = htmlentities($string, ENT_QUOTES);
  5.  
  6.     // 處理 [b] 及 [/b] 的粗體字
  7.     $string = preg_replace ('/\[b\](.*?)\[\/b\]/is', '<strong>$1</strong>', $string);
  8.     // 處理 [i] 及 [/i] 的斜體字
  9.     $string = preg_replace ('/\[i\](.*?)\[\/i\]/is', '<em>$1</em>', $string);
  10.     // 處理 [u] 及 [/u] 的底線字
  11.     $string = preg_replace ('/\[u\](.*?)\[\/u\]/is', '<u>$1</u>', $string);
  12.  
  13.     // [url] 超連結
  14.     $string = preg_replace('/\[url\](.*?)\[\/url\]/is', '<a href="$1">$1</a>', $string);
  15.     // [url=url] 超連結
  16.     $string = preg_replace('/\[url\=(.*?)\](.*?)\[\/url\]/is', '<a href="$1">$2</a>', $string);
  17.  
  18.     // [img] 圖片
  19.     $string = preg_replace('/\[img\](.*?)\[\/img\]/is', '<img src="$1" />', $string);
  20.  
  21.     return $string;
  22. }
  23. ?>

現在已經完成了最基本的 BBCode,但可以將以上程式碼簡化,還可以選進執行效能。以上總共呼叫了 6 次 preg_replace() 函式,而實際上 preg_replace() 是可以用 array 作為搜索字串及替換字串的,所以可以改為只呼叫 preg_replace() 函式兩次,那麼程式碼會這樣:

PHP:
  1. <?php
  2. function bbcode_convert($string){
  3.     // 移除 HTML tags
  4.     $string = htmlentities($string, ENT_QUOTES);
  5.  
  6.     $bbcode_search = array(
  7.                 '/\[b\](.*?)\[\/b\]/is',
  8.                 '/\[i\](.*?)\[\/i\]/is',
  9.                 '/\[u\](.*?)\[\/u\]/is',
  10.                 '/\[url\=(.*?)\](.*?)\[\/url\]/is',
  11.                 '/\[url\](.*?)\[\/url\]/is',
  12.                 '/\[img\](.*?)\[\/img\]/is'
  13.                 );
  14.  
  15.     $bbcode_replace = array(
  16.                 '<strong>$1</strong>',
  17.                 '<em>$1</em>',
  18.                 '<u>$1</u>',
  19.                 '<a href="$1">$2</a>',
  20.                 '<a href="$1">$1</a>',
  21.                 '<img src="$1" />'
  22.                 );
  23.  
  24.     return preg_replace($bbcode_search, $bbcode_replace, $string);
  25. }
  26. ?>

這個 BBCode 函式已經大致上完成,你可以按照自己的需要加入各種語法,原理與以上的做法相同。

May 27, 2007 · 程式設計分享 · Comments (1)

15 個免費 SQL Injection Scanners

現時很多網站應用程式也有用資料庫儲存資料,而應用程式被攻擊的一個常見漏洞是 SQL Injection。SQL Injection 是使用者輸入的資料中夾帶 SQL 指令,在設計不良的程式忽略了檢查,這些夾帶進去的指令就會被資料庫伺服器誤認為是正常的SQL指令而執行,因此招致到破壞。以下是 15 個免費的 SQL Injection Scanners:

-- SQLIer
-- SQLbftools
-- SQL Injection Brute-forcer
-- SQLBrute
-- BobCat
-- SQLMap
-- Absinthe
-- SQL Injection Pen-testing Tool
-- SQID
-- Blind SQL Injection Perl Tool
-- SQL Power Injection
-- FJ-Injector Framwork
-- SQLNinja
-- Automagic SQL Injector
-- NGSS SQL Injector

May 22, 2007 · 程式設計分享 · No Comments Yet

無法存取 php.ini 下更改其設定值

php.ini 內有很多設定值,如果無法更法 php.ini 而需要更改某些設定值的話,可以透過 PHP 程式或 .htaccess 來實現。

PHP

PHP:
  1. <? ini_set("magic_quotes_gpc", "1"); ?>

以上程式碼會開啟 magic_quotes_gpc。

.htaccess
用 .htaccess 來實現更加方便,因為整個目錄內也會生效,在 .htaccess 加入:

php_value magic_quotes_gpc 1

以上使用了 php_value 來設定 magic_quotes_gpc,並定義它的值為 1 (即開啟)。

這個方法是有限制的,例如 safe_mode 及 safe_mode_exec_dir 這類 functions 就不可以修改了。

May 20, 2007 · 程式設計分享 · Comments (3)

PHP: 追蹤上傳檔案進度

現時用 PHP 編寫上傳檔案的功能時,如果檔案體積較龐大,或者使用者與伺服器端的連線較慢,這樣上傳便要等一段頗長的時間,而且最慘是使用者根本不知還要等多久,以及已經上傳進度完成了多少。幸好在 PHP 5.2 支援檢查檔案上傳進度的功能,可以給使用者看到實時上傳進度。這篇在 IBM DeveloperWorks 的文章介紹了用 $_POST 陣及 APC_UPLOAD_PROGRESS 製作上傳實時進度的方法:

What's new in PHP V5.2, Part 5: Tracking file upload progress

May 20, 2007 · 程式設計分享 · No Comments Yet


« Previous Page  Next Page »