1
votes

I have a PHP file (that I cant make a snippet out of). I need to connect it to the database and rather then doing it the normal way was wondering if I could just include a header file of some sort that already has a DB connection.

Does anyone know of such a file in the Modx file structure?

3

3 Answers

2
votes

Easy...

if you open the main index.php, you can see some hint:

/* define this as true in another entry file, then include this file to simply access the API
 * without executing the MODX request handler */
if (!defined('MODX_API_MODE')) {
    define('MODX_API_MODE', false);
}

// ...

/* execute the request handler */
if (!MODX_API_MODE) {
    $modx->handleRequest();
}

That said, if you have a raw PHP file, let's say as an example: hello.php

<?php

define('MODX_API_MODE', true); // IMPORTANT!!!
require 'index.php'; // or give directory path, according to your need

// let's test it
$startPage = $modx->getObject('modResource', $modx->getOption('site_start', null, 1));

if (!$startPage) {
    die('CRAP!');
}

$startPageArray = $startPage->toArray();
echo '<pre>';
print_r($startPageArray);
echo '</pre>';
die('WOOHOO');

And no, you don't have to define $modx again.

It's using the same object in index.php.

0
votes

you can run any operations against your modx database if you load the modx module in your external script [in fact you can use any modx functions]

https://rtfm.modx.com/revolution/2.x/developing-in-modx/other-development-resources/loading-modx-externally

once you instantiate the modx object it will handle all your database connection details. This will work in any page, not just manager pages.

-1
votes

The only place which allows database connections using system database config are manager pages, yet that would require more work to write a plugin to access its classes and functions.

If you want to be able to use MODX functionality to establish connection, I suggest using it's xPDO to perform queries, for security reasons at least.

Such setup would be:

define('MODX_CORE_PATH', '/path/to/revo/core/'); define('MODX_CONFIG_KEY','config'); require_once MODX_CORE_PATH . 'model/modx/modx.class.php';

$host = 'localhost'; $username = 'your_username'; $password = 'your_password'; $dbname = 'your_database'; $port = 3306; $charset = 'utf-8';

$dsn = "mysql:host=$host;dbname=$dbname;port=$port;charset=$charset"; $xpdo = new xPDO($dsn, $username, $password);