さくらVPSでWordpressブログをやってます。そんなにアクセスがないはずなのに、さくらVPSに移行した当時は結構サーバが落ちました。topコマンドで見るとスワップが結構70%まで上がったりして、手動でapache再起動とかもやりました。。ネットでいろいろググッてそれなりにパフォーマンスチューニングした結果やっと安定して、同じサーバに2つのWordpressブログと一つのRailsアプリケーションを実行しています。

参考までにさくらVPSは一番安いの512MB、月1000円のプランで、平日だとこのブログの一日PVは大体500〜600です。

チューニングしてから結構時間が経ったのでだいぶ忘れました。Evernoteでのメモを貼ります。

効果が高い順で。

Wordpress

W3 Total Cacheプラグインが一押しです。インストールも設定も簡単ですし、一番効果があります。 ページのキャッシュ、cssやjavascriptのマージと圧縮など、結構やってくれます。実際これだけ入れても感じるほど早くなるはずです。

Apache

httpd.confを編集します。いろいろ修正してみましたが、結果下記の設定にしました。この辺はググったら結構出ますが、それぞれの環境に合わせて試行錯誤したほうがオススメです。


<IfModule prefork.c>
StartServers       5
MinSpareServers    5
MaxSpareServers   10
ServerLimit      64
MaxClients       64
MaxRequestsPerChild  50
MaxMemFree 2000
</IfModule>

PHP

/etc/php.ini

zlib.output_compression = On

APC

pecl install APC

Wordpressで画像アップロード時にいつも3サイズのサムネイルが生成されたのですが、さくらVPSに移行後それができなくなったのです。

調べてみたらPHPの画像処理のライブラリであるgdがインストールしてないことがわかりました。 CentOSなのでyumを使ってインストールすれば解決です。

sudo yum install php-gd
sudo service httpd restart
#php #php #snippet

curl_multi系を使って、プロセス数を指定して実行するマルチスレッド処理です。

urlは配列で受け取って、もし指定したプロセス数より多い場合は分割して実行するようになってます。

このサンプルコードではこのブログの幾つかのurlに対してtitleを取得しました。

<?php
/**
* 指定したプロセス数で並列処理を実行する
*
* @param array $url_list URLの配列
* @param boolean $url_as_key 結果配列を返すときに、urlをキーにする
* @param int $timeout タイムアウト秒数 0だと無制限
* @return array 結果配列
*/
function execute($url_list, $url_as_key = false, $timeout=0) {
    // set your process number
    $process = 5;
    $is_over_process = false;
    if ($process < count($url_list)) {
        // chunk url list / process number*
        $url_chunk = array_chunk($url_list, $process);
        $is_over_process = true;
    }
    $ret = array(); 
        
    if ($is_over_process && !empty($url_chunk)) {
        foreach ($url_chunk as $key => $url_list) {
            echo "chunk start:{$key}\n";
            
            $res = fetch_multi_url($url_list, $url_as_key, $timeout);
            if (!empty($res)) {
                $ret = array_merge($ret, $res);
            } else {
                continue;
            }
        }
    } else if (!$is_over_process && !empty($url_list)){
        $ret = fetch_multi_url($url_list, $url_as_key, $timeout);
    } else {
        echo "url invalid::";
    }
    
    return $ret;
    
}
/**
 * curl_multi_execの並列処理
 * ほぼboilerplate
 *
* @param array $url_list URLの配列
* @param boolean $url_as_key 結果配列を返すときに、urlをキーにする
* @param int $timeout タイムアウト秒数 0だと無制限
* @return array 結果配列
 */
function fetch_multi_url($url_list, $url_as_key, $timeout) {
    $mh = curl_multi_init();
    foreach ($url_list as $i => $url) {
        $ch[$i] = curl_init($url);
        curl_setopt($ch[$i],CURLOPT_RETURNTRANSFER,1);
        //タイムアウト
        if ($timeout){
            curl_setopt($ch[$i],CURLOPT_TIMEOUT,$timeout);
        }
        curl_multi_add_handle($mh,$ch[$i]);
    }
    //URLを取得
    //すべて取得するまでループ
    $active = null;
    do {
        $mrc = curl_multi_exec($mh,$active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    while ($active and $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh,$active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    if ($mrc != CURLM_OK) {
        echo '読み込みエラーが発生しました:'.$mrc;
    }
    //ソースコードを取得
    $res = array();
    foreach ($url_list as $i => $url) {
        if (($err = curl_error($ch[$i])) == '') {
            // url_as_keyがtrueの場合、urlをキーとして格納
            if ($url_as_key) {
                $res[$url] = curl_multi_getcontent($ch[$i]);
            // そうでない場合は、ただ配列に入れる
            } else {
                $res[$i] = curl_multi_getcontent($ch[$i]);
            }
        } else {
            echo '取得に失敗しました:'.$url_list[$i].'<br />';
        }
        curl_multi_remove_handle($mh,$ch[$i]);
        curl_close($ch[$i]);
    }
    curl_multi_close($mh);
    return $res;
}
// 並列実行したいurl list
$url_list = array(
    "https://kinopyo.com/ja/blog/ipad-2-not-charging-when-connected-to-pc-usb/",
    "https://kinopyo.com/ja/blog/the-first-app-i-installed-to-ipad2/",
    "https://kinopyo.com/ja/blog/chrome-warn-before-quitting-with-command-q-in-mac/",
    "https://kinopyo.com/ja/blog/reply-to-all-always-in-gmail/",
    "https://kinopyo.com/ja/blog/lion-fullscreen-shortcut-key-conflict-with-evernote-client/",
    "https://kinopyo.com/ja/blog/how-to-set-gesture-for-chrome-to-swipe-back-and-forth-in-lion/",
    "https://kinopyo.com/ja/blog/3-free-ebooks-for-study-coffeescript/"
);
// start time
$start_time = microtime(true);
// execute
$res = execute($url_list, true);
// execute time
$time = microtime(true) - $start_time;
// play with the result
// here I just get the page title
$titles = array();
foreach ($res as $url => $html) {
    preg_match('{<title>(.*)</title>}',$html, $match_title);
    $titles[$url] = $match_title[1];
}
echo "Result:\n";
echo "time:{$time} sec\n";
print_r($titles);

参考:PHPでマルチスレッド(バックグラウンド処理)を実現する方法

#php #php #snippet

curl_multi系を使って、プロセス数を指定して実行するマルチスレッド処理です。

urlは配列で受け取って、もし指定したプロセス数より多い場合は分割して実行するようになってます。

このサンプルコードではこのブログの幾つかのurlに対してtitleを取得しました。

<?php
/**
* 指定したプロセス数で並列処理を実行する
*
* @param array $url_list URLの配列
* @param boolean $url_as_key 結果配列を返すときに、urlをキーにする
* @param int $timeout タイムアウト秒数 0だと無制限
* @return array 結果配列
*/
function execute($url_list, $url_as_key = false, $timeout=0) {
    // set your process number
    $process = 5;
    $is_over_process = false;
    if ($process < count($url_list)) {
        // chunk url list / process number*
        $url_chunk = array_chunk($url_list, $process);
        $is_over_process = true;
    }
    $ret = array(); 
        
    if ($is_over_process && !empty($url_chunk)) {
        foreach ($url_chunk as $key => $url_list) {
            echo "chunk start:{$key}\n";
            
            $res = fetch_multi_url($url_list, $url_as_key, $timeout);
            if (!empty($res)) {
                $ret = array_merge($ret, $res);
            } else {
                continue;
            }
        }
    } else if (!$is_over_process && !empty($url_list)){
        $ret = fetch_multi_url($url_list, $url_as_key, $timeout);
    } else {
        echo "url invalid::";
    }
    
    return $ret;
    
}
/**
 * curl_multi_execの並列処理
 * ほぼboilerplate
 *
* @param array $url_list URLの配列
* @param boolean $url_as_key 結果配列を返すときに、urlをキーにする
* @param int $timeout タイムアウト秒数 0だと無制限
* @return array 結果配列
 */
function fetch_multi_url($url_list, $url_as_key, $timeout) {
    $mh = curl_multi_init();
    foreach ($url_list as $i => $url) {
        $ch[$i] = curl_init($url);
        curl_setopt($ch[$i],CURLOPT_RETURNTRANSFER,1);
        //タイムアウト
        if ($timeout){
            curl_setopt($ch[$i],CURLOPT_TIMEOUT,$timeout);
        }
        curl_multi_add_handle($mh,$ch[$i]);
    }
    //URLを取得
    //すべて取得するまでループ
    $active = null;
    do {
        $mrc = curl_multi_exec($mh,$active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    while ($active and $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh,$active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    if ($mrc != CURLM_OK) {
        echo '読み込みエラーが発生しました:'.$mrc;
    }
    //ソースコードを取得
    $res = array();
    foreach ($url_list as $i => $url) {
        if (($err = curl_error($ch[$i])) == '') {
            // url_as_keyがtrueの場合、urlをキーとして格納
            if ($url_as_key) {
                $res[$url] = curl_multi_getcontent($ch[$i]);
            // そうでない場合は、ただ配列に入れる
            } else {
                $res[$i] = curl_multi_getcontent($ch[$i]);
            }
        } else {
            echo '取得に失敗しました:'.$url_list[$i].'<br />';
        }
        curl_multi_remove_handle($mh,$ch[$i]);
        curl_close($ch[$i]);
    }
    curl_multi_close($mh);
    return $res;
}
// 並列実行したいurl list
$url_list = array(
    "https://kinopyo.com/ja/blog/ipad-2-not-charging-when-connected-to-pc-usb/",
    "https://kinopyo.com/ja/blog/the-first-app-i-installed-to-ipad2/",
    "https://kinopyo.com/ja/blog/chrome-warn-before-quitting-with-command-q-in-mac/",
    "https://kinopyo.com/ja/blog/reply-to-all-always-in-gmail/",
    "https://kinopyo.com/ja/blog/lion-fullscreen-shortcut-key-conflict-with-evernote-client/",
    "https://kinopyo.com/ja/blog/how-to-set-gesture-for-chrome-to-swipe-back-and-forth-in-lion/",
    "https://kinopyo.com/ja/blog/3-free-ebooks-for-study-coffeescript/"
);
// start time
$start_time = microtime(true);
// execute
$res = execute($url_list, true);
// execute time
$time = microtime(true) - $start_time;
// play with the result
// here I just get the page title
$titles = array();
foreach ($res as $url => $html) {
    preg_match('{<title>(.*)</title>}',$html, $match_title);
    $titles[$url] = $match_title[1];
}
echo "Result:\n";
echo "time:{$time} sec\n";
print_r($titles);

参考:PHPでマルチスレッド(バックグラウンド処理)を実現する方法

#facebook #php

今はほとんどのサイトがLike(いいね!)ボタンを置いてますが、Likeボタンがどれだけクリックされたか、その数は気になりますね。

Facebook独自のFQL(文法はSQLに似ている)を使って複数URLのLikeされた数が取れます。Facebook公式ドキュメントはこちらにあります。

下記はPHPでのサンプルコードです。

<?php
// see fql docs:
// http://developers.facebook.com/docs/reference/fql/link_stat/
$url_list = array(
	'http://example.com/url1.html',
	'http://example.com/url2.html',
);
$url_string = '("'. implode('","', $url_list). '")';
// just like sql syntax
$fql = "select url, like_count from link_stat where url in".$url_string;
// remember to encode it
$url = "https://api.facebook.com/method/fql.query?format=json&query=".urlencode($fql);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, true);
$ret = array();
print_r($json);
// result example
/*
Array
(
    [0] => Array
        (
            [url] => http://example.com/url1.html
            [like_count] => 10
        )
    [1] => Array
        (
            [url] => http://example.com/url2.html
            [like_count] => 20
        )
)
*/
#facebook #php #oauth

Our automated systems have detected that you may be inadvertently allowing authentication data to be passed to 3rd parties.

ここ最近Facebookから”認証情報をサードパーティに渡している可能性がある、48時間内に修正しろ”みたいなメールが届いた人が多いと思います。 メール本文です:

Dear Developer of xxxxxx {your app name} xxxxx, Our automated systems have detected that you may be inadvertently allowing authentication data to be passed to 3rd parties. Allowing user ids and access tokens to be passed to 3rd parties, even inadvertently, could allow these 3rd parties to access the data the user made available to your site. This violates our policies and undermines user trust in your site and Facebook Platform. In every case that we have examined, this information is passed via the HTTP Referer Header by the user’s browser. This can happen when using our legacy authentication system and including <iframe>, <img> or <script> content from 3rd parties in the page that receives authentication data from Facebook. Our legacy mechanism passes authentication information in the URL query string which, if handled incorrectly, can be passed to 3rd parties by the browser. Our current OAuth 2.0 authentication system, released over a year ago, passes this information in the URL fragment, which is not passed to 3rd parties by the browser. Please ensure that you are not allowing this data to be passed immediately. Accessing your site as a test user while running a HTTP proxy/monitor like Charles or Fiddler is the best way to determine if you are allowing this information to be passed. If you discover the issue, you can do one of two things: 1. Migrate your site to use our OAuth 2.0 authentication system. We are requiring all apps and sites to update to this mechanism by Sept. 1, 2011. Migrating now will address this issue and ensure that you are one of the first to meet the deadline. For more details, please see our Authentication Guide. 2. Create and use an interstitial page to remove the authentication data before redirecting to your page with 3rd party content. This approach is used by many of our largest developers today (although they are all migrating to OAuth 2.0 shortly). This is a simple and straightforwardchange that should have minimal impact on your site. For more details on this approach, see our Legacy Connect Auth doc. Because of the importance of ensuring user trust and privacy, we are asking you to complete one of the above steps in the next 48 hours. If you fail to do so, your site may be subject to one of the enforcement actions outlined in our policies. If you have any questions or believe you have received this message in error, please contact us. Facebook Developer Relations

多分認証システムが古い(OAuth 2.0を使ってない)かつ、該当のページに<iframe>などのタグがあるのを条件としてFacebook側が検知してたと思います、別にサードパーティにどうこうした訳ではなく。

ソースの確認

まずユーザ認証のところのソースを確認しましょう。 古い認証システムを使う場合これに似てるはずです。 ソースはFacebookのhttp://developers.facebook.com/docs/authentication/connect_auth/より。

 $api_key = "YOUR_API_KEY";
 $interstitial_page = "YOUR_SECURE_URL"; //URL with no 3rd party apps

 $url='http://www.facebook.com/login.php?api_key=' . $app_id
   . '&session_version=3&next=' . urlencode($interstitial_page)
   . '&v=1.0&return_session=1&fbconnect=1'
   . '&cancel_url=' . urlencode($interstitial_page);

 echo "Welcome to the Old Auth flow";
 echo "<p>";

 echo("<a href='" . $url . "'>"
   . "<img src='http://static.ak.facebook.com/images/"
   . "devsite/facebook_login.gif'></a>");

この場合nextパラメータで指定したページに行く時、URLパラメータでuidとかaccess_tokenが渡されますので、危ないと。

OAuth 2.0を使ったログインURLはこうです。

https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream

改修

メールで書かれた通り一つはOAuth2.0に移行する、一つは「中間ページ」挟んでユーザ情報をセッションに保持して隠蔽する。

OAuthについてはhttps://developers.facebook.com/docs/authentication/で詳しく説明しています。

後者の場合はhttp://developers.facebook.com/docs/authentication/connect_auth/の最後でサンプルコードがあるので参考できます。

#php #php #cakephp #xml

CakephpでXMLを配列に変換するのはとても簡単です。 下記のファンクションを使えば一発でできます。

uses('Xml');
$xml = new Xml("/path/to/xml");
$xml_array = Set::reverse($xml);
#php #php #cakephp #xml

CakephpでXMLを配列に変換するのはとても簡単です。 下記のファンクションを使えば一発でできます。

uses('Xml');
$xml = new Xml("/path/to/xml");
$xml_array = Set::reverse($xml);
#php #php

こちらを参照してください。

  • Mcrypt Requirements
  • Mcrypt Installation PHPを–with-mcrypt=DIR再コンパイルする必要があるそうです。またlibmcryptも2.5.6以上のバージョンを求められます。

一般的にもしfunction is undefinedになったら、何かライブラリをコンパイルする必要があるということになります。

# for ubuntu
sudo apt-get install php5-mcrypt

# for mac
sudo port install php5-mcrypt
#php #php

こちらを参照してください。

  • Mcrypt Requirements
  • Mcrypt Installation PHPを–with-mcrypt=DIR再コンパイルする必要があるそうです。またlibmcryptも2.5.6以上のバージョンを求められます。

一般的にもしfunction is undefinedになったら、何かライブラリをコンパイルする必要があるということになります。

# for ubuntu
sudo apt-get install php5-mcrypt

# for mac
sudo port install php5-mcrypt
#php #php #troubleshooting

障害

http_build_queryを使ってurlのパラメータを作るときにパラメータがこうなりました。

foo=bar&amp;amp;baz=boo&amp;amp;hoge=hoge

上記のように複数のパラメータがある時に;であるべきのところが&となってしまいました。

これはPHPの設定ファイル、php.iniのarg_separator.outputで制御されてて、XAMPPの場合インストールされたデフォルトでは、「&」となるそうです。

解決方法

なので、php.iniの「arg_separator.output」の値を「&」から「&」に変更する

参考

http_build_queryを使うときの注意点(PHP) http://www.multiburst.net/sometime-php/2008/12/http_build_query/

#php #php #troubleshooting

障害

http_build_queryを使ってurlのパラメータを作るときにパラメータがこうなりました。

foo=bar&amp;amp;baz=boo&amp;amp;hoge=hoge

上記のように複数のパラメータがある時に;であるべきのところが&となってしまいました。

これはPHPの設定ファイル、php.iniのarg_separator.outputで制御されてて、XAMPPの場合インストールされたデフォルトでは、「&」となるそうです。

解決方法

なので、php.iniの「arg_separator.output」の値を「&」から「&」に変更する

参考

http_build_queryを使うときの注意点(PHP) http://www.multiburst.net/sometime-php/2008/12/http_build_query/

問題

新しい mysqlnd ライブラリは、MySQL 4.1 用の41バイトの新しいパスワードフォーマットを使用します。 古い16バイトのパスワードを使うと、mysql_connect() 系の関数は次のようなエラーメッセージを生成します。”mysqlnd cannot connect to MySQL 4.1+ using old authentication”

MacPortでインストールしたPHP5.3では、

mysqlnd(php5.3のmysql native client)が適用される。 しかし、CentOSなどのyumでインストールできるMySQLサーバーとの相性がよろしくない。 PHP Warning: mysql_connect(): mysqlnd cannot connect to MySQL 4.1+ using old authentication というエラーが現れ、接続することができません。 mysqlndを利用しないよう再コンパイルが必要となる。

解決方法

portでインストールしたモジュールを確認、mysqlndがactiveなってるはず。

sudo port installed

php5-mysql @5.3.5_0+mysqlnd (active)

そしてmysql5のvariantsを指定で再インストール。

% sudo port install php5-mysql +mysql5

--->  Computing dependencies for php5-mysql
--->  Fetching php5-mysql
--->  Verifying checksum(s) for php5-mysql
--->  Extracting php5-mysql
--->  Configuring php5-mysql
--->  Building php5-mysql
--->  Staging php5-mysql into destroot
--->  Installing php5-mysql @5.3.5_0+mysql5
--->  Deactivating php5-mysql @5.3.5_0+mysqlnd
--->  Cleaning php5-mysql
--->  Activating php5-mysql @5.3.5_0+mysql5
--->  Cleaning php5-mysql

再度port installedで確認すればmysql5がactiveになるはず。これで解決。

php5-mysql @5.3.5_0+mysqlnd
php5-mysql @5.3.5_0+mysql5 (active)

参考

【php】mysqlndを使うとMySQLに接続できない http://www.softel.co.jp/blogs/tech/archives/2225

SnowLeopard + PHP5.3でのMySQLリモート接続 http://taikimen.blogspot.com/2010/10/snowleopard-php53mysql.html

PHP: mysqlnd cannot connect to MySQL 4.1+ using old authentication http://www.bitshop.com/Blogs/tabid/95/EntryId/67/PHP-mysqlnd-cannot-connect-to-MySQL-4-1-using-old-authentication.aspx

おまけ

mysqlが古い16バイトのパスワードを使ってるかを確認する方法です。 mysqlにログインして下記コマンドを実行:

mysql> select password('aa');

+------------------+
| password('aa')         |
+------------------+
| 0123456789abcdef |
+------------------+

16位だっだら古いです。40位なら新しいってことです。

問題

新しい mysqlnd ライブラリは、MySQL 4.1 用の41バイトの新しいパスワードフォーマットを使用します。 古い16バイトのパスワードを使うと、mysql_connect() 系の関数は次のようなエラーメッセージを生成します。”mysqlnd cannot connect to MySQL 4.1+ using old authentication”

MacPortでインストールしたPHP5.3では、

mysqlnd(php5.3のmysql native client)が適用される。 しかし、CentOSなどのyumでインストールできるMySQLサーバーとの相性がよろしくない。 PHP Warning: mysql_connect(): mysqlnd cannot connect to MySQL 4.1+ using old authentication というエラーが現れ、接続することができません。 mysqlndを利用しないよう再コンパイルが必要となる。

解決方法

portでインストールしたモジュールを確認、mysqlndがactiveなってるはず。

sudo port installed

php5-mysql @5.3.5_0+mysqlnd (active)

そしてmysql5のvariantsを指定で再インストール。

% sudo port install php5-mysql +mysql5

--->  Computing dependencies for php5-mysql
--->  Fetching php5-mysql
--->  Verifying checksum(s) for php5-mysql
--->  Extracting php5-mysql
--->  Configuring php5-mysql
--->  Building php5-mysql
--->  Staging php5-mysql into destroot
--->  Installing php5-mysql @5.3.5_0+mysql5
--->  Deactivating php5-mysql @5.3.5_0+mysqlnd
--->  Cleaning php5-mysql
--->  Activating php5-mysql @5.3.5_0+mysql5
--->  Cleaning php5-mysql

再度port installedで確認すればmysql5がactiveになるはず。これで解決。

php5-mysql @5.3.5_0+mysqlnd
php5-mysql @5.3.5_0+mysql5 (active)

参考

【php】mysqlndを使うとMySQLに接続できない http://www.softel.co.jp/blogs/tech/archives/2225

SnowLeopard + PHP5.3でのMySQLリモート接続 http://taikimen.blogspot.com/2010/10/snowleopard-php53mysql.html

PHP: mysqlnd cannot connect to MySQL 4.1+ using old authentication http://www.bitshop.com/Blogs/tabid/95/EntryId/67/PHP-mysqlnd-cannot-connect-to-MySQL-4-1-using-old-authentication.aspx

おまけ

mysqlが古い16バイトのパスワードを使ってるかを確認する方法です。 mysqlにログインして下記コマンドを実行:

mysql> select password('aa');

+------------------+
| password('aa')         |
+------------------+
| 0123456789abcdef |
+------------------+

16位だっだら古いです。40位なら新しいってことです。

MacportでPHPをインストールし、CakePHPを動かしたら「Strict Standards」エラーが出ました。 当時のエラー本文は残ってませんので、Googleで検索したエラー本文を貼り付けます。パス以外は同じのはずです。

Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/basics.php on line 279
Strict Standards: Redefining already defined constructor for class Object in /Applications/MAMP/htdocs/xxxx/cake/libs/object.php on line 65
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/object.php on line 92
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/inflector.php on line 65
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/configure.php on line 96
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/configure.php on line 154
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/cache.php on line 71
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/cache.php on line 157
Strict Standards: Non-static method Configure::getInstance() should not be called statically in /Applications/MAMP/htdocs/xxxx/cake/bootstrap.php on li

解決方法

これはCakePHPの問題ではなく、PHPのerror_reportingの設定問題だそうです。 php.iniを開いてerror_reportingで検索します。 値をE_ALLに変更すれば解決です。

ちなみにMacportでPHPをインストールしたときのphp.iniパスは/opt/local/etc/php5/php.iniになります。

参考リンク

http://oldblog.awpny.com/2007/12/mamp-php5-cakephp-and-strict-standards/

MacportでPHPをインストールし、CakePHPを動かしたら「Strict Standards」エラーが出ました。 当時のエラー本文は残ってませんので、Googleで検索したエラー本文を貼り付けます。パス以外は同じのはずです。

Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/basics.php on line 279
Strict Standards: Redefining already defined constructor for class Object in /Applications/MAMP/htdocs/xxxx/cake/libs/object.php on line 65
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/object.php on line 92
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/inflector.php on line 65
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/configure.php on line 96
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/configure.php on line 154
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/cache.php on line 71
Strict Standards: Assigning the return value of new by reference is deprecated in /Applications/MAMP/htdocs/xxxx/cake/libs/cache.php on line 157
Strict Standards: Non-static method Configure::getInstance() should not be called statically in /Applications/MAMP/htdocs/xxxx/cake/bootstrap.php on li

解決方法

これはCakePHPの問題ではなく、PHPのerror_reportingの設定問題だそうです。 php.iniを開いてerror_reportingで検索します。 値をE_ALLに変更すれば解決です。

ちなみにMacportでPHPをインストールしたときのphp.iniパスは/opt/local/etc/php5/php.iniになります。

参考リンク

http://oldblog.awpny.com/2007/12/mamp-php5-cakephp-and-strict-standards/

#api #php #php #snippet

file_get_contentsとjson_decodeの組み合わせでAPIコールするサンプルコードです。

// APIコール
$api_url = 'http://example.com/api/';
$api_ret = file_get_contents($api_url);

// JSONにデコード
$api_result = json_decode($api_ret,true);

// APIエラーチェック: 何かしらの成功フラグでチェック
if(isset($api_result*'success']) && $api_result['success'* == 0)
{
    // 処理
}
else
{
    // handle error
}

#api #php #php #snippet

file_get_contentsとjson_decodeの組み合わせでAPIコールするサンプルコードです。

// APIコール
$api_url = 'http://example.com/api/';
$api_ret = file_get_contents($api_url);

// JSONにデコード
$api_result = json_decode($api_ret,true);

// APIエラーチェック: 何かしらの成功フラグでチェック
if(isset($api_result*'success']) && $api_result['success'* == 0)
{
    // 処理
}
else
{
    // handle error
}

#php #php #xampp #oracle #環境構築

Oracle Instantclientをインストールすることで、PHPからOracleデータベースへの接続が可能になります。

XAMPPのデフォルトインストールではそれが無効となっています。確認方法はphpinfoのページから’oci8’を検索して何もなかったらつまり接続できてないことです。

手順

  • php.ini(XAMPP/phpのパスにある)の中から;extension=php_oci8.dllを検索して、セミコロン(;)を削除。
  • Oracleから“Instant Client Package – Basic” for Windowsをダウンロードし、任意の場所に解凍。ここではc:\instantclient_11_1とする。
  • Windowsの環境変数pathに上記instantclientが解凍されたパスを追加(c:\instantclient_11_1)
  • そしてWindowsを再起動!
  • Apacheを再起動

確認

phpinfoのページからoci8を検索してあれば成功!

その他

  • ORACLE_HOMEやORACLE_SIDなどの環境変数はInstant Clientでは必要ないから設定しなくても大丈夫だそう。
  • パス設定後Windowsを再起動しないと、”unable to load dynamic library php_oci8.dll”のようなエラーが出た。
#php #php #xampp #oracle #環境構築

Oracle Instantclientをインストールすることで、PHPからOracleデータベースへの接続が可能になります。

XAMPPのデフォルトインストールではそれが無効となっています。確認方法はphpinfoのページから’oci8’を検索して何もなかったらつまり接続できてないことです。

手順

  • php.ini(XAMPP/phpのパスにある)の中から;extension=php_oci8.dllを検索して、セミコロン(;)を削除。
  • Oracleから“Instant Client Package – Basic” for Windowsをダウンロードし、任意の場所に解凍。ここではc:\instantclient_11_1とする。
  • Windowsの環境変数pathに上記instantclientが解凍されたパスを追加(c:\instantclient_11_1)
  • そしてWindowsを再起動!
  • Apacheを再起動

確認

phpinfoのページからoci8を検索してあれば成功!

その他

  • ORACLE_HOMEやORACLE_SIDなどの環境変数はInstant Clientでは必要ないから設定しなくても大丈夫だそう。
  • パス設定後Windowsを再起動しないと、”unable to load dynamic library php_oci8.dll”のようなエラーが出た。
#php #php #cakephp #model #orm
$this->Ingredient->save($newData);
$newIngredientId = $this->Ingredient->id;    // OK
// id以外のフィールドはダメ
$this->Ingredient->name;    // NG
$this->Ingredient->category;    // NG

登録/更新には関係なく。 公式マニュアルでは:

一度保存が完了してしまうと、オブジェクトの ID をモデルオブジェクトの $id プロパティで取得することができます。特に新しいオブジェクトを生成した場合に便利です。

と書いてありますが、id以外のフィールド情報は持ってないようです。 欲しければ$this->dataから取れます。

#php #php #cakephp #model #orm
$this->Ingredient->save($newData);
$newIngredientId = $this->Ingredient->id;    // OK
// id以外のフィールドはダメ
$this->Ingredient->name;    // NG
$this->Ingredient->category;    // NG

登録/更新には関係なく。 公式マニュアルでは:

一度保存が完了してしまうと、オブジェクトの ID をモデルオブジェクトの $id プロパティで取得することができます。特に新しいオブジェクトを生成した場合に便利です。

と書いてありますが、id以外のフィールド情報は持ってないようです。 欲しければ$this->dataから取れます。

#php #php #string
/##
 #  文字列を全て半角に
 #  @param  string $str 文字列
 #  @return string $str 半角の文字列
 # /
function toHankaku($str) {
    $str= mb_convert_kana($str,"rnask");
    return $str;
}
#php #php #string
/##
 #  文字列を全て半角に
 #  @param  string $str 文字列
 #  @return string $str 半角の文字列
 # /
function toHankaku($str) {
    $str= mb_convert_kana($str,"rnask");
    return $str;
}
#php #php

$_GET、 $_POST そして $_COOKIE の内容をまとめた連想配列です。

もう少し説明を加えると、

In the beginning of execution, $_REQUEST is a clone of $_GET. $_POST is then merged into the array, overwriting keys if they exist in both $_GET and $_POST. Finally, $_COOKIE is merged into the array, again overwriting old values.

まずは$_GETのクローンでそこに$_POSTをマージする感じで、同じキーのものがあれば上書きされます。同じくその後$_COOKIEもマージします。 なので本当にPOSTで受取るものは$_REQUESTに書き換えてはいけないと思いますね。

#php #php

$_GET、 $_POST そして $_COOKIE の内容をまとめた連想配列です。

もう少し説明を加えると、

In the beginning of execution, $_REQUEST is a clone of $_GET. $_POST is then merged into the array, overwriting keys if they exist in both $_GET and $_POST. Finally, $_COOKIE is merged into the array, again overwriting old values.

まずは$_GETのクローンでそこに$_POSTをマージする感じで、同じキーのものがあれば上書きされます。同じくその後$_COOKIEもマージします。 なので本当にPOSTで受取るものは$_REQUESTに書き換えてはいけないと思いますね。

#apache #php #php #memcache

My環境

XAMPP1.7.3 + WinXP ダウンロードはこちら

memcache側の設定

memcacheのインストール手順

  • http://code.jellycan.com/memcached/よりmemcached 1.2.6 => win32 binaryバージョンのファイルをダウンロード +zipファイルを適当な場所(例えばc:\memcached)に解凍 +コマンドプロンプトから下記コマンドを叩く、Windowsサービスとしてインストール。これで今度Windowsが起動すると自動でmemcacheサーバが起動してくれる。
    c:\memcached.exe -d install
    

memcacheの起動(初回のみ)

コマンドプロンプト

c:\memcached\memcached.exe -d start

php側

php.iniの設定

XAMPPのパス/php/php.iniを編集:下記コードを追加

extension = php_memcache.dll

ここはLinux環境と違い拡張子が.soではなく.dll。

php_memcache.dllのダウンロード

http://downloads.php.net/pierre/から’memcache’を検索して正しいバージョンのファイルをダウンロード。 そしてxampp/php/extに入れる。

ここで問題!正しいバージョンはなんなのか?間違ってダウンロードすると後でApacheサーバを立ち上がるときエラーが出るよ。私の環境だとphp_memcache-cvs-20090703-5.3-VC6-x86.zipのファイルが正しいけど、今時点で上記URLには載せていない。結構ググって見ても結局古い結果で、しょうがなく友人からそのファイル貰った。。。ここにアップしたので、必要な方はダウンロードしてください。ウイルススキャンしてね。。 <a href=’https://images.kinopyo.com/wp-content/uploads/2010/11/php_memcache-cvs-20090703-5.3-VC6-x86.zip)>php_memcache-cvs-20090703-5.3-VC6-x86</a>

動作確認

xamppでapacheサーバを起動、下記内容をphpファイルと保存してサーバのDocumentパス(デフォルトではXAMPP/htdocs)に置く。


<?php
    $memcache = new Memcache; // instantiating memcache extension class
    $memcache->connect("localhost",11211); // try 127.0.0.1 instead of localhost
                                           // if it is not working

    echo "Server's version: " . $memcache->getVersion() . "<br />\n";

    // we will create an array which will be stored in cache serialized
    $testArray = array('horse', 'cow', 'pig');
    $tmp       = serialize($testArray);

    $memcache->add("key", $tmp, 30);

    echo "Data from the cache:<br />\n";
    print_r(unserialize($memcache->get("key")));
?>

おまけ:memcacheメモリの調整

Memcached, by default, loads with 64mb of memory for it’s use which is low for most applications. To change this to something else, navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server in your registry, find the ImagePath entry and change it to look something like this:

“C:\memcached\memcached.exe” -d runservice -m 512

参考

http://www.codeforest.net/how-to-install-memcached-on-windows-machine http://pureform.wordpress.com/2008/01/10/installing-memcache-on-windows-for-php/

#apache #php #php #memcache

My環境

XAMPP1.7.3 + WinXP ダウンロードはこちら

memcache側の設定

memcacheのインストール手順

  • http://code.jellycan.com/memcached/よりmemcached 1.2.6 => win32 binaryバージョンのファイルをダウンロード +zipファイルを適当な場所(例えばc:\memcached)に解凍 +コマンドプロンプトから下記コマンドを叩く、Windowsサービスとしてインストール。これで今度Windowsが起動すると自動でmemcacheサーバが起動してくれる。
    c:\memcached.exe -d install
    

memcacheの起動(初回のみ)

コマンドプロンプト

c:\memcached\memcached.exe -d start

php側

php.iniの設定

XAMPPのパス/php/php.iniを編集:下記コードを追加

extension = php_memcache.dll

ここはLinux環境と違い拡張子が.soではなく.dll。

php_memcache.dllのダウンロード

http://downloads.php.net/pierre/から’memcache’を検索して正しいバージョンのファイルをダウンロード。 そしてxampp/php/extに入れる。

ここで問題!正しいバージョンはなんなのか?間違ってダウンロードすると後でApacheサーバを立ち上がるときエラーが出るよ。私の環境だとphp_memcache-cvs-20090703-5.3-VC6-x86.zipのファイルが正しいけど、今時点で上記URLには載せていない。結構ググって見ても結局古い結果で、しょうがなく友人からそのファイル貰った。。。ここにアップしたので、必要な方はダウンロードしてください。ウイルススキャンしてね。。 <a href=’https://images.kinopyo.com/wp-content/uploads/2010/11/php_memcache-cvs-20090703-5.3-VC6-x86.zip)>php_memcache-cvs-20090703-5.3-VC6-x86</a>

動作確認

xamppでapacheサーバを起動、下記内容をphpファイルと保存してサーバのDocumentパス(デフォルトではXAMPP/htdocs)に置く。


<?php
    $memcache = new Memcache; // instantiating memcache extension class
    $memcache->connect("localhost",11211); // try 127.0.0.1 instead of localhost
                                           // if it is not working

    echo "Server's version: " . $memcache->getVersion() . "<br />\n";

    // we will create an array which will be stored in cache serialized
    $testArray = array('horse', 'cow', 'pig');
    $tmp       = serialize($testArray);

    $memcache->add("key", $tmp, 30);

    echo "Data from the cache:<br />\n";
    print_r(unserialize($memcache->get("key")));
?>

おまけ:memcacheメモリの調整

Memcached, by default, loads with 64mb of memory for it’s use which is low for most applications. To change this to something else, navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server in your registry, find the ImagePath entry and change it to look something like this:

“C:\memcached\memcached.exe” -d runservice -m 512

参考

http://www.codeforest.net/how-to-install-memcached-on-windows-machine http://pureform.wordpress.com/2008/01/10/installing-memcache-on-windows-for-php/

#php #php #smarty

Smarty templateの作成

application/viewsにhello.tplというファイルを作成します。

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>{$title}</title>
</head>
<body>
	hello, {$name}
</body>
</html>

Controllerの作成

hello.phpというControllerを作成します。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Hello extends Controller {

	public function action_index()
	{
		$view = View::factory("smarty:hello");
		$view->name = "kinopyo!";
		$view->title = "Smarty & Kohana Sample";
		$this->request->response = $view;
	}
}

View::factoryに”smarty:”というプリフィックスを書くことでSmartyテンプレートとして認識してくれます。

動作確認

http://127.0.0.1/myapp/helloにアクセスし、”hello, kinopyo!”が表示されれば成功です。

Controller_Templateの場合

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Hello extends Controller_Template {

	public $template = 'smarty:hello';

	public function action_index()
	{
		$this->template->name = 'kinopyo!';
		$this->template->title = "Hello Title";
	}

}
#php #php #smarty

Smarty templateの作成

application/viewsにhello.tplというファイルを作成します。

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>{$title}</title>
</head>
<body>
	hello, {$name}
</body>
</html>

Controllerの作成

hello.phpというControllerを作成します。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Hello extends Controller {

	public function action_index()
	{
		$view = View::factory("smarty:hello");
		$view->name = "kinopyo!";
		$view->title = "Smarty & Kohana Sample";
		$this->request->response = $view;
	}
}

View::factoryに”smarty:”というプリフィックスを書くことでSmartyテンプレートとして認識してくれます。

動作確認

http://127.0.0.1/myapp/helloにアクセスし、”hello, kinopyo!”が表示されれば成功です。

Controller_Templateの場合

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Hello extends Controller_Template {

	public $template = 'smarty:hello';

	public function action_index()
	{
		$this->template->name = 'kinopyo!';
		$this->template->title = "Hello Title";
	}

}
#php #smarty #mac #環境構築

Smartyのインストールはphp.iniにインクルードパスを書く方法と書かない方法があります。ここではphpのインクルードパスに書く方法を紹介します。

1 Smartyをダウンロード

http://www.smarty.net/download.phpからダウンロードします。今回は3.0rc3にしました。

2 ファイルの解凍

できたフォルダ名はSmarty-3.0rc3で、それをsmartyにリネームして、/Applications/XAMPP/xamppfiles/lib/phpに移動します。こうするのはここがXAMPPの場合のinclude_pathになるからです。

3 php.iniを変更して、smartyを読み込ませる

php.ini中のinclude_pathに”.:/Applications/XAMPP/xamppfiles/lib/php/smarty/libs”の記述を追加します。 できたイメージはこうなります。

include_path=".:/Applications/XAMPP/xamppfiles/lib/php:/Applications/XAMPP/xamppfiles/lib/php/pear.:/Applications/XAMPP/xamppfiles/lib/php/smarty/libs"

4 smartyが必要なフォルダを作成します。

smartyは四つのフォルダが必要です:

  • templates
  • templates_c
  • cache
  • config

templates_cとcacheフォルダには適切な書き込み権限を付与しなければなりません。 場所は任意のはずです。ここではこんな形にしました。htdocsはXAMPPのウェブルートフォルダです。

  • /Applications/XAMPP/xamppfiles/htdocs/smarty/templates
  • /Applications/XAMPP/xamppfiles/htdocs/smarty/config
  • /Users/zolo/Develop/smarty/templates_c
  • /Users/zolo/Develop/smarty/cache

5 smartyテンプレートを作成

上記templatesフォルダにsmarty.tplというファイルを作成します。

<html>
<body>
Hello, {$name}!
</body>
</html>

6 テンプレートに値をセットするphpファイルを作成

/Applications/XAMPP/xamppfiles/htdocs/にsmarty.phpというファイルを作成します。

<?php

// load Smarty library
require('Smarty.class.php');

$smarty = new Smarty;

$smarty->template_dir = '/Applications/XAMPP/xamppfiles/htdocs/smarty/templates';
$smarty->config_dir = ' /Applications/XAMPP/xamppfiles/htdocs/smarty/config';
$smarty->cache_dir = '/Users/zolo/Develop/smarty/cache';
$smarty->compile_dir = '/Users/zolo/Develop/smarty/templates_c';

$smarty->assign('name','kinopyo!');

$smarty->display('smarty.tpl');
?>

7 動作確認

php.iniを編集したため、まずはapacheを再起動します。 そしてhttp://127.0.0.1/smarty.phpにアクセスしてエラーがなければOKです。

参考リンク:

http://news.php.net/php.smarty.dev/2703

#php #php #smarty #環境構築

ダウンロード

http://wiki.github.com/MrAnchovy/kohana-module-smarty/

インストール

githubでも手順がとても分かりやすいので直接引用させていただきます。

  1. Download the latest version from the links above
  2. Unpack the downloaded file
  3. Move the smarty directory into the Kohana modules directory
  4. Enable the module in your application’s bootstrap.php
Kohana::modules(array(
  'auth' => MODPATH.'auth', // Basic authentication
  // 'cache' => MODPATH.'cache', // Caching with multiple backends
  // 'codebench' => MODPATH.'codebench', // Benchmarking tool
  'database' => MODPATH.'database', // Database access
  // 'image' => MODPATH.'image', // Image manipulation
  'orm' => MODPATH.'orm', // Object Relationship Mapping
  'pagination' => MODPATH.'pagination', // Paging of results
  'userguide' => MODPATH.'userguide', // User guide and API documentation
  'smarty' => MODPATH.'smarty', // smarty template module.
));
  1. Visit the page www.yoursite.com/smarty to confirm all is OK

その他リンク

このモジュールのファイル構造: http://github.com/MrAnchovy/kohana-module-smarty/wiki/file-structure

#php #php #smarty #環境構築

ダウンロード

http://wiki.github.com/MrAnchovy/kohana-module-smarty/

インストール

githubでも手順がとても分かりやすいので直接引用させていただきます。

  1. Download the latest version from the links above
  2. Unpack the downloaded file
  3. Move the smarty directory into the Kohana modules directory
  4. Enable the module in your application’s bootstrap.php
Kohana::modules(array(
  'auth' => MODPATH.'auth', // Basic authentication
  // 'cache' => MODPATH.'cache', // Caching with multiple backends
  // 'codebench' => MODPATH.'codebench', // Benchmarking tool
  'database' => MODPATH.'database', // Database access
  // 'image' => MODPATH.'image', // Image manipulation
  'orm' => MODPATH.'orm', // Object Relationship Mapping
  'pagination' => MODPATH.'pagination', // Paging of results
  'userguide' => MODPATH.'userguide', // User guide and API documentation
  'smarty' => MODPATH.'smarty', // smarty template module.
));
  1. Visit the page www.yoursite.com/smarty to confirm all is OK

その他リンク

このモジュールのファイル構造: http://github.com/MrAnchovy/kohana-module-smarty/wiki/file-structure

#php #php #memcache #環境構築

前提条件

memcacheとphp_memcache extensionがインストールされたこと。 https://kinopyo.com/ja/blog/install-memcache-and-php-extension-in-mac-xampp/を参考してください。

手順

1. application/bootstrap.phpを編集

Kohana::modulesのcacheのコメントを外します。 Kohana active cache in bootstrap.php

2. 下記の内容でconfig/cache.phpを作成

場所はapplication/configでもいいしsystem/config、modules/configでもいいです。

<?php defined('SYSPATH') or die('No direct script access.');
return array
(
	'default'  => array
	(
		'driver'             => 'memcache',
		'default_expire'     => 3600,
		// Use Zlib compression (can cause issues with integers)
		'compression'        => FALSE,
		'servers'            => array
		(
			array
			(
				// Memcache Server
				'host'             => '127.0.0.1',
				// Memcache port number
				'port'             => 11211,
				// Persistent connection
				'persistent'       => FALSE,
			),
		),
	),

);

3. 動作確認

まずはmemcacheを立ち上がってください。(ターミナルでmemcached -m 8 -l 127.0.0.1 -p 11211 -d ) そしてbootstrap.phpの最後にテスト用のコードを追記します。

$cache = Cache::instance();
$cache->set('hello','world');
die(var_dump($cache->get('hello')));

これで任意のページを開いて下記の内容が表示されれば成功ってことです。 string(5) “world”

テスト成功したらbootstrap.phpからテスト用のコードを削除してください。

#php #php #memcache #環境構築

前提条件

memcacheとphp_memcache extensionがインストールされたこと。 https://kinopyo.com/ja/blog/install-memcache-and-php-extension-in-mac-xampp/を参考してください。

手順

1. application/bootstrap.phpを編集

Kohana::modulesのcacheのコメントを外します。 Kohana active cache in bootstrap.php

2. 下記の内容でconfig/cache.phpを作成

場所はapplication/configでもいいしsystem/config、modules/configでもいいです。

<?php defined('SYSPATH') or die('No direct script access.');
return array
(
	'default'  => array
	(
		'driver'             => 'memcache',
		'default_expire'     => 3600,
		// Use Zlib compression (can cause issues with integers)
		'compression'        => FALSE,
		'servers'            => array
		(
			array
			(
				// Memcache Server
				'host'             => '127.0.0.1',
				// Memcache port number
				'port'             => 11211,
				// Persistent connection
				'persistent'       => FALSE,
			),
		),
	),

);

3. 動作確認

まずはmemcacheを立ち上がってください。(ターミナルでmemcached -m 8 -l 127.0.0.1 -p 11211 -d ) そしてbootstrap.phpの最後にテスト用のコードを追記します。

$cache = Cache::instance();
$cache->set('hello','world');
die(var_dump($cache->get('hello')));

これで任意のページを開いて下記の内容が表示されれば成功ってことです。 string(5) “world”

テスト成功したらbootstrap.phpからテスト用のコードを削除してください。

#php #php #mac #memcache #環境構築

環境情報

  • Mac OSX Snow Leopard 10.6.4
  • XAMPP 1.7.3

手順書

1. Apple Developer Tools (Xcode)の最新版をインストール

2. XAMPP Developer Packageをインストール

http://www.apachefriends.org/en/xampp-macosx.htmlより下記赤線のリンクをダウンロードします。 xampp develop package for mac 参考リンク:http://blog.m-schmidt.eu/2010/03/30/develop-memcached-web-apps-with-xampp-under-mac-os-x/ ダウンロードしたdmgファイルを開いてDevel-Package.mpkgをダブルクリックでインストールします。

3. ターミナルを開いて(/Applications/Utilities/Terminal)下記コマンドを実行

cd /tmp
pecl download memcache
tar xzf memcache-2.2.5.tgz
cd memcache-2.2.5
/Applications/XAMPP/xamppfiles/bin/phpize-5.3.1
MACOSX_DEPLOYMENT_TARGET=10.6 CFLAGS='-O3 -fno-common -arch i386 -arch x86_64' LDFLAGS='-O3 -arch i386 -arch x86_64' CXXFLAGS='-O3 -fno-common -arch i386 -arch x86_64' ./configure --with-php-config=/Applications/XAMPP/xamppfiles/bin/php-config-5.3.1
make
sudo make install

成功したら/Applications/XAMPP/xamppfiles/lib/php/php-5.3.1/extensions/no-debug-non-zts-xxxxのフォルダ(xxは20090626みたいな日付)にmemcache.soというファイルが生成されます。

4. php.iniファイルの編集

/Applications/XAMPP/xamppfiles/etc/php.iniファイルを開いて”Dynamic Extensions”のブロックを検索し、下記内容を追記します。私の環境では538行くらいでした。

extension=memcache.so

こんあ感じです。 Add memcache extention to php.ini

5.memcacheを立ち上がる

ターミナルで下記コマンドを実行します。

memcached -m 8 -l 127.0.0.1 -p 11211 -d

これは自分の環境でmemcacheをIP:127.0.0.1、ポート:11211、8MBのRAMスペースで立ち上がる意味です。

6. phpで動作確認

下記ファイルを用意します。ファイル名は任意です(ここではmemcache.phpとしました)。

<?php

$memcache = memcache_connect('127.0.0.1', 11211);

if ($memcache) {
	$memcache->set("str_key", "String to store in memcached");
	$memcache->set("num_key", 123);

	$object = new StdClass;
	$object->attribute = 'test';
	$memcache->set("obj_key", $object);

	$array = Array('assoc'=>123, 345, 567);
	$memcache->set("arr_key", $array);

	var_dump($memcache->get('str_key'));
	var_dump($memcache->get('num_key'));
	var_dump($memcache->get('obj_key'));
}
else {
	echo "Connection to memcached failed";
}
?>

これを/Applications/XAMPP/xamppfiles/htdocsに置いて、ブラウザでhttp://localhost/memcache.php(あるいはhttp://127.0.0.1/memcache.php)を開きます。 下記のようなページが表示されればOKです。 memcache test in php

ちなみにmemcacheを停止するコマンドは:

killall memcached
#php #php #mac #memcache #環境構築

環境情報

  • Mac OSX Snow Leopard 10.6.4
  • XAMPP 1.7.3

手順書

1. Apple Developer Tools (Xcode)の最新版をインストール

2. XAMPP Developer Packageをインストール

http://www.apachefriends.org/en/xampp-macosx.htmlより下記赤線のリンクをダウンロードします。 xampp develop package for mac 参考リンク:http://blog.m-schmidt.eu/2010/03/30/develop-memcached-web-apps-with-xampp-under-mac-os-x/ ダウンロードしたdmgファイルを開いてDevel-Package.mpkgをダブルクリックでインストールします。

3. ターミナルを開いて(/Applications/Utilities/Terminal)下記コマンドを実行

cd /tmp
pecl download memcache
tar xzf memcache-2.2.5.tgz
cd memcache-2.2.5
/Applications/XAMPP/xamppfiles/bin/phpize-5.3.1
MACOSX_DEPLOYMENT_TARGET=10.6 CFLAGS='-O3 -fno-common -arch i386 -arch x86_64' LDFLAGS='-O3 -arch i386 -arch x86_64' CXXFLAGS='-O3 -fno-common -arch i386 -arch x86_64' ./configure --with-php-config=/Applications/XAMPP/xamppfiles/bin/php-config-5.3.1
make
sudo make install

成功したら/Applications/XAMPP/xamppfiles/lib/php/php-5.3.1/extensions/no-debug-non-zts-xxxxのフォルダ(xxは20090626みたいな日付)にmemcache.soというファイルが生成されます。

4. php.iniファイルの編集

/Applications/XAMPP/xamppfiles/etc/php.iniファイルを開いて”Dynamic Extensions”のブロックを検索し、下記内容を追記します。私の環境では538行くらいでした。

extension=memcache.so

こんあ感じです。 Add memcache extention to php.ini

5.memcacheを立ち上がる

ターミナルで下記コマンドを実行します。

memcached -m 8 -l 127.0.0.1 -p 11211 -d

これは自分の環境でmemcacheをIP:127.0.0.1、ポート:11211、8MBのRAMスペースで立ち上がる意味です。

6. phpで動作確認

下記ファイルを用意します。ファイル名は任意です(ここではmemcache.phpとしました)。

<?php

$memcache = memcache_connect('127.0.0.1', 11211);

if ($memcache) {
	$memcache->set("str_key", "String to store in memcached");
	$memcache->set("num_key", 123);

	$object = new StdClass;
	$object->attribute = 'test';
	$memcache->set("obj_key", $object);

	$array = Array('assoc'=>123, 345, 567);
	$memcache->set("arr_key", $array);

	var_dump($memcache->get('str_key'));
	var_dump($memcache->get('num_key'));
	var_dump($memcache->get('obj_key'));
}
else {
	echo "Connection to memcached failed";
}
?>

これを/Applications/XAMPP/xamppfiles/htdocsに置いて、ブラウザでhttp://localhost/memcache.php(あるいはhttp://127.0.0.1/memcache.php)を開きます。 下記のようなページが表示されればOKです。 memcache test in php

ちなみにmemcacheを停止するコマンドは:

killall memcached
#php #php

kohanaというphpフレームワークを触り始めました。MVCパターンなのでいろんなところで結構Railsと似ていますが、コード量が明らかにRailsより多くてまだ慣れてません。さすがにRailsやってから他の言語やフレームワークを触るとキツイです。

kohanaにはデフォルトでmodulesにuserguideが付いてます。ローカルでもガイドのドキュメントやAPIを参照できるため結構便利です。

userguideモジュールをアクティブする方法

bootstrap.phpの中に’userguide’を検索してコメントアウトします。

アクセスURL

例えばbase_urlが’myapp’の場合は: http://localhost/myapp/userguide/docs になります。

内容としては公式サイトのhttp://kohanaframework.org/guide/about.kohanaと同じになります。

#php #php

kohanaというphpフレームワークを触り始めました。MVCパターンなのでいろんなところで結構Railsと似ていますが、コード量が明らかにRailsより多くてまだ慣れてません。さすがにRailsやってから他の言語やフレームワークを触るとキツイです。

kohanaにはデフォルトでmodulesにuserguideが付いてます。ローカルでもガイドのドキュメントやAPIを参照できるため結構便利です。

userguideモジュールをアクティブする方法

bootstrap.phpの中に’userguide’を検索してコメントアウトします。

アクセスURL

例えばbase_urlが’myapp’の場合は: http://localhost/myapp/userguide/docs になります。

内容としては公式サイトのhttp://kohanaframework.org/guide/about.kohanaと同じになります。