Diễn đàn Nhật Bản - diendannhatban.info

NHÀ PHÁT TRIỂN - DEVELOPERS - 技術開発 => FRAMEWORK - SDK => CakePHP => Tác giả chủ đề:: admin trong Chủ nhật, 29/01/2017, 11:30:47 am

Tiêu đề: Khởi tạo biến trên ENV khi dev với CakePHP
Gửi bởi: admin trong Chủ nhật, 29/01/2017, 11:30:47 am
Keyword: cakephp, php, enviroment variable, env

1. Thiết lập biến trong file env.json (thêm vào .gitignore)
Code: Bạn không thể xem liên kết này. Đăng ký hoặc Đăng nhập
{
    "DB_USER" : "user_name",
    "DB_PASS" : "password"
}

2. Đọc file JSON và khởi tạo biến ENV trong bootstrap.php của CakePHP
Code: Bạn không thể xem liên kết này. Đăng ký hoặc Đăng nhập
<?php
# in Config/bootstrap.php

// import any environment variables from the .env file (if it exists)
// default .env path for cakephp APP . DS . '.env'
$env_file_path APP DS '.env';
if(
is_file($env_file_path))
{
    
$vars json_decode(file_get_contents($env_file_path), true);

    foreach(
$vars as $name => $val)
    {
        
putenv("$name=$val");
    }
}

Đọc biến ENV từ PHP
Code: Bạn không thể xem liên kết này. Đăng ký hoặc Đăng nhập
<?php
$connection 
open_con(getenv('DB_USER'), getenv('DB_PASS'));