- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为安装了 WP 域的用户开发一个项目。
我将数据存储在 WP 使用的同一个数据库中(只是在不同的表中)。
我不能使用 include 函数来获取文件并简单地使用那里的信息,因为根据来自 http://wordpress.stackexchange.com
的用户的说法。 , wp-config.php
在发布有关我遇到的问题的问题(仅 有时 )后,不应将其包含在文件中( The Issues that encounter when including the file )。
现在,我已经有了一个选择(因为包括 wp-config.php 问题只会遇到 有时 ):
我正在处理的应用程序需要安装才能运行(由用户)。因此,在安装过程中,我可以简单地包含 wp-config.php
文件 一次 ,复制我需要的信息,并将其放入我自己的文件中,然后将其用于应用程序的其余部分。
上述解决方案的问题是,如果我在安装过程中遇到问题怎么办?用户将不得不一次又一次地尝试,直到它起作用。 = 不满意的用户。
关于我可以用来完成这个的替代方案的任何想法?
最佳答案
This blog post似乎有您正在寻找的答案,并附有代码。作者按照您在问题中链接的帖子的评论中的建议进行操作。
帖子摘录:
I need a script to extract the database details from the wp-config.php file so I could keep the logon details in one location when I was coding something outside the WP framework.
I came up with a class that does this, connects to mysql and selects the database. There are three connection options:
PDO
,mySQLi
or the proceduralmysql_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();
?>
关于php - 如何包含 WordPress wp-config.php 以访问 MySQL 数据库信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9178287/
我正在尝试在我正在处理的博客上使用类别帖子 (WP-CPL) 插件来按类别过滤“最近的帖子”。基本上,当有人点击博客上的类别名称时,我希望它显示该类别的帖子。这将通过 Life Is Simple 模
我的形象 我只想为某些用户隐藏特定页面。 function remove_menus(){ // get current login user's role $roles = wp_g
我的形象 我只想为某些用户隐藏特定页面。 function remove_menus(){ // get current login user's role $roles = wp_g
我为我的 wp 网站创建了一个简单的脚本,我正在尝试从 2 个表的 wp 数据库中获取正确的数据,这是代码, 当我显示“user_ref_id”列的结果重复多次时,这是代码 global $wpdb;
我安装了一个名为 Hide My WP 的插件来更改网站结构,但考虑到我使用的是自定义主题,它破坏了一些功能。所以我手动从plugins文件夹中删除了插件,但是从那以后我就无法访问/wp-admin/
我试图从头开始创建 WXR 文件(WordPress eXtended Rss)。 我的代码基于 XML/ wordpress生成的WXR文件并像这样开始: 我是这样开始的: $newxml =
我想将所有页面重定向到 http://www.expample2.com除了 wp-admin 和 wp-json。 例如,用户能够登录 http://www.example1.com/wp-admi
我使用 MAMP 在本地构建了一个快速的 WordPress 网站,然后将其 checkin SVN 存储库。然后我将其检查到我的开发服务器上。 除了运行 search and replace too
在搜索端点的 WP REST API (wp json) 中: https://www.example.com/wp-json/wp/v2/search?search=searchPhrase&_em
我正在使用这个 NGINX 规则来强制 WordPress 网站的尾部斜杠: rewrite ^([^.]*[^/])$ $1/ permanent; 但是这个规则给 Gutenberg 和 wp-j
在搜索端点的 WP REST API (wp json) 中: https://www.example.com/wp-json/wp/v2/search?search=searchPhrase&_em
我正在使用这个 NGINX 规则来强制 WordPress 网站的尾部斜杠: rewrite ^([^.]*[^/])$ $1/ permanent; 但是这个规则给 Gutenberg 和 wp-j
我想限制所有用户访问 WordPress 网站登录。 例如:假设我有 WordPress 网站域 example1.com,我想限制所有用户使用 example1.com/wp- 访问管理员登录adm
尝试实现这里讨论的技术, http://z9.io/2013/10/21/shiny-new-dynamic-content-wp-super-cache/ 进入使用 Genesis 框架的站点。我想
我试图在位于我的 WP 主题文件夹内的 PHP 文件中调用自定义 AJAX 函数,但是我无法让它检索输出。我认为问题在于将 WP 查询链接到主 WP 文件? $.ajax({ url: "../../
我正在编写一个 perl 脚本,用于将 Wordpress 安装从一个地方迁移到另一个地方。在这项工作中,我需要使用 wp-cli 调用从 wp-config 文件中获取 wordpress 数据库名
我最近更改了我的 WordPress 网站上的目录。我导出了数据库,搜索并替换了旧 URL 为新 URL,然后重新导入。该网站的前端工作正常,但任何页面的后端都需要近 15 秒才能加载。 从funct
我使用下面的代码通过类似的单词标签获取帖子但不起作用 $query = " SELECT * FROM $wpdb->posts , $wpdb->terms
我已经通过 DirectAdmin 在我的服务器上安装了 SSL 证书。这似乎运作良好。 我已将 wp_*_options 表中的 url 更改为 https://mydomain.nl 等。突然我的
我正在建立一个网站,使用 wordpress+buddypress(最新版本)。 在这个网站中,我有自己的自定义登录|注册|重置密码表单,我不想将它们链接到后端 wp-forms。 我已经阻止了所有用
我是一名优秀的程序员,十分优秀!