如何包含WordPress wp-config.php来访问MySQL DB信息

时间:2012-02-07 14:47:08

标签: php wordpress

我正在为WP安装域的用户开发一个项目。

我将数据存储在WP使用的同一个数据库中(仅在不同的表中)。

我无法使用include函数来获取文件,只是使用那里的信息,因为根据http://wordpress.stackexchange.com的用户,wp-config.php在发布问题后永远不应该包含在文件中关于我遇到的问题(只有有时)这样做(The Issues that encounter when including the file)。

现在,我已经有了一个选项(因为包含wp-config.php问题遇到有时):

我正在处理的应用程序需要安装(由用户运行)。因此,在安装过程中,我可以只包含wp-config.php文件 ONCE ,复制我需要的信息,并将其放入我自己的文件中,然后将其用于其余部分。应用

上述解决方案的问题是,如果我在安装过程中遇到问题该怎么办?用户必须一次又一次地尝试直到它工作。 =不开心的用户。

我可以用任何关于替代品的想法来实现这个目标吗?

6 个答案:

答案 0 :(得分:1)

This blog post似乎有你正在寻找的答案,完成代码来完成它。作者按照您在问题中链接的帖子的评论中的建议进行操作。

摘自帖子:

  

我需要一个脚本来从wp-config.php中提取数据库详细信息   文件,所以我可以在我的时候将登录详细信息保存在一个位置   编写WP框架之外的东西。

     

我想出了一个这样做的类,连接到mysql并选择   数据库。有三种连接选项:PDOmySQLi或   程序性mysql_connect()

更新:由于原始博文不可用,因此原始代码为:

<?php
/**
 * This class pulls the database logon information out of wp-config.
 * It then evals the settings it finds into PHP and then makes the
 * database connection.
 *
 * Acts as a Singleton.
 *
 * @package wpConfigConnection
 * @author Mark Flint
 * @link www.bluecubeinteractive.com
 * @copyright Please just leave this PHPDoc header in place.
 */
Class wpConfigConnection
  {
  /**
   * @var object $_singleton This is either null in the case that this class has not been
   * called yet, or an instance of the class object if the class has been called.
   *
   * @access public
   */
  private static $_singleton;
  /**
   * @var resource $_con The connection.
   * @access public
   */
  public $_con;

  /**
   * The wp-config.php file var
   * @var string $str The string that the file is brought into.
   * @access private
   */
  private $str;
  /**
   * @var $filePath Path to wp-config.php file
   * @access private
   */
  private $filePath;
  /**
   * @var array Array of constant names used by wp-config.php for the
   * logon details
   * @access private
   */
  private $paramA = array(
    'DB_NAME',
    'DB_USER',
    'DB_PASSWORD',
    'DB_HOST'
  );
  /**
   * @var bool $database Can check this var to see if your database was connected successfully
   */
  public $_database;

  /**
   * Constructor. This function pulls everything together and makes it happen.
   * This could be unraveled to make the whole thing more flexible later.
   *
   * @param string $filePath Path to wp-config.php file
   * @access private
   */
  private
  function __construct($type = 1, $filePath = './wp-config.php')
    {
    $this->filePath = $filePath;
    $this->getFile();
    $this->serverBasedCondition();
    /**
     * eval the WP contants into PHP
     */
    foreach($this->paramA as $p)
      {
      $this->evalParam('define(\'' . $p . '\'', '\');');
      }

    switch ($type)
      {
    default:
    case 1:
      $this->conMySQL_Connect();
      break;

    case 2:
      $this->conPDO();
      break;

    case 3:
      $this->conMySQLi();
      break;
      }
    }

  /**
   * Make the connection using mysql_connect
   */
  private
  function conMySQL_Connect()
    {
    try
      {
      if (($this->_con = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)) == false)
        {
        throw new Exception('Could not connect to mySQL. ' . mysql_error());
        }
      }

    catch(Exception $e)
      {
      exit('Error on line  ' . $e->getLine() . ' in ' . $e->getFile() . ': ' . $e->getMessage());
      }

    try
      {
      if (($this->_database = mysql_select_db(DB_NAME, $this->_con)) == false)
        {
        throw new Exception('Could not select database. ' . mysql_error());
        }
      }

    catch(Exception $e)
      {
      exit('Error on line  ' . $e->getLine() . ' in ' . $e->getFile() . ': ' . $e->getMessage());
      }
    }

  /**
   * Make the connection using mySQLi
   */
  private
  function conMySQLi()
    {
    $this->_con = @new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (mysqli_connect_errno())
      {
      exit('MySQLi connection failed: ' . mysqli_connect_error());
      }
    }

  /**
   * Make the connection using PDO
   */
  private
  function conPDO()
    {
    try
      {
      $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME;
      $this->_con = @new PDO($dsn, DB_USER, DB_PASSWORD);
      }

    catch(PDOException $e)
      {
      exit('Error on line  ' . $e->getLine() . ' in ' . $e->getFile() . ': ' . $e->getMessage());
      }
    }

  /**
   * Read the wp-config.php file into a string
   *
   * @access private
   */
  private
  function getFile()
    {
    try
      {
      $this->str = @file_get_contents($this->filePath);
      if ($this->str == false)
        {
        throw new Exception('Failed to read file (' . $this->filePath . ') into string.');
        }
      }

    catch(Exception $e)
      {
      exit('Error on line  ' . $e->getLine() . ' in ' . $e->getFile() . ': ' . $e->getMessage());
      }
    }

  /**
   * Get the logon parameter and evaluate it into PHP.
   * Eg, eval("define('DB_NAME', 'm4j3lub3_wordpress');");
   *
   * @param string $pre This defines what to look for at the start of a logon parameter
   * definition. Eg, if you are looking for  "define('DB_NAME', 'm4j3lub3_wordpress');"
   * then the $pre bit would be "define('DB_NAME'".
   *
   * @param string $post Like $pre, this defines what to look for at the end of the logon
   * parameter definition. In the case of WordPress it is always going to be "');"
   *
   * @access private
   */
  private
  function evalParam($pre, $post)
    {
    $str = $this->str;
    $str1 = substr($str, strpos($str, $pre));
    $str1 = substr($str1, 0, strpos($str1, $post) + strlen($post));
    eval($str1);
    }

  /**
   * Grab the right code block if there are more than one set of definitions
   *
   * Sets $this->str to be the right code block
   *
   * Used for when there are conditional settings based on local or remote configuration,
   * using the condition: if ($_SERVER['HTTP_HOST']=='localhost') { ...
   *
   * @access private
   */
  private
  function serverBasedCondition()
    {
    if (strpos($this->str, '$_SERVER["HTTP_HOST"]') || strpos($this->str, '$_SERVER[\'HTTP_HOST\']'))
      {
      if (strpos($this->str, '$_SERVER["HTTP_HOST"]'))
        {

        // case of double quotes - get a substring

        $this->str = substr($this->str, strpos($this->str, '$_SERVER["HTTP_HOST"]'));
        }
      elseif (strpos($this->str, '$_SERVER[\'HTTP_HOST\']'))
        {

        // case of single quotes - get a substring

        $this->str = substr($this->str, strpos($this->str, '$_SERVER[\'HTTP_HOST\']'));
        }

      // substring from 1st occurance of {

      $this->str = substr($this->str, strpos($this->str, '{') + 1);
      if ($_SERVER['HTTP_HOST'] == 'local.dev')
        {

        // local - substring from start to 1st occurance of } - this is now the block

        $this->str = substr($this->str, 0, strpos($this->str, '}') - 1);
        }
        else
        {

        // remote - substring from the else condition

        $this->str = substr($this->str, strpos($this->str, '{') + 1);
        $this->str = substr($this->str, 0, strpos($this->str, '}') - 1);
        }

      // replace all double quote with single to make it easier to find the param definitions

      $this->str = str_replace('"', '\'', $this->str);
      }
    }

  /**
   * Return an instance of the class based on type of connection passed
   *
   * $types are:
   * 1 = Procedural connection using mysql_connect()
   * 2 = OOP connection using PHP Data Objects (PDO)
   * 3 = OOP connection using mySQLi
   *
   * @return resource Database connection
   * @access private
   */
  private static
  function returnInstance($type)
    {
    if (is_null(self::$_singleton))
      {
      self::$_singleton = new wpConfigConnection($type);
      }

    return self::$_singleton;
    }

  /**
   * Action the return of the instance based on Procedural connection using mysql_connect()
   *
   * @access public
   * @return resource Procedural connection using mysql_connect()
   */
  public static

  function getInstance()
    {
    return self::returnInstance(1);
    }

  /**
   * Action the return of the instance based on OOP connection using PDO
   *
   * @access public
   * @return resource OOP connection using PHP Data Objects (PDO)
   */
  public static

  function getPDOInstance()
    {
    return self::returnInstance(2);
    }

  /**
   * Action the return of the instance based on OOP connection using mySQLi
   *
   * @access public
   * @return resource OOP connection using mySQLi
   */
  public static

  function getMySQLiInstance()
    {
    return self::returnInstance(3);
    }
  }

// USAGE EXAMPLES
// mysql_connect example

$mfdb = wpConfigConnection::getInstance();
try
  {
  $query = 'select * FROM wp_users';
  $res = mysql_query($query);
  if ($res == false)
    {
    throw new Exception('mySQL error: ' . mysql_error() . '. Query: ' . $query);
    }
  }

catch(Exception $e)
  {
  echo 'Error on line  ' . $e->getLine() . ' in ' . $e->getFile() . ': ' . $e->getMessage();
  exit;
  }

while ($row = mysql_fetch_assoc($res))
  {
  echo $row['user_login'] . '<br />';
  }

// PDO example, showing prepared statement with bound value

$mfdb = wpConfigConnection::getPDOInstance();
$mfdb->_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$mfdb->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM wp_users WHERE 1=:cond";
$stmt = $mfdb->_con->prepare($query);
$stmt->bindValue(':cond', 1);
$stmt->execute();

while ($row = $stmt->fetch())
  {
  echo $row['user_login'] . '<br />';
  }

$mfdb->_con = null;

// mySQLi example

$mfdb = wpConfigConnection::getMySQLiInstance();
$sql = ' SELECT * FROM wp_users';

if (!$mfdb->_con->real_query($sql))
  {
  echo 'Error in query: ' . $mfdb->_con->error;
  exit;
  }

if ($result = $mfdb->_con->store_result())
  {
  while ($row = $result->fetch_assoc())
    {
    echo $row['user_login'] . '<br />';
    }
  }

$result->close();
?>

来源:https://web.archive.org/web/20130410000149/www.markflint.net/parsing-wordpress-wp-config-php-file/

答案 1 :(得分:1)

对于必须与WordPress安装集成的项目,我总是包含'wp-blog-header.php'。

Integrating WordPress with Your Website

示例:

<?php 
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>

阅读完评论后,我建议编写(在安装过程中)脚本,查找WordPress的配置文件,并为DB_NAME,DB_USER,DB_PASSWORD,DB_HOST,DB_CHARSET,DB_COLLATE提取已定义的值并将其存储在你自己的配置文件。

答案 2 :(得分:1)

我建议在主题文件夹中创建一个名为page-custom-name.php的文件,然后发布一个标题为“Custom-name”的空白页面。现在,当您访问www.yoursite / custom-name时,您将看到该页面。

在page-custom-name.php中,您只需输入:

global $wpdb;

并且您可以访问数据库:)

答案 3 :(得分:0)

<?php

require_once('wp-load.php');

// your script here. which conforms to wordpress standards.

答案 4 :(得分:0)

如果您只想在没有其他Wordpress功能的情况下访问wp-config.php。

执行以下步骤:

1:在插件目录中创建一个空的wp-settings.php文件

2:将此广告到您的php文件

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad ");
    [super viewDidLoad];
    leftMenu.target=self.revealViewController;
    leftMenu.action=@selector(revealToggle:);
    self.title=@"Main";
    [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];


    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    NSURL *url=[NSURL URLWithString:@"http://www.test.com/ios/GetMainInfoByCat.php?cat_id=76"];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //self.collectionview.dataSource=self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data=[[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)Thedata
{
    [data appendData:Thedata];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading ");
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

    dnews=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    news=[dnews objectForKey:@"news_main_info_by_cat"];
    NSString *str=[news valueForKey:@"img_url"];

    //[self.collectionview reloadData];
    //NSLog(@"%@",str);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *erroMsg=[[UIAlertView alloc]initWithTitle:@"Error" message:@"Qoşula bilmədi. İnternet bağlantınızı yoxlayın" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
    [erroMsg show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    [collectionView.collectionViewLayout invalidateLayout];
    return 1;
}

-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSLog(@"%i",[news count]);
    [collectionView.collectionViewLayout invalidateLayout];
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell=(UICollectionView *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.newsTitle.text=[[news objectAtIndex:indexPath.row] objectForKey:@"post_title"];
    //cell.newsImage.image=[NSData dataWithContentsOfURL:[NSURL URLWithString:[[news objectAtIndex:indexPath.row] objectForKey:@"img_url"]]];
    //[[news objectAtIndex:indexPath.row] objectForKey:@"img_url"];
    return cell;
}

这适用于WordPress 4.2.4“向下和向上”,我在我们自己的插件mywebapplets中进行了测试。

答案 5 :(得分:0)

这是SonerGönül解决方案的变体,也基于独立脚本。小心将此文件放在没有人可以访问它的位置,除了您(例如:受Apache密码保护的文件夹或其他具有访问限制的域)。执行以下步骤:

1 - 创建一个名为wp-settings.php的空php脚本

2 - 假设您的WordPress文件夹的路径是/ var / www / html /,将下面的代码添加到另一个脚本(例如:db-info.php),放在与以前创建的空脚本相同的文件夹中

<?php
// you are defining ABSPATH here, so wp-config.php won't be able to define it again. The result is that wp-config.php, when required, will require your empty script (and not the real wp-settings.php), avoiding this way the start of WordPress loading.
define('ABSPATH', __DIR__ . '/');
// assuming that the path to your WordPress folder is /var/www/html/. Typing the path directly, instead of using $_SERVER['DOCUMENT_ROOT'], will allow you to run the script from anywhere (another domain of your server, for example).
require_once '/var/www/html/wp-config.php';

3 - 要查看代码是否正常工作:将以下行添加到脚本的末尾,

echo DB_NAME . '<br>';
echo DB_HOST . '<br>';

并使用您的浏览器进行测试,访问:http://'one-of-your-domains/path-to/db-info.php