【问题标题】:Run PHP script in same directory as wordpress, but without it在与 wordpress 相同的目录中运行 PHP 脚本,但没有它
【发布时间】:2016-07-18 16:00:02
【问题描述】:

假设我有一个名为 import.php 的 PHP 脚本(代码在底部),它存储在与我的 wordpress 网站相同的目录(根目录)中。我的问题是当我想通过键入来运行该脚本时:www.mydomain.com/import.php 当然它会启动带有 404 错误的 wordpress。

如何在 wordpress 环境之外以某种方式运行此脚本/将其从 wordpress 中排除?

我的脚本专用于数据库更新(通过真正的 cron),这就是我不想为此使用 wordpress 的原因。

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');


$mysql_host = 'localhost';
$mysql_username = '';
$mysql_password = '';
$mysql_database = '';

$db = new PDO('mysql:dbname='.$mysql_database.';host='.$mysql_host,$mysql_username,$mysql_password);

// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

function truncate_db()
{
    global $db;

    $sql_query_1 = "
    TRUNCATE TABLE `WIZYTY`; 
    TRUNCATE TABLE `ANIMALS`;
    TRUNCATE TABLE `DOCTORS`;
    TRUNCATE TABLE `CUSTOMER`
    "; 

    try {
        $stmt = $db->prepare($sql_query_1);
        $stmt->execute();
        echo "Truncate action - OK";
    }
    catch (PDOException $e)
    {
        echo $e->getMessage();
        die();
    }
}

function import_db()
{
    global $db;

    try
       {
         $sql_query_2 = implode(array_map(function ($v) {
            return file_get_contents($v);
            }, glob(__DIR__ . "/*.sql")));

         $qr = $db->exec($sql_query_2); 
         echo "Import action - OK";
       }
       catch (PDOException $e) 
       {
         echo 'Connection failed: ' . $e->getMessage();
    }
}

truncate_db();
echo '<br />';
import_db();

$db = null;
?>

【问题讨论】:

  • 你需要在wordpress生成的重写规则集中添加一个异常。这些由 wordpress 存储在 .htaccess 样式文件中。该脚本的异常将阻止 wordpress“接管”该请求的处理。
  • 为什么?实际上,如果您的根文件夹(通常放置 wp-config.php)应该可以工作,因为 Web 服务器将在 WordPress 之前处理它。同yourdomain.com/license.txt

标签: php database cron


【解决方案1】:

你应该添加这样的东西 .htaccess

<FilesMatch "^import\.php$">
Allow from all
</FilesMatch>

无论如何,您不应该将它放在根文件夹中,请检查 wordpress 以获得更好的解决方案

Wordpress 事件调度程序 https://codex.wordpress.org/Function_Reference/wp_schedule_event

这里有一个很好的例子 https://tommcfarlin.com/wordpress-cron-jobs/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2013-05-08
    • 2016-08-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    相关资源
    最近更新 更多