星期三, 4月 18, 2012

網站上線前測試項目

javascript測試事項
  • 是否支援json
    //檢查json是否存在
    if (typeof (JSON) == 'undefined') { //沒有 JSON 時才讓 browser 下載 json2.js
        $('head').append($("<script src="json2.js" type="text/javascript">
    ));
    
    }
  • 兼容性测试
    不同browser都要試一下

unit test測試事項
  • 邊界值及最大、最小值

get reals一書提到...

對於每一個新功能你需要……
  • 1. 對它說不
  • 2. 強迫它證明自己的價值
  • 3. 如果得到否定的答案,就此打住。如果是yes,繼續往下……
  • 4. 為界面繪製草圖
  • 5. 設計界面
  • 6. 編寫代碼
  • 7-15. 測試,改進,測試,改進,測試,改進,測試,改進……
  • 16. 檢查幫助文字是否需要修改
  • 17. 更新產品預覽流程(如果有必要的話)
  • 18. 更新用於銷售的拷貝(如果有必要的話)
  • 19. 更新服務條款(如果有必要的話)
  • 20. 檢查是否違背之前的任何許諾
  • 21. 檢查價格體系是否受影響
  • 22. 上線
  • 23. 深吸一口氣

星期六, 3月 17, 2012

firefox同步

這實在太強大了...
之前有擴充套件(add-on)可以同步記錄書籤
但現在firefox自己出了"選項/同步",只能記錄書籤已經不夠看了

試用了一下,真的是太棒了
除了書籤外,最重要的是每次換台新電腦就得要重安裝套件
居然連這也能同步,太強了... 我要按個讚

後記...
firefox不知為何在2012.7常當掉
發現是在輸入項(input)時,很容易掛
因為太頻繁了,所以只好先改用chrome

用完Chrome後...
好吧... 我改用Chrome了
因為browser是綁gmail帳號
chrome就自動把書籤、autocompleted都同步了...
firefox強項剩firebug...

星期五, 3月 09, 2012

linux prompt

  1. 設置檔
    • 全users
      /etc/profile or /etc/bashrc
    • 個別user
      ~/.bash_profile , ~/.bash_login , ~/.profile , ~/.bashrc or ~/.bash_logout
  2. 客製化prompt
    PS1='[\u@\h \w] \$ # ' #即為user@host ~

    PS1="\e[\u@\h \w]$ \e]" #即為[user@host ~]
    加框'[', ']',由於是key words所以要加\e
    而0;32m 是指顏色,其他以此類推應該就看的出來了
  3. 加上顏色
    PS1="\e[0;32m[\u@\h \w]\e]$ \e[m]" #即為[user@host ~]
  4. 啟使
    source .bashrc
    or
    . .bashrc
  5. Changing foreground and background bash prompt colors

    Syntax for changing colors in the bash is as follows:
    \033[ -> Indicates the beginning of color in the text
     x;yzm - Indicates color code
     \033[00m - Indicates the end of color in the text  

截錄常用的字元代表意思
Bash special characterBash special character explanationBash special characterBash special character explanation
\] end a sequence of non-printing characters \[ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
\h the hostname up to the first `.' \H the hostname
\s the name of the shell, the basename of $0 (the portion following the final slash) \l the basename of the shell's terminal device name
\$ if the effective UID is 0, a #, otherwise a $ \u the username of the current user
\w the current working directory \W the basename of the current working directory
\D{format} the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required

個人配置檔
#prompt
if [ $TERM = 'xterm' ]
then
        PS1='\e[0;32m[\[\033[02;32m\]\u@\h\[\033[01;34m\] \w\e[0;32m]\$\e[m '
else
        PS1='[\u@\h \w] \$ # '
fi

# colorful man page 
export PAGER="`which less` -s"
export BROWSER="$PAGER"
export LESS_TERMCAP_mb=$'\E[01;36m'
export LESS_TERMCAP_md=$'\E[01;36m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;33m'

References

Bash prompt basics

星期二, 3月 06, 2012

FirePHP no message in FireBug console

忘記更新了什麼東西,結果FirePHP居然沒反應了
goolge了一下,也有人遇到,印象中是更新了FirePHP的套件就解決了

而最近公司更換網域,環境也跟著改變
重新安裝FireBug及FirePHP後,居然又沒反應了
又找不到原本解決的網頁,真是快瘋了

後來注意到firefox有個提醒列
提到要"enable Net Panel ..."
才去開放script及net panel,如下圖

才知道FirePHP需要開啟net panel才能動....

星期四, 2月 23, 2012

What is my IP? (Public IP address)

Using wget
wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'
Using curl
curl -s checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'

curl -s http://whatismyip.org/
Using Lynx
lynx -dump checkip.dyndns.org

lynx -dump www.whatismyip.com | grep 'Your IP'
Reference Linux command: What is my IP? (Public IP address)

星期二, 2月 21, 2012

mysql grant

最近一個案子要連到廠商的db讀資料
不過不知卡在什麼地方,一直沒辦法連到db
後來想到是mysql沒開遠端連線的權限,想透過phpmyadmin去開
但是限制一堆,只能用ssh進mysql server下指令...
用慣了phpmyadmin.... 要用指令下授權...ㄟ... grant all db.... 什麼.... 放棄
下select就算了,下授權... 不知多久才用一次的東西...google一下吧..
  • 先連db囉
    $ mysql -u root -p
  • 查詢 某 User 的權限
    這樣就可以知道該User是否有從某ip連db的權限
    mysql> select User,Host from mysql.user;
    +------+---------------------------+
    | User | Host |
    +------+---------------------------+
    | root | localhost |
    +------+---------------------------+
    1 rows in set (0.00 sec)

  • add SELECT,INSERT privileges to a user using GRANT
    上例中,root未開放192.168.0.1的連線
    這裡假設開放root(密碼:ok1234)可從192.168.0.1連線db_base下的所有table(利用*來代表所有的table)的權限
    GRANT SELECT,INSERT ON db_base.* TO root@192.168.0.1 IDENTIFIED BY 'ok1234';

References

git增減remote及fetch and pull branch


  • 增加一個remote
    //增加一個在github的remote
    git remote add github https://github.com/username/Hello-World.git
    
    //origin也視成一個remote,所以一樣的方法,只是叫origin
    git remote add origin https://github.com/username/Hello-World.git

當origin或remote有local沒有的branhc要如何抓下來
  • 自己的
    #git branch
    * master
  • Origin或remote的
    #git branch
    check
    * master
  • 利用fetch抓回來
    #git fetch origin check:check 

星期五, 2月 10, 2012

ie中session遺失問題

先前寫個cross site的程式給廠商呼叫
結果最近在說只有ie會掛,firefox, chrome都通過
一試之下,還真的同事的全掛,最有趣的是我的ie卻能過
且我ie 7,8,9全試了,都可以,為什麼.. 還沒查出來

因為ie不能看iframe裡的內容,而自己的電腦又不會有問題
只能請同事看,查到快起肖了
最後發現是session值會不見

看到有人提到session的useragent不同,而ci裡的config會比對,只要關掉即可
可是還是失敗,總之查了半天,突然看到P3P的字眼...
才想到以前也有遇到ie跨網域取不到相關值的問題,加上後就解決了
friday night加班到9點...更~~~~~~~~~~~~

網上有人整理好了
  • How to set p3p http header in ASP.Net?
    HttpContext.Current.Response.AddHeader("p3p", "CP=\""IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""")
  • How to set p3p http header in PHP?
    header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
  • How to set p3p http header in JSP?
    response.setHeader("P3P","CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'")
  • How to set p3p http header in ColdFusion?
    <cfheader name="P3P" value="CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'">

References

星期四, 2月 09, 2012

利用 php 本身寫 error log 及 error/warning/notice message

  • error_reporting
    設定php回發生錯誤的等級
    error_reporting(0);  // Turn off all error reporting
    ini_set('error_reporting', E_ALL);  // Same as error_reporting(E_ALL);
  • error_log
    bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )
    Sends an error message to the web server's error log or to a file.
    需寫入file,因此需指定file path
    用法
    //log to file
    ini_set('error_log', dirname(__FILE__) . '/error_log.txt');  
    
    // Send notification through the server log if we can not
    // connect to the database.
    if (!Ora_Logon($username, $password)) {
        error_log("Oracle database not available!", 0);
    }
    
    // Notify administrator by email if we run out of FOO
    if (!($foo = allocate_new_foo())) {
        error_log("Big trouble, we're all out of FOOs!", 1,
                   "operator@example.com");
    }
    
    // another way to call error_log():
    error_log("You messed up!", 3, "/var/tmp/my-errors.log");
    
  • error/warning/notice message
    定義log level多配合log4php,不過也可透過trigger_error
    即可靠php本身達成此效果
    trigger_error("Notice Message",E_USER_NOTICE);
    trigger_error("Warning Message",E_USER_WARNING);
    trigger_error("Error Message",E_USER_ERROR);
    如此就不用再掛log4php,就能方便帶訊息
也就是說error_report 是設定php觸發回報錯誤的等級
如果想利用此機制寫自定的訊息就可透過trigger_error
而error_log就自己想log什麼就log什麼

error_report設定篇
開啟是否顯示error及log的等級
  • 在php.ini中設定
    display_errors = On 
    
  • 在.php中設定
    每次要到php.ini設定就太累了,這邊有方法可以直接在.php裡,直接設定log,這樣開發起來就方便多了,且不會動到整體環境
    ini_set('display_errors', 1);   //turn on display error on screen
    ini_set('log_errors', 1);     //turn on log error
    error_reporting(E_ALL); //log all errors and warnings


常見常數定義
列出常見的幾個,其他看官網Predefined Constants
Constant Description Note
E_NOTICERun-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.
E_STRICTEnable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.Since PHP 5 but not included in E_ALL until PHP 5.4.0
E_ALLAll errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.

References

星期日, 1月 29, 2012

亂數order id

最近在寫銷售系統,由於會把order id給客戶,主管反應這樣會被會看出銷售量,所以要改成亂數,避免競爭對手等看出銷售數量。

研究了半天,自己用padding、加亂數的方法似乎還是會被察覺,google後,覺得還是用加密比較簡單

  • two way encryption
    先下載加密法encryption_class.php
    在encryption_class.php裡,有以下兩行
    $this->scramble1 = '! #$%&()*+,-./0123456789:;>=<?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~';
    $this->scramble2 = 'f^jAE]okIOzU[2&q1{3`h5w_794p@6s8?BgP<dFV=m D>TcS%Ze|r:lGK/uCy.Jx)HiQ!#$~(;Lt-R}Ma,NvW+Ynb*0X';
    此加密法是簡單的利用代換字母做加密,記得叫Caesar Cipher什麼的,主要利用自己的key,去對應scramble相同字母的位置
    當然這樣1對1的對應,很容易就被破,所以裡面的function _applyFudgeFactor(),就是在每次計算代換字母就偏移順序
    利用scramble1把key轉換成順序,每次再偏移位置,從scramble2取出該字母當祕文
  • 產生加密後的order id
    <?php
    include 'encryption_class.php';
    
    $crypt = new encryption_class(); 
    
    $key = "A-COMPLETELY-RANDOM-KEY-THAT-I-HAVE-USED";
    // Min length of 8 for encrypted string
    $min_length = 8;
    
    $order_id = 123456789;
    
    print "Original: " . $order_id . PHP_EOL;
    
    $encrypt_result = $crypt->encrypt($key, $order_id, $min_length); 
    
    print "Encrypted: " . $encrypt_result . PHP_EOL;
    
    // DECRYPT
    $decrypt_result = $crypt->decrypt($key, $encrypt_result);
    
    print "Decrypted: " . $decrypt_result . PHP_EOL;
    
    ?>
    結果如下
    Original: 123456789
    Encrypted: 2UD5UIK9S
    Decrypted: 123456789

  • 以數字實作
    不過問題又來了,因為order id用integer,所以要求全是數字
    • 轉ascii code
      就直接全轉3位數的ascii code

      $numeric_cipher='';
      for($i=0;$i<strlen($decrypt_result);$i++){
          $numeric_cipher .= str_pad(ord(substr($decrypt_result,$i,1)),3,'0',STR_PAD_LEFT); //不到3碼,左邊補0至3碼
      }
      

      不過實在太長了,5位數就要長到15個數字
      所以ascii百位數後全不用,即d(100),e(101),...
      這樣padding就只要2位,這樣5位數也只要10個數字
    • 還嫌太長!?最終極版大絕!!!
      由於key是對應scremble的排序...
      把key跟scremble都只放數字,這樣............ 應該夠短了吧...
      就是有點容易猜...不過一時間內應該也夠用了
      order id太長,將來要查也不好查
      • 改encryption_class.php
        //把scramble改成如下,不要重覆,順序可亂擺,不要一樣就好
        $this->scramble1 = '0123456789';
        $this->scramble2 = '2135794680';
      • 改key值
        因為要對應scramble,所以key有什麼值,scramble就要有什麼值,否則對應不到
        至於密文min length長度,當超過明文長度時,預設是在字串後方補上空格
        但因為得全為數字,所以scramble沒有空格,造成空格對應不到,因此不能超過order id的長度

        //key可隨意變化,但key的值一定要出現在scramble裡
        $key='1234534567890';   
        $key='11223344';   
        $key='68490';   
        
        $min_length = strlen($order_id); //因為1對1,所以不能超過order id的長度
        
      結果如下
      OriginalEncryptedDecrypted
      151
      70
      115011
      991999
      100583100
      101585101
      110505110
      111507111
      這就可以看出來,當key、scramble、偏移量相同,位於前面的字母相同時,代碼都會相同,變化不夠大,忘了那資安的名詞叫什麼,意思是當原文變化不大時,密文的變化仍要夠大,如md5等
      因為可變化的太少了,不過應該算堪用了
      另外還有兩個問題
      • original為7時,沒辦法反解
        原作者在decrypt用empty,所以遇到0會當false,改!isset即可
        相同的,當encrypt 0時,也會當成false,也需要改成!isset
      • decrypt result為0xx
        雖是正常,不過ordre id用integer,這個0就會不見,到時會解不回去
      min length問題
      由於是全數字,又密文長度不能超過明文長度,實在容易被猜出來
      那如何超過明文長度咧...
      解法:不補空格,補0,在明文字串前方補足0,由於integer前面有0,也是當成0,所以沒差
      ex. $id = 50; $min_length = 4;
      $id = '0050'; // 補2個0,足4位
      在encryption_class.php裡
      function encrypt(){
          ...
          //$source = str_pad($source, $sourcelen);              //原作法
          $source = str_pad($source, $sourcelen, '0', STR_PAD_LEFT); //新的作法
          ...
      


References
Four ways to generate unique id by PHP
How to generate Unique Order Id (just to show touser) with actual Order Id?

星期四, 1月 19, 2012

該死的ie form

在html包form實在是在平常不過的事了
在firefox, chrome都跑的好好的
沒想到ie跑版,馬上開F12來看一下
天殺的那是在iframe裡... 要到該網頁又要帶參數....好想殺人
查了半天的css實是看不出原因

亂搬了一下form,居然有變化了
最後把margin設為0... 更.. 好了....
同事事後也說,他也遇過,說這form實在很奧妙....

忘了是ie什麼版本影響了... 總之先記下來
ie我恨你...

星期日, 1月 15, 2012

PHP5.3, CentOS,裝Oci8, pdo_oci8

沒連過oracle,一開始要用還真搞不太懂
載了2個檔案,共2G回來,還是不會用
最後看只需載個client的basic,供oci連線即可
看完網路一裝教學,還是裝不起來,在交叉比對下,終於成功了~~~

os: CentOS 6.4
php: 5.3
download Instant Client Downloads
自己的環境是linux 64bit, 所以載了 Instant Client for Linux x86-64
  1. Install oracle instant client
    • oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
    • oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm
    • oracle-instantclient11.2-sdk-11.2.0.1.0-1.x86_64.zip
    # rpm -ivh oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
    # rpm -ivh oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm
  2. 設定ORACLE_HOME
    設定ORACLE_HOME的提示真是讓我暈倒,說要指到lib
    設好了,但在install oci時,會掛,最後試出只要到"HOME"就好了
    看下面設定 vi /etc/profile
    export ORACLE_HOME=/usr/lib/oracle/11.2/client64
    export ORACLE_OWNER=oracle
    export ORACLE_SID=ora1
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib
    export PATH=$ORACLE_HOME/bin:$PATH
    export TNS_ADMIN=$ORACLE_HOME/network/admin
    export NLS_LANG="AMERICAN_AMERICA.AL32UTF8"
    啟動環境變數
    source /etc/profile
  3. 解壓sdk並把裡面的sdk裡的資料複製到/usr/include
    # unzip oracle-instantclient11.2-sdk-11.2.0.1.0-1.x86_64.zip 
    # cp -fr instantclient_11_2/sdk/include/* /usr/include
  4. install oci
    • Installing OCI8 from PECL 
      • Use 'pecl install oci8' to install for PHP 8.
      • Use 'pecl install oci8-2.2.0' to install for PHP 7.
      • Use 'pecl install oci8-2.0.12' to install for PHP 5.2 - PHP 5.6.
      • Use 'pecl install oci8-1.4.10' to install for PHP 4.3.9 - PHP 5.1.

      p.s. 基本上裝最新版即可,它有向下相融
            就這麼簡單,過程會要求輸入ORACLE_HOME的位置,如果第3步有做的話,就按enter即可 如果找不到pecl,就先安裝pear

      yum install php-pear
      #如果找不到的話,就先增加repository
      rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm
      yum --enablerepo=webtatic install php-pear

  5. 設定php.ini
    vi /etc/php.ini , add the line extension=oci8.so
    再重開apache即可
    # service httpd restart

    這時下php -m 就會看到oci8了~ 開心
  6. 測試
    <?php
    $option = array(
        'ip'            => '10.0.3.20',
        'port'          => '15210',
        'account'       => 'web',
        'password'      => 'FEF00CB',
        'service_name'  => 'WXS4'
    );
    
        $db = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={$option['ip']})(PORT={$option['port']}))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={$option['service_name']})))";
    
        if(function_exists('ocilogon')){
            $c1 = ocilogon($option['account'],$option['password'],$db) or die('OCI Connect error, wrong connection string');
            echo 'OCI Connect pass. yes!!!';
        }else{
            echo 'ocilogon not exists, installment is not correct';
        }
有看到某些文章指出要安裝pdo,自己裝了也一直失敗
後來發現php5.3已經有了,所以不用裝了

全手動安裝

在公司封閉的網路,只能手動安裝可以參考這篇 PHP 5.3 連線 Oracle 的客戶端及 PDO_OCI 模組安裝

issue
  • pdo_oci unsupported oracle version 
由於oracle instantclient可能出了新版,而pdo_oci未更新,可以直接改pdo_oci/config.m4 ,自己加上要的版本,search 一下unsupported version字眼,就可以找到,詳細可參考這篇 

p.s. 改完記得要先phpize --clean,不然configure的內容不會生效哦!!!

星期三, 1月 11, 2012

教授比較強!?

以前唸專科時,學校裡有教授頭術及碩士畢業的講師
曾經有個交大畢業的碩士講師跟我說過
有些學生比較看不起講師,覺得教授等級才夠看

專科時期,算是個人進入資訊領域的起萌期
老師個人當然還是有強弱,不過都覺得可學習的滿多的
也沒有感覺有沒有教授的頭銜有什麼差別

後來進了大學
老師都至少助理教授以上等級,且大多為40多歲以上
且教授等級的老師在業界或學術界都頗具名氣
聽課時,就真的覺得有差,除了講義上的東西,還可以講的更深入
一些理論的東西,也能講的比較活,感覺比較實用

有位教授說了句玩笑話:「教授就是專門把簡單的東西教的很難。」
原本只是會心一笑,後來才體會到,教授已經多年研究這領域,且每年都重複教這東西,已經成精了,而我們這些小毛頭,一時要聽懂,真的不是件容易的事。

所以...
碩士畢業的講師不敢說弱
只能說教授真的滿強的...

星期六, 1月 07, 2012

tmux改 screen 256 color

改了tmux的設定後,發現顏色沒有改
查了一下,知道可用tput color來看
只有8色,不支援256
可在config裡給screen-256color
set -g default-terminal "screen-256color"

不過開vim時,卻發生Terminal entry not found in terminfo 'screen-256color' not known
所以讀預色的ansi
搞的vim都沒顏色了,而且很多vim指令不能下

又看了一下要用
export TERM=screen-256color

不改還好,一改連tmux也進不去
出現 missing or unsuitable terminal: screen-256color

想改回去 已經不知原本的值了
幸好另一台server也有灌,看了原來本的設定是
TERM=screen
改回來就進tmux了

結論...
還是沒顏色... 有改回來就偷笑了
不過應該centos 沒有screen-256color這東西
想辦法搞定,應該就能work了

References

星期四, 1月 05, 2012

ci取db錯誤

codeigniget在db出錯時,會自行印出錯誤訊息,如果要關掉有兩種方法
  • config/database.php設定
    $db['default']['db_debug'] = TRUE;
  • 程式裡設定
    $this->db->db_debug = false;  
關掉錯誤訊息,那如何取得錯誤訊息咧
$this->db->_error_message(); 
因為不管關不關錯誤訊息try-catch都抓不到
所以如要判斷中斷程式得利用affected row
ci論談已經有人寫好function,可配合暫時關掉錯誤訊息,中斷和印出錯誤訊息
function insert_quiet($table = ‘’, $set = NULL)
  {
      $oldv =$this->db_debug;
      $this->db_debug = false;     
      $this->insert($table, $set);
      $e = $this->_error_message();
      $aff = $this->affected_rows();
      $this->db_debug = $oldv;
      if($aff < 1) {
        return($e);
      } else {
        return(true);
      }
  }
Reference

星期四, 12月 22, 2011

轉:Setting up an SSL secured Webserver with CentOS

在apache裡建https就這麼簡單...
  1. Getting the required software
    yum install mod_ssl openssl
  2. Generate a self-signed certificate
    # Generate private key 
    openssl genrsa -out ca.key 1024 
    
    # Generate CSR 
    openssl req -new -key ca.key -out ca.csr
    
    # Generate Self Signed Key
    openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt
    
    # Copy the files to the correct locations
    cp ca.crt /etc/pki/tls/certs
    cp ca.key /etc/pki/tls/private/ca.key
    cp ca.csr /etc/pki/tls/private/ca.csr
  3. Setting up the virtual hosts
    #vim /etc/httpd/conf.d/ssl.conf
    -----------------------------
    #將<virtualhost>裡的內容修改為以下...
    <virtualhost *:443>
        SSLEngine on
        SSLCertificateFile /etc/pki/tls/certs/ca.crt
        SSLCertificateKeyFile /etc/pki/tls/private/ca.key
        <Directory /var/www/vhosts/yoursite.com/httpsdocs>
            AllowOverride All
        </Directory>
        DocumentRoot /var/www/vhosts/yoursite.com/httpsdocs
        ServerName yoursite.com
    </VirtualHost>
  4. Configuring the firewall
    yum install mod_ssl openssl

Reference

星期五, 12月 16, 2011

mysql存日期該用什麼data type

mysql存日期的data type有好幾種type,用int存秒數也是一種
一直很猶疑要用哪一種,想法是byte越少越好
所以整理了一下
TypeStorage(Bytes)Minimum Value(Signed/Unsigned)Maximum Value(Signed/Unsigned)
DATE3 bytes
TIME3 bytes
DATETIME8 bytes
TIMESTAMP4 bytes
YEAR1 bytes
INT4-21474836482147483647

所以我想... 利用INT存比較快吧...
created date就用int來存秒數,轉換日期就利用FROM_UNIXTIME(seconds)
last updated date就用timestamp來存,反正一樣大,而且會自動更新
References

星期四, 12月 15, 2011

active record使用memcached

一直用sql當memcached的key跑的順順的
不過最近在用ci在開發,發現用的active record不知抓什麼來當key
研究了一下,發現有last_query()可取出sql string
不過又看了一下發現是先execute後,才會有的query

而cache當然是要跑之前做,不然就沒有意義了
又serach了一下,發現有_compile_select()
差別當然在有執行跟沒執行,以下是片斷程式碼
有引用tomschlick寫好給ci用的memcached-library
 $key = $this->db->_compile_select();
$this->load->library('Memcached_library','','memcached');
$results = $this->memcached->get($key);

// If the key does not exist it could mean the key was never set or expired
if ($results) 
     echo 'hit';
else{
     echo 'miss';
     $results = $this->db->get()->row_array();
     $this->memcached->add($key, $results);
}
不過每個有用db的程式這樣寫太麻煩了
原本想改寫ci的db driver,看起來有點麻煩,先求有吧
所以先簡單的寫在helper裡,有空再來研究改寫driver
_compile_select());
        $ci = & get_instance();
        $ci->load->library('Memcached_library','','memcached');
        $results = $ci->memcached->get($key);

        // If the key does not exist it could mean the key was never set or expired
        if ($results) {

                $ci->fb->info('[memcache] hit', "info");
        }else{

                $ci->fb->warn('[memcache] miss', "memcached");
                $results = $db->get()->row_array();
                $ci->memcached->add($key, $results);
        }

        $db->_reset_select();  //clear sql query string
        return $results;
}
References Getting CodeIgniter Active Record's current SQL code

星期一, 12月 12, 2011

檢查遠端的檔案是否存在

這方法還不錯,只回傳header,不看body
function remoteFileExists($url) {
    $curl = curl_init($url);

    //don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
    echo 'file exists';
} else {
    echo 'file does not exist';   
}
Reference

星期二, 12月 06, 2011

CodeIgniter - db active record常用指令

  • basic
    • 取得config中,名為group_one的db
      $DB1 = $this->load->database('group_one', TRUE); //給true才會產生實體給$DB1
      $this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);
      
      p.s. 給true才會回傳個db object
    • 取sql string
      • last_query()
        執行的過程中,最後的一個sql query string
      • _compile_select()
        目前sql條件的sql query string,尚未實際執行
  • select
    $this->db->select('title, content, date'); //不下的話就是*
    $query = $this->db->get('mytable');
    foreach ($query->result() as $row)
    {
        echo $row->title;
    }
    
  • from、join
    $this->db->from('mytable');
    $this->db->select('*');
    $this->db->from('blogs');
    $this->db->join('comments', 'comments.id = blogs.id');
    
    $query = $this->db->get();
    
    // Produces:
    // SELECT * FROM blogs
    // JOIN comments ON comments.id = blogs.id
  • where 
    //法1.
    $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
    $this->db->or_where('id >', $id);  // Produces: WHERE name != 'Joe' OR id > 50
    
    //法2
    $this->db->select('title')->from('mytable')->where('id', $id);
    
  • insert
  • 新增欄位為now()的方法
    $data = array (
       'customer_id'=> $customer_id,
       'total' => $totalprice
      );
      $this->db->set('order_date', 'NOW()', FALSE);
      $this->db->insert('omc_orders', $data);


Reference