【php】【関数】localhostか否かを判定してDB接続文字列を自動的に切り替える関数

localhost(開発環境)か否かを判定して、DB接続文字列を自動で切り替える関数。開発環境と本番環境でアップロードファイルを分けなくていいので便利。

class dbConsts {

    public $host;
    public $dbName;
    public $user;
    public $pass;
    public $DSN;

    public function __construct() {
        if (
                $_SERVER['SERVER_ADDR'] === 'localhost' || $_SERVER['SERVER_ADDR'] === '127.0.0.1'
        ) {
            //localhostだ
            $this->host = 'localhost';
            $this->dbName = 'dbName';
            $this->user = 'root';
            $this->pass = 'rootpassword';
            $this->DSN = $this->retDSN($this->host, $this->dbName);
        } else {
            //localhostではない
            $this->host = 'example.com';
            $this->dbName = 'exampleDB';
            $this->user = 'exampleUser';
            $this->pass = 'examplePassword';
            $this->DSN = $this->retDSN($this->host, $this->dbName);
        }
    }

    public function retDSN($host, $dbName) {
        return 'mysql:dbhost=' . $this->host . ';dbname=' . $this->dbName;
    }

}

使う時はNewして使う。

$objDBInfo = new dbConsts();
$db = new PDO($objDBInfo->DSN, $objDBInfo->user, $objDBInfo->pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $db->prepare('set names utf8;');
$stmt->execute();

以上。

ライセンスはMIT。ご自由に使って下さい。


もしサポート頂けたなら、そのお金は、私が全力で生きるために使います。