顯示具有 codeigniter 標籤的文章。 顯示所有文章
顯示具有 codeigniter 標籤的文章。 顯示所有文章

2022年8月3日 星期三

PHP 開發筆記 - 關於 CodeIgniter4 starter app / PHP Coding Standards Fixer v3.9.5 / PHP 7.4 @ macOS 與 Windows

之前初探 PHP Coding Standards Fixer (php-cs-fixer) 時,略知預設跑下去已經有一定水準的 Coding Style 制約機制,然而,工作上引導同事在使用時,碰到了一些雷區。

首先是用 CodeIgniter 4 官方文件建立出的資料後,要跑 PHP Coding Standards Fixer 時會出現要修正語法的問題

```
// https://www.codeigniter.com/user_guide/installation/installing_composer.html
% composer create-project codeigniter4/appstarter project-root
% ./vendor/bin/php-cs-fixer fix --dry-run -v .
PHP CS Fixer 3.9.5 Grand Awaiting by Fabien Potencier and Dariusz Ruminski.
PHP runtime: 7.4.30
Loaded config CodeIgniter4 Coding Standards from "/path/./.php-cs-fixer.dist.php".
Using cache file ".php-cs-fixer.cache".
Paths from configuration file have been overridden by paths provided as command arguments.
.....F......................................F.............                                                                            58 / 58 (100%)
Legend: ?-unknown, I-invalid file syntax (file ignored), S-skipped (cached or empty file), .-no changes, F-fixed, E-error
   1) app/Config/Logger.php (ordered_imports)
   2) app/Views/errors/html/error_exception.php (braces, unary_operator_spaces, not_operator_with_successor_space)

Checked all files in 1.104 seconds, 16.000 MB memory used
```

然後故意降版本到 v3.8.0 又可以正常

```
% mv composer.json composer.json-bak
% composer require friendsofphp/php-cs-fixer:3.8.0 --dev
% ./vendor/bin/php-cs-fixer fix --dry-run -v .
PHP CS Fixer 3.8.0 BerSzcz against war! by Fabien Potencier and Dariusz Ruminski.
PHP runtime: 7.4.30
Loaded config default.
Using cache file ".php-cs-fixer.cache".
..........................................................                                                                            58 / 58 (100%)
Legend: ?-unknown, I-invalid file syntax (file ignored), S-skipped (cached or empty file), .-no changes, F-fixed, E-error

Checked all files in 0.303 seconds, 14.000 MB memory used
```

為了避免未來同事不同平台開發的困局,就來安分地寫一下 .php-cs-fixer.dist.php 檔案吧!也順道研究到 CodeIgniter 也有個 CodeIgniter/coding-standard 規範,接著參考 github.com/CodeIgniter/coding-standard#setup 一步一步測試

```
% cat .php-cs-fixer.dist.php
<?php

use CodeIgniter\CodingStandard\CodeIgniter4;
use Nexus\CsConfig\Factory;

return Factory::create(new CodeIgniter4())->forProjects();

% ./vendor/bin/php-cs-fixer fix --dry-run -v .
PHP CS Fixer 3.9.5 Grand Awaiting by Fabien Potencier and Dariusz Ruminski.
PHP runtime: 7.4.30
Loaded config CodeIgniter4 Coding Standards from "/path/./.php-cs-fixer.dist.php".
Using cache file ".php-cs-fixer.cache".
Paths from configuration file have been overridden by paths provided as command arguments.
.....F......................................F.............                                                                            58 / 58 (100%)
Legend: ?-unknown, I-invalid file syntax (file ignored), S-skipped (cached or empty file), .-no changes, F-fixed, E-error
   1) app/Config/Logger.php (ordered_imports)
   2) app/Views/errors/html/error_exception.php (braces, unary_operator_spaces, not_operator_with_successor_space)

Checked all files in 1.104 seconds, 16.000 MB memory used
```

開始先找一下怎樣略過那兩個檔案的用法:

```
% cat .php-cs-fixer.dist.php
<?php
use CodeIgniter\CodingStandard\CodeIgniter4;
use Nexus\CsConfig\Factory;
use PhpCsFixer\Finder;

// https://github.com/codeigniter4/CodeIgniter4/blob/develop/.php-cs-fixer.dist.php
$finder = Finder::create()
->files()
->notPath([
'app/Config/Logger.php',
'app/Views/errors/html/error_exception.php',
]);

// https://github.com/NexusPHP/cs-config/blob/develop/src/Factory.php
//return Factory::create(new CodeIgniter4())->forProjects();
return Factory::create(new CodeIgniter4(), [], [
'finder' => $finder,
])->forProjects();

% ./vendor/bin/php-cs-fixer fix --dry-run .
Loaded config CodeIgniter4 Coding Standards from "/path/./.php-cs-fixer.dist.php".
Using cache file ".php-cs-fixer.cache".

Checked all files in 0.032 seconds, 14.000 MB memory used
```

接著去 Windows 跑:

```
C:\path>.\vendor\bin\php-cs-fixer fix --dry-run .
PHP CS Fixer 3.9.1 Grand Awaiting by Fabien Potencier and Dariusz Ruminski.
PHP runtime: 7.4.30
Loaded config CodeIgniter4 Coding Standards from "C:\path\.\.php-cs-fixer.dist.php".
Using cache file ".php-cs-fixer.cache".
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF          56 / 56 (100%)
Legend: ?-unknown, I-invalid file syntax (file ignored), S-skipped (cached or empty file), .-no changes, F-fixed, E-error

   1) app\Common.php (line_ending)
  ...
  55) tests\_support\Libraries\ConfigReader.php (line_ending)
  56) tests\_support\Models\ExampleModel.php (line_ending)

Checked all files in 1.187 seconds, 16.000 MB memory used
```

最後再加個 line_ending 來處理一下:

```
% cat .php-cs-fixer.dist.php
<?php
use CodeIgniter\CodingStandard\CodeIgniter4;
use Nexus\CsConfig\Factory;
use PhpCsFixer\Finder;

// https://github.com/codeigniter4/CodeIgniter4/blob/develop/.php-cs-fixer.dist.php
$finder = Finder::create()
->files()
->notPath([
'app/Config/Logger.php',
'app/Views/errors/html/error_exception.php',
]);

// https://github.com/NexusPHP/cs-config/blob/develop/src/Factory.php
//return Factory::create(new CodeIgniter4())->forProjects();
return Factory::create(new CodeIgniter4(), [], [
'finder' => $finder,
// https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/3955
'lineEnding' => PHP_EOL,
])->forProjects();
```

收工!

2018年1月27日 星期六

[PHP] 使用 PHP built-in web server 及 PHP CodeIgniter framework

回想起來,我大概斷斷續續用了 CodeIgniter 七年了,最近才準備在本地開發 XD 開發上就在想 node.js 都有 webpack 等工具了,為啥 PHP 開發上還要先架設個 Web server 而感到納悶。

然而,其實 PHP 早已有 built-in web server 了,雖然只是 single-thread 但在開發上已經非常夠用,就來摸一下怎樣整再一起

$ cd project_web_document_root
$ php -S localhost:8000


接著就在 http://localhost:8000 就可以運行了!
然而,許多 web framework 都靠 routing 把 requests 統一集中到一支程式判斷,似乎已經是個非常基本的設計概念,那在 php built-in web server 也是可以的,他可以設定 routing 機制

$ cd project/web
$ cat ../tools/routing.php
$BASE_DIR = __DIR__ . '/../web' ;
if (file_exists($BASE_DIR . $_SERVER['REQUEST_URI']))
return false;
$_SERVER['SCRIPT_NAME'] = '/index.php';
include_once ($BASE_DIR . '/index.php');
$ php -S localhost:8000 ../tools/routing.php
PHP 7.0.27 Development Server started at Tue Jan 23 12:31:32 2018
Listening on http://localhost:8000
Document root is C:\Users\user\Desktop\ci-project\web
Press Ctrl-C to quit.


更多筆記:changyy/codeiginiter-and-php-built-in-web-server

2017年10月27日 星期五

Firebase 開發筆記 - 使用 PHP 之 Verify ID tokens using a third-party JWT library

PHP 漸漸地越來越沒有愛了 XD Ubuntu server 預設還是停留在 php5.5 系列,而許多套件都進入了 PHP 7 世界了。不知是不是這樣子,所以官方沒再推出 PHP SDK ?於是乎,只好自己刻一下下。也順勢認識 JWT,第一次認識是在 APNs Auth Key 的使用,沒想到這麼快又要上戰場了 XD

網路資源:
若覺得很煩,就直接用 https://github.com/kreait/firebase-php 吧!這篇專注在紀錄 JWT - Firebase 的使用和驗證。

用法:

$ mkdir jwt-3.2.2 ; cd jwt-3.2.2 ; composer require lcobucci/jwt
$ vim test.php
<?php
require 'vendor/autoload.php';

$token_string = 'XXXXXXXXXXX';

$signer = new Lcobucci\JWT\Signer\Rsa\Sha256();
$keychain = new Lcobucci\JWT\Signer\Keychain;
$parser = new Lcobucci\JWT\Parser;

try {
$token = $parser->parse($token_string);
} catch( Exception $e ) {
echo "decode failed\n";
exit;
}

// check key field
foreach (array( 'iat', 'exp', 'aud', 'iss', 'user_id' ) as $field) {
if (!$token->hasClaim($field)) {
echo "no $field\n";
exit;
}
}

if ($token->isExpired()) {
echo "exp expired\n";
exit;
}

if (!$token->hasHeader('kid')) {
echo "no kid\n";
exit;

}
$kid = $token->getHeader('kid');

$keys = json_decode(file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'), true);

if (!isset($keys[$kid])) {
echo "kid not found\n";
exit;
}


try {
if( $token->verify($signer, $keychain->getPublicKey($keys[$kid])) )
echo "PASS\n";
} catch (Exception $e) {
echo "Failed";
}

$user_id = $token->getClaim('user_id');


連續動作(PHP Codeigniter Usage):

$ cat Jwt_library.php
<?php
require_once 'jwt-3.2.2/vendor/autoload.php';
class Jwt_library {
public function __construct() {
$this->ci = &get_instance();
$this->parser = new Lcobucci\JWT\Parser;
$this->keychain = new Lcobucci\JWT\Signer\Keychain;
$this->signer = new Lcobucci\JWT\Signer\Rsa\Sha256;
}

public function verify_firebase_token(&$error, $user_token, $project_id, $service_public_keys = array()) {
$user_id = NULL;
$error = NULL;
$token = false;
try {
$token = $this->parser->parse($user_token);
} catch (Exception $e) {
$error= 'decode failed';
return NULL;
}

// check filed name
foreach (array( 'iat', 'exp', 'aud', 'iss', 'user_id' ) as $field) {
if (!$token->hasClaim($field)) {
$error = "no $field";
return NULL;
}
}

if ($token->isExpired()) {
$error = 'exp expired';
return NULL;
}
//if ($token->getClaim('iat') > time() )
// return 'token has been issued in the future';

if ($token->getClaim('aud') != $project_id ) {
$error = 'aud error';
return NULL;
}

$user_id = $token->getClaim('user_id');

$kid = false;
try{
$kid = $token->getHeader('kid');
} catch (Exception $e) {
$error = 'no kid';
return NULL;
}

if (!isset($service_public_keys[$kid])) {
$error = 'kid not found: '.$kid;
return NULL;
}

try {
if ($token->verify($this->signer, $this->keychain->getPublicKey($service_public_keys[$kid])))
return $user_id;
} catch (Exception $e) {
$error = 'verify failed';
}

return NULL;
}
}


$ cat php_ci_controller.php
<?php
$output = array( 'status' => false );

$authorization_info = $this->input->get_request_header('Authorization', True);
if (empty($authorization_info) || strstr($authorization_info, 'Bearer ') == false) {
        $output['error'] = -1;
        $output['message'] = 'no Authorization';
        $this->_json_output($output);
        return;
}

$firebase_user_token = trim(substr($authorization_info, strlen('Bearer ')));
$this->load->library('jwt_library');
$keys = @json_decode(@file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'), true);
$firebase_user_id = $this->jwt_library->verify_firebase_token($verify_error, $firebase_user_token, 'YourFirebaseProjectId', $keys);
if (empty($firebase_user_id)) {
$output['error'] = 1;
$output['message'] = 'verify: '.$verify_error;
$this->_json_output($output);
return;
}

2016年7月20日 星期三

NGNIX 與數個 PHP CodeIgniter 專案部署問題:使用虛擬目錄切該各個專案

最近處理某個老專案,裡頭有多個 PHP CI Project,配置在同一台 Web Server,原本採用 Apache Web Server 設定相安無事,直到搬到 Nginx 才發現頭很痛 XD 若使用 Nginx 部署一個 CI Project 是很容易的,但使用虛擬目錄則會面臨一些問題。

這個原因是建構在部署專案時,採用 Apache Alais 跟 Requests Rewrite 方式,非常便利 Requests URI 導向至指定的 PHP CI Project:

# Apache Web Server
Alias /prefix/project /path/ci/project
<Directory /path/ci/project>
Options FollowSymLinks
DirectoryIndex index.php
AllowOverride None
Require all granted
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /prefix/project
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
        </IfModule>
</Directory>


其中 /prefix 是個虛擬的目錄,然而,在 Nginx 環境中,若要採用類似的架構時,就會需要處理一些問題,包含要做 requests uri 或 php script filename 的更新等,若 PHP CI Project 有提供 Web UI 時,就還得處理 css/js/image 的 requests 導向。

最終的解法:

# static files
location ^~ /prefix/project/assets/ {
alias "/path/ci/project/assets/";
}

# php requests
location ^~ /prefix/project {
root "path/ci/project";
try_files $uri $uri/ /prefix/project/index.php?$query_string;

location ~ \.php$ {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_read_timeout 180;
fastcgi_buffer_size 64k;
fastcgi_buffers 512 32k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 256k;
fastcgi_index  index.php;
include fastcgi_params;

set $target_fastcgi_script_name $fastcgi_script_name;
if ($target_fastcgi_script_name ~ ^/prefix/project/(.*)$) {
set $target_fastcgi_script_name /$1;
}
fastcgi_param SCRIPT_FILENAME $document_root$target_fastcgi_script_name;
}
}


此外,若想多了解 nginx location 的優先順序,可以參考這則: Nginx location priority - Stack Overflow

2016年6月23日 星期四

[PHP] 使用 Google api client 操作 Google Spreadsheet API (Google Docs - Excel)

最近在整理資料,由於使用情境尚未明朗,想了一下就把資料塞到 Excel 來呈現,要排序、輸出跟轉 PDF 檔都 ok ,再加上有定期更新的需求,就來找一下 Google Spreadsheet API 來用用:https://developers.google.com/sheets/ ,程式擺在:

https://github.com/changyy/codeigniter-library-google-spreadsheet

由於同事比較熟 PHP ,就繼續挑 PHP 路線了 :P 沒想到 PHP 相關的 library 滿少的,大概都推薦 github.com/asimlqt/php-google-spreadsheet-client 這套了,但他採用的 API 所實作出來的有些侷限,但已經可以滿足八成的需求了!

最後為了達成自己想幹的事,在 k 完文件跟摸索後,還是自己下海包一份當作筆記(實在是官方文件都沒寫很清楚,只能自己追細節),包括的功能:

  • 支援單獨使用,以及和 PHP CodeIgniter 合用
  • 使用 composer.json 維護相依性:只有使用 google/apiclient: https://github.com/google/google-api-php-client
  • 使用  Google Spreadsheet API v4
  • 取得 Spreadsheet 清單 (使用 v3 API)
  • 建立 Spreadsheet
  • 修改 Spreadsheet name
  • 建立 Worksheet
  • 刪除 Worksheet
  • 可對 Worksheet 凍結視窗(frozenRow/frozenColumn)
  • 更新 Cells 資料
  • 搭配 Web server (如 CodeIgniter Controller 架構),可以完成 Google OAuth 流程,取得 Access Token 跟 Refresh Token
  • 搭配 Google OAuth offline 權限,可以自動 renew access_token

整體上,若不需要建立 Spreadsheet 跟 frozenRowColumn 的功能,建議直接用 asimlqt/php-google-spreadsheet-client 即可,我只先完成自己需要的部分。

2015年12月25日 星期五

[Linux] 解決 PHP CodeIgniter 在 Nginx 環境中 $_REQUEST 永遠為空

這塊只是 Nginx 的 try_files 的地方未補好引起的,我有點忘了當初是在哪邊找到的 XD 剛看一下 Nginx 的官網的確也是這樣寫:

https://www.nginx.com/resources/wiki/start/topics/recipes/codeigniter/
location / {
# Check if a file or directory index file exists, else route it to index.php.
try_files $uri $uri/ /index.php;
}


這樣的環境下,在 PHP CodeIgniter 裡頭,每次想要從 $_REQUEST 取資料都會為空

<?php
print_r($_REQUEST);


解法就是將 $query_string 資訊帶入即可:

location / {
# Check if a file or directory index file exists, else route it to index.php.
try_files $uri $uri/ /index.php?$query_string;
}

2015年10月6日 星期二

[PHP] 處理 PHP CodeIgniter 與 apache web server、nginx 的 Rewrite Rules

之前比較常用 Apache Web server ,在使用 PHP CodeIngiter 時,常常設定 Rewrite Rules 時,需要做一些手腳,例如:http://hostname/ci 想要瀏覽到 PHP CodeIgniter Project,而 ci 這個並非實體目錄,且 PHP CI Project 並非擺在 DocumentRoot 裡,這時就有很多環境變數需處理。

由於要符合 PHP CodeIgniter 的 routing rules,必須把 /ci 這個 path 給去掉,在 Apache Web server 透過 RewriteBase 處理,而 Nginx 又更麻煩一點,需處理 fastcgi_param REQUEST_URI 跟 fastcgi_param SCRIPT_FILENAME 資訊。

Apache 的設定:

Alias /ci /data/ci-project
<Directory /data/ci-project>
       Options FollowSymLinks
       DirectoryIndex index.php
       AllowOverride None

       Require all granted
       <IfModule mod_rewrite.c>
               RewriteEngine On
               RewriteBase /ci

               RewriteCond %{REQUEST_URI} ^system.*
               RewriteRule ^(.*)$ /index.php?/$1 [L]
 
               RewriteCond %{REQUEST_URI} ^application.*
               RewriteRule ^(.*)$ /index.php?/$1 [L]

               RewriteCond %{REQUEST_FILENAME} !-f
               RewriteCond %{REQUEST_FILENAME} !-d
               RewriteRule ^(.*)$ index.php?/$1 [L]
       </IfModule>
</Directory>


Nginx 設定:

        set $request_prefix '/ci/';
        set $ci_sys_dir '/opt/actions-channel-api/';

        location /ci/ {
                alias $ci_sys_dir;
                index  index.php index.html index.htm;

                try_files $uri $uri/ /ci/index.php?$query_string;
        }
        location ~* \.php$ {
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_split_path_info ^(.+\.php)(.*)$;
                include fastcgi_params;

                set $target_request_uri $request_uri;
                if ($target_request_uri ~ ^/ci/(.*)$ ) {
                        set $target_request_uri /$1;
                }
                fastcgi_param REQUEST_URI $target_request_uri;

                set $target_fastcgi_script_name $fastcgi_script_name;
                if ($target_fastcgi_script_name ~ ^/ci/(.*)$ ) {
                        set $target_fastcgi_script_name $1;
                }
                fastcgi_param SCRIPT_FILENAME $ci_sys_dir$target_fastcgi_script_name;
        }


其他 Nginx 筆記:

  • alias 的數值記得要補上最後的 "/" ;alias 跟 root 的最大差別是 alias 的位置不需要在 document root  裡頭
  • 在 try_files 流程中,一旦符合條件後,就不會再執行該 nginx location 底部項目,因此還是把 php handler 拉到最外層,而不要全部都寫在 location /ci/ 此區塊裡頭
  • nginx 可定義很多環境變數,若想要看它就寫到 log 即可:
    • http {
          log_format proxy ' "$request"  "$status"  "$http_referer"  "$http_user_agent"  $request_time  $upstream_response_time "$ci_sys_dir" "$target_fastcgi_script_name"  "$target_request_uri"  '
      }

2015年4月25日 星期六

PHP CodeIgniter - 使用 Memcached

官方文件寫得很簡單,簡單的無法看懂:

@ https://ellislab.com/codeigniter/user-guide/libraries/caching.html
$this->load->driver('cache');
$this->cache->memcached->save('foo', 'bar', 10);


後來我自己去 trace 原始碼才知道該怎樣設定跟測試。首先,新增一個設定檔:

$ vim application/config/memcached.php
$config['memcached'] = array(
        'hostname' => 'Your_memecached_cluster',
        'port' => 11211,
        'weight' => 1
);


接著,使用:

class My_Library {
public function __construct() {
$this->ci =& get_instance();
$this->init();
}
public function init() {
$this->ci->load->driver('cache');
return $this->ci->cache->is_supported('memcached');
}
public function set($key, $value, $tts) {
return $this->ci->cache->memcached->save($key, $value, $tts);
}
public function delete($key) {
$this->ci->cache->memcached->delete($key);
}
}


關鍵之處就是要呼叫 $this->ci->cache->is_supported('memcached') 這段,才會從 application/config/memcached.php 把資訊更新進來 Orz

若需要 debug 的話:

$ find . -name "*mem*"
./system/libraries/Cache/drivers/Cache_memcached.php


找到 $this->_memcached 可以善用它,例如 $this->_memcached->getResultCode();

2015年4月8日 星期三

PHP CodeIgniter - 透過 Apache RewriteRule 限制 CGI 功能

基於一些開發需求,想要侷限網站的功能。剛好這個網站服務是用 PHP CodeIgniter 開發的,整套都是走 RewriteRule 來進行,例如一個 URL 位置,都一律導向到 PHP CodeIgniter Project 的 index.php?/path 來分析。

假設原本網站有 3 個主要網址,分別是 /api, /shopping, / 等,假設想要讓此網站只開啟 /api 時,這時就可以透過 Apache RewriteRule 來限制:

<VirtualHost *:80>
DocumentRoot /ci-project/
DirectoryIndex index.html index.php index.htm

# empty page
Alias /empty     /var/www/html/

<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>

<Directory /var/www/html/>
Options FollowSymLinks
AllowOverride None
DirectoryIndex index.html index.php index.htm
Require all granted
Satisfy Any
</Directory>

<Directory /ci-project>
Options FollowSymLinks
DirectoryIndex index.php
AllowOverride None
#AllowOverride All
Require all granted
Satisfy Any

<IfModule mod_rewrite.c>
RewriteEngine On
#LogLevel alert rewrite:trace6
RewriteBase /

# disable index.php with empty QUERY_STRING
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^index\.php$ /empty/ [L]

RewriteCond $1 !^(index\.php|images|css|js|favicon\.ico)
# enable /api only
RewriteCond $1 ^api.*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
</IfModule>
</Directory>
</VirtualHost>


如此一來,只要使用者逛 / 位置,則會顯示 /var/www/html 的資料,而逛 /api 系列時,則是可以正常引導到 PHP CodeIgniter 相關程式碼來處理。

2014年11月25日 星期二

[PHP] CodeIgniter 與 Facebook PHP SDK v4 整合筆記 @ Ubuntu 14.04

整個流程並主要是把 Facebook PHP sdk v4 source code 下載到 ci_proj/application/libraries 中,接著撰寫一隻 ci library: facebook.php 來橋接一下,就差不多可以收工了。在此謹驗證收到的 facebook token 是否有效,其他部分並不實作:

$ cd /path/ci_proj/application/libraries
$ git clone https://github.com/facebook/facebook-php-sdk-v4.git
$ ln -s facebook-php-sdk-v4 facebook


建立 Facebook 相關 config:

$ vim /path/ci_proj/application/config/facebook.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
$config['facebook']['api_id'] = 'FACEBOOK APP ID';
$config['facebook']['app_secret'] = 'FACEBOOK APP SECRET KEY';


編輯橋接的 library 用法:

$ vim /path/ci_proj/application/libraries/facebook.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH . 'libraries/facebook/autoload.php';

use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

class Facebook {
var $ci;
var $helper;
var $session;
var $permissions;

public function __construct() {
$this->ci =& get_instance();
$this->ci->load->config('facebook');
$this->permissions = $this->ci->config->item('permissions', 'facebook');
FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );
        }
public function token_validation($token) {
try {
$this->session = new FacebookSession( $token );
if ( $this->session->validate() )
return true;
} catch ( Exception $e ) {
}
$this->session = null;
return false;
}
public function get_user($token = NULL) {
if ( $this->session || (!empty($token) && $this->token_validation($token)) ) {
$request = ( new FacebookRequest( $this->session, 'GET', '/me' ) )->execute();
$user = $request->getGraphObject()->asArray();
return $user;
}
return false;
}
}


使用方式:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller {
public function index()
{
$this->load->config('facebook');
$this->load->library('facebook');
$output = array(
'reqeusts' => $_REQUEST,
'app_id' => $this->config->item('api_id', 'facebook'),
'user_id' => $this->facebook->get_user($_REQUEST['token'])
);
$this->output->set_content_type('application/json')->set_output(json_encode($output));
        }
}

2014年3月18日 星期二

[PHP] CodeIgniter 處理多層子目錄 Routing 問題

[PHP] CodeIgniter 處理多層子目錄 Routing 問題

過去使用 CodeIgniter 一直以為在 application/controller 裡的目錄結構可以無限延伸使用,如:

application/conotrollers/service/dashboard/product.php
application/conotrollers/service/api/product.php
application/conotrollers/service/welcome.php
application/conotrollers/welcome.php


當瀏覽 hostname/ 可以由 conotrollers/welcome.php 處理,瀏覽 hostname/service/welcome 則由 conotrollers/service/welcome.php 處理,一切正常。

但瀏覽 hostname/service/api/product 和 hostname/service/dashboard/product 時,卻噴 404 Page Not Found 訊息。

一開始以為 nginx rules 設定錯誤,追一下 CodeIgniter 的 source code 後,發現 CodeIgniter 的程式碼沒有用遞迴或等價方式去搜尋子目錄,再透過相關關鍵字才發現,關於多層子目錄的需求,則只能透過指定 routing 的設定方式進行,但對應到還是一層目錄結構:

例如 hostname/service/dashboard/product 用法:

$ vim application/config/routes.php

$route['service/(:any)/(:any)'] = 'service_$1/$2';


而目錄結構更新為:

application/conotrollers/service_dashboard/product.php
application/conotrollers/service_api/product.php
application/conotrollers/welcome.php


簡言之,就是以 application/controllers 為基準,頂多再加一層 subdir 而已,而想要 uri 有多層的含義,只能自定 route 來達到。

2014年1月21日 星期二

[Linux] CodeIgniter on Nginx : site_url, base_url use https @ Ubuntu 12.04

在 nginx 上跑 CodeIgniter 時,使用 site_url 、 base_url 卻會產生 https 的連結出來,此現象是因為 CodeIgniter 是透過 $_SERVER['HTTPS'] 判斷所造成的,解法就是設定 Nginx PHP 的環境參數(fastcgi_param  HTTPS  off),在 /etc/nginx/fastcgi_params 可看到這樣的定義:

fastcgi_param  HTTPS  $https;

暫時偷懶解法 (/etc/nginx/sites-available/default):

location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param  HTTPS off;
}


2014年1月12日 星期日

[Linux] Nginx + Auth + PHP + CodeIgniter @ Ubuntu 12.04

Nginx Authentication 可以參考官網 HttpAuthBasicModule / ngx_http_auth_basic_module 設定:

location ~^ /ci/  {
  auth_basic            "Restricted";
  auth_basic_user_file  htpasswd;
}


由於 nginx 用 apt-get 安裝,此例 htpasswd 則是位於 /etc/nginx/htpasswd ,若不確定的話,翻一下 nginx access/error logs 來看。

比較特別,如果保護的是一個 location 包含要運行 PHP 程式的話,裡頭需要把完整的 PHP 處理也定義好,據說是因為 nginx auth_basic module 不會繼續往下讀起 nginx.conf。

解法:

location ~^ /ci/  {
  auth_basic            "Restricted";
  auth_basic_user_file  htpasswd;

  # for codeigniter
  index  index.html index.htm index.php;
  try_files $uri $uri/ /ci/index.php;

  # for php
  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

    # With php5-cgi alone:
    fastcgi_pass 127.0.0.1:9000;

    # With php5-fpm:
    #fastcgi_pass unix:/var/run/php5-fpm.sock;

    fastcgi_index index.php;
    include fastcgi_params;
}

2014年1月8日 星期三

[Linux] 簡易的測試機 - Nginx + Codeigniter + PHP + MySQL + PhpMyAdmin @ Linode Ubuntu 12.04 TLS

有點久沒在 Linode 打滾了,記得...我的信用卡還因為 Linode 的事件花錢換了一張新的 Orz 這次著重在測試機,所以先偷懶不裝防火牆

更新系統:

$ apt-get update && apt-get upgrade && apt-get dist-upgrade

簡易管理員:

$ adduser userid
$ vim /etc/group
sudo:userid


更新 hostname (建議不要有 "-",過去的經驗是 Hadoop 會找不到機器):

$ vim /etc/hostname
$ hostname -F /etc/hostname
$ vim /etc/hosts
127.0.1.1 YourName


簡易資安管理:

$ apt-get install denyhosts
$ vim /etc/hosts.allow
# whilelist
sshd: MyIP : allow


設定開發環境:

$ apt-get install nginx php5-cli php5-fpm mysql-server phpmyadmin

$ nginx -v
nginx version: nginx/1.1.19
$ php -v
PHP 5.3.10-1ubuntu3.9 with Suhosin-Patch (cli) (built: Dec 12 2013 04:27:25)
$ php5-fpm -v
PHP 5.3.10-1ubuntu3.9 (fpm-fcgi) (built: Dec 12 2013 04:31:25)


設定 nginx + PHP + Codeigniter:

$ vim /etc/nginx/sites-available/default
server {
# …
index index.html index.htm index.php;
# …
        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
 
                # With php5-cgi alone:
                fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                #fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
        # http://wiki.nginx.org/Codeigniter
        location /ci_proj/ {
               index index.html index.htm index.php;
               try_files $uri $uri/ /ci_proj/index.php;
        }
# …
}
$ service nginx restart


設定 nginx + PHPMyAdmin:

$ ln -s /usr/share/phpmyadmin/ /usr/share/nginx/www/phpmyadmin
$ sudo service php5-fpm restart


其中 /etc/phpmyadmin/config-db.php 有標記預設登入的帳蜜,當然,也可以用當初設定 mysql 的 root 登入,建議新增帳號後,把 root 登入關掉, 共有兩處:

$ vim /etc/phpmyadmin/config.inc.php
/* Authentication type */
$cfg['Servers'][$i]['AllowRoot'] = FALSE;


其他資料庫匯入:

$ mysql -u db_account -p -D db_name < db_backup.sql