1. 程式人生 > >PHP-執行外部程式

PHP-執行外部程式

備份/恢復資料庫

exec — 執行一個外部程式(在php檔案所在目錄進行執行)

很久以前寫的,很多方法是專案中的直接複製粘體用不了,只能提供下思路。
用到執行外部程式的就這一句:
exec("mysql -u$username -p$password $database < $backup_path$backup_name");

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Database extends MY_Controller {
    private $backup_path;
    public function __construct(){
        parent::__construct();
        $this->backup_path = dirname($_SERVER['SCRIPT_FILENAME']).DIRECTORY_SEPARATOR.'db_backup'.DIRECTORY_SEPARATOR;
    }

    public function index(){
        $this->loadViewhf('back/database.html');
    }

    public function list_backup(){
        
        //開啟資料夾
        $dir_handle = opendir($this->backup_path);
        //讀取資料夾
        $backup_names = array(); 
        while(false !== $file = readdir($dir_handle)){
            if ($file == '.' || $file == '..') continue;
            // 建立每一行資料
            $table_row_map = (object)array(
                'backup_name' => $file,
                'backup_path' => '~/db_backup'
                );
            // 加入每一行資料到data
            $result['data'][] = $table_row_map;
        }
        //返回結果  
        $this->returnResult($result);
    }


    public function backup(){

        // 選擇備份路徑(網站根目錄下的db_backup資料夾)
        $backup_path = $this->backup_path;
        // 生成備份檔名
        $backup_name = date("Y-m-d_H-i-s").'_backup.sql';;
        // 進行備份
        $username = $this->db->username;
        $password = $this->db->password;
        $database = $this->db->database;
        exec("mysqldump -u$username -p$password $database > $backup_path$backup_name");
        // 返回結果
        $result['status'] = true;
        $this->returnResult($result);
    }

    public function del_backup(){
        // 備份檔名
        $backup_name = $this->input->post('backup_name', true);
        // 選擇備份路徑(網站根目錄下的db_backup資料夾)
        $backup_path = $this->backup_path;
        // 刪除
        if (unlink($backup_path.$backup_name)) {
            $result['status'] = true;
        }else{
            $result['status'] = false;
        }
        // 返回結果
        $this->returnResult($result);
    }

    public function recover_backup(){
        // 備份檔名
        $backup_name = $this->input->post('backup_name', true);
        // 選擇備份路徑(網站根目錄下的db_backup資料夾)
        $backup_path = $this->backup_path;
        // 恢復備份
        $username = $this->db->username;
        $password = $this->db->password;
        $database = $this->db->database;
        exec("mysql -u$username -p$password $database < $backup_path$backup_name");
        // 返回結果
        $result['status'] = true;
        $this->returnResult($result);
    }

}