简体   繁体   English

如果本地主机失败,php切换到服务器连接

[英]php switching to server connection if localhost failed

I'm trying to write a script that connects to an online server if localhost connection failed or inaccessible. 我正在尝试编写一个脚本,如果本地主机连接失败或无法访问,该脚本将连接到在线服务器。 I have the script below that connects to a localhost database and if it's not accessible then reroute to a server connection. 我下面有连接到本地主机数据库的脚本,如果无法访问,请重新路由到服务器连接。 The script somehow fails to work and I just don't know why. 该脚本某种程度上无法正常工作,我只是不知道为什么。 Anyone has any suggestions? 有人有建议吗?

<?php
  $DB_HOST = 'localhost';
  $DB_USER = 'root';
  $DB_PASS = '';
  $DB_NAME = 'admin';

  $DB_CON_A = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);

  if(!$DB_CON_A) {
    die($DB_CON_A);
    $DB_HOST = 'www.xyz.com';
    $DB_USER = 'admin';
    $DB_PASS = '1235kasK';
    $DB_NAME = 'admin';
  }

  try {
    $DB_CON_A = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
    $DB_CON_A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  catch(PDOException $e){
    echo $e->getMessage();
  }

Here is my solution for those who's looking for one: 这是我为那些正在寻找的人的解决方案:

    <?php
      function ping($DB_HOST) {
        exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($DB_HOST)), $res, $rval);
        return $rval === 0;
      }

      $DB_HOST = 'www.xyz.com';
      $connected = ping($DB_HOST);

      if ($connected) {
        $DB_HOST = 'www.xyz.com';
        $DB_USER = 'user';
        $DB_PASS = 'pass';
        $DB_NAME = 'accounts';
      } else {
          $DB_HOST = 'localhost';
          $DB_USER = 'root';
          $DB_PASS = '';
          $DB_NAME = 'accounts';
      }

      // Create database if not exists
      $DB_CON_C = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
      $DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $DB_CON_C->query("CREATE DATABASE IF NOT EXISTS $DB_NAME");
      $DB_CON_C->query("USE $DB_NAME");

      try {
        $DB_CON_C = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
        $DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }

      catch(PDOException $e){
        echo $e->getMessage();
      }
    ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM