Kinopyo Blog

プログラマとしてRuby, Rails, iPhone, iPad,Macなどなどと向き合う日々のログポース

Posts Tagged ‘PHP’

PHP: mysqlnd cannot connect to MySQL 4.1+ using old authentication

2011年03月17日

問題

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

http://www.php.net/manual/ja/migration53.incompatible.php

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を利用しないよう再コンパイルが必要となる。

http://taikimen.blogspot.com/2010/10/snowleopard-php53mysql.html

解決方法

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位なら新しいってことです。

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/

PHPで他のJSON形式APIをコールするサンプルコード

2011年03月07日

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
}

Windows XAMPPにOracle Instantclientをインストール

2011年02月18日

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”のようなエラーが出た。

CakePHP: $model->save()後、$model->id以外のフィールド情報は持ってない

2011年02月03日
$this->Ingredient->save($newData);
$newIngredientId = $this->Ingredient->id;    // OK
// id以外のフィールドはダメ
$this->Ingredient->name;    // NG
$this->Ingredient->category;    // NG

登録/更新には関係なく。

公式マニュアルでは:

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

http://book.cakephp.org/ja/view/75/データを保存する

と書いてありますが、id以外のフィールド情報は持ってないようです。

欲しければ$this->dataから取れます。

PHP:文字列を全て半角に

2011年02月01日
    /**
     * 文字列を全て半角に
     * @param  string $str 文字列
     * @return string $str 半角の文字列
     */
    function toHankaku($str) {
        $str= mb_convert_kana($str,"rnask");
        return $str;
    }

PHP: $_REQUESTと$_GET、$_POSTはどこが違うか

2010年12月27日

$_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でJSONPを返すサンプルコード

2010年12月21日

PHP側で

echo $_GET['callback'] . '(' . json_encode($object) . ');';

JS側で

    $(function(){
         $.getJSON('foo.php?callback=?',
                    {},  // No additional parameters sent
                    function (data) {
                         // data is now JSON object instantiated from retrieved info
                         alert(data['key']);
         });
    });

参考:

http://www.carolinamantis.com/wordpress/?p=29

Windowsにmemcacheをインストール、PHPの設定

2010年11月26日

My環境

XAMPP1.7.3 + WinXP

ダウンロードはこちら

memcache側の設定

memcacheのインストール手順
  1. http://code.jellycan.com/memcached/よりmemcached 1.2.6 => win32 binaryバージョンのファイルをダウンロード
  2. zipファイルを適当な場所(例えばc:\memcached)に解凍
  3. コマンドプロンプトから下記コマンドを叩く、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には載せていない。結構ググって見ても結局古い結果で、しょうがなく友人からそのファイル貰った。。。ここにアップしたので、必要な方はダウンロードしてください。ウイルススキャンしてね。。

php_memcache-cvs-20090703-5.3-VC6-x86

動作確認

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


connect("localhost",11211); // try 127.0.0.1 instead of localhost

                                           // if it is not working 

    echo "Server's version: " . $memcache->getVersion() . "\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:\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/

Kohana3にSmartyを利用するサンプル

2010年09月25日

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";
	}                             

}