How to acces wordpress functions in self-written php code? - php

I am working on a project where users can check and edit their own data and can also view their invoices.
I am writing the code for this project myself in PHP on my local machine but the invoices are made with the wp-invoice plugin on an existing and working wordpress site that's hosted somewhere else.
I want users to be able to log in to my web-app and then see their invoices that the web-app retreived from the wp-invoice api on the public wordpress site. The documentation for the wp-invoice api can be found here: https://www.usabilitydynamics.com/product/wp-invoice/docs/wp-invoice-api, it uses XML-RPC with which I am not familiar.
XML-RPC uses built-in wordpress functions to use the API. So I also downloaded and installed wordpress on my local machine and almost got it working (i believe). But when I load the wordpress functions into my web-app using "wp-load.php" it redirects me to the wordpress installer which says wordpress is already installed and there is a working wp-config.php file. This is correct because I installed wordpress successfully.
My code:
(This is my only code, there are no other files, functions or classes included using 'include_once')
define("ABSPATH", "C:/wamp64/www/mijnDashboard/WP");
define("WPINC", "/wp-includes");
include_once( ABSPATH . '/wp-load.php' );
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$client = new WP_HTTP_IXR_Client( 'http://MyWordpressSiteWithWP-INVOICEinstalled/xmlrpc.php' );
$client->query('wp.invoice', array(
$method = 'get_invoice',
$credentials = array('Username', 'Password'),
$args = array(
'ID' => 1032017043
)
));
$the_invoice = $client->getResponse();
echo "$the_invoice";
echo "hallo";
Result: (it redirected me from my self-written 'dashboard.php' to the wordpress page 'wp-admin/setup-config.php')
Tried solutions:
I searched the web for solutions and some people said it had something to do with my browser cache. I tried another browser and incognito mode in chrome but both got me the same result.
Beside that I tried to load the wordpress functions that I need to use XML-RPC using an other wordpress file called 'wp-blog-header.php' but it got me the same result.
I actually think this is easy to fix but I am new to XML-RPC and API's at all and I don't know how to properly include all wordpress functions in a non-wordpress, self-written file.
Thanks,
Elias

Okay, I figured it out. I didn't use my local machine anymore but I used a webserver instead. There are no errors and I am not being redirected when I load 'wp-load.php'.
It is strange that almost the same code runs fine on a public webserver but not on a local machine. But it's working now so it's fine.
The code: (I used this and uploaded it to the WordPress root directory which contains the other files like wp-config.php etc.)
<?php
define( 'WP_USE_THEMES', false );
require( 'wp-load.php' );
$rootD = $_SERVER['DOCUMENT_ROOT'];
define("ABSPATH", "$rootD/httpdocs");
define("WPINC", "/wp-includes");
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$client = new WP_HTTP_IXR_Client( 'http://mywordpresswebsite/xmlrpc.php' );
$client->query('wp.invoice', array(
$method = 'get_invoice',
$credentials = array('username', 'password'),
$args = array(
'ID' => 1032017039
)
));
$the_invoice = $client->getResponse();
foreach ($the_invoice as $key => $value) {
echo "$value";
}
?>
Thanks for all the help.

Related

wordpress becomes irresponsive when plugin is run

i've created a woocommerce plugin,
the plugin itself runs perfectly.
However as long as it takes for it to run, i'm experiencing wierd performances issues.
The website is totally inaccessible(both frontend and backend) ONLY from the browser that is logged in and ran the plugin.
Both frontend and backend are loading until the plugin finishes.
to make things even wierder it's working perfectly from another browser.
also this is run on a high-end dedicated server and when it's running the loads on the server are very low.
any clues?
require __DIR__ . '/vendor/autoload.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');
use Automattic\WooCommerce\Client;
$woocommerce = new Client(woocommerce_api_url, api_key, api_secret,['version' => 'wc/v3','timeout' => '99999',]);
echo '<pre>';
$db = new DBfdr();
$i=0;
$page = 1;
$products = [];
$all_products = [];
do{
try {
$products = $woocommerce->get('products',array('per_page' => 100, 'page' => $page));
} catch(HttpClientException $e) {
die("Can't get products: $e");
}
$all_products = array_merge($all_products,$products);
$page++;
Notes: the DBfdr class contains a simple function for managing pdo connections to the sql server.
That piece of code doesn't look so good, why would you need to make a plugin that externally loads wp then going through Woocommerce Client Api to get the list of products and then cycle all of them to make an if condition.
That would be so much more efficient if you would just pass inside WP standard plugin structure, using global $wpdb class and performing your queries with some join.
That said, the problem you are facing could be solved by adding this before your code:
ignore_user_abort( true );
/* Don't make the request block till we finish, if possible. */
if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
fastcgi_finish_request();
}
The problems occurs because the wp-config.php is included in the beggining.
wp-config.php in the end has
require_once(ABSPATH . 'wp-settings.php');
which inits some core wordpress functions which in turn "locks" the session.
i managed to fix the issue by removing
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');
and replacing it with customs defines

WordPress 3.9 Multisite db connection error

I have a ZendFW application and WPMU installed. Admins at Zend app has an interface where they can create a new MU site.
I included wp-load.php and then called wpmu_create_blog and so on...
Once I updated the WP to 3.9 I got error establishing database connection.
This test code works OK with 3.8 but gives db error when tried WP 3.9.
blog38 is WP 3.8
<?php
include "../blog38/wp-load.php";
global $wpdb;
echo "<pre>";
var_dump($wpdb->tables());
?>
blog39 is WP 3.9
<?php
include "../blog39/wp-load.php";
global $wpdb;
echo "<pre>";
var_dump($wpdb->tables());
?>
Does anyone know what the problem is? How to solve this connection error?
I posted it on WordPress discussion and submitted a ticket as well. The problem is in ms-setting.php file with new way they set $path and $current_site->path variables. In WP 3.8.3 they had
$current_site->path = $path = PATH_CURRENT_SITE;
and in WP 3.9 they set
$current_site->path = PATH_CURRENT_SITE;
and $path is determined by the $_SERVER['REQUEST_URI'] variable. So when you load wp-load.php file inside your application (and wordpress is in subdirectory) you have $path and $current_site->path variable different which ends up in no blog defined case, which gives Database connection error.
Current workaround is to override $_SERVER['REQUEST_URI'] = '/blog/'; before loading wp-load.php
More information can be found:
http://wordpress.org/support/topic/wordpress-39-multisite-db-connection-error
https://core.trac.wordpress.org/ticket/27999

Utilize IPSLib for IP.Board on External PHP

I have wrote a PHP script that grabs the latest forum posts by categories that I want, which works fine and everything, however my problem lies in the actual output of the code itself, previously I was utilizing XenForo and could use their API on external pages no problem, now that we have migrated to IP.Board I am trying to utilize the IPSLib Library in order to use the parsing system so that the posts I have pulled don't show up all messy and with bbcode everywhere.
The code that pulls the information from IP.Board's database works fine, again I'm simply trying to load & use the IPSLib from IP.Board.
My question is how, if possible, can you load the IPSLib in order to utilize the functions provided by the library?
require_once( 'forums/initdata.php' );
require_once( IPS_ROOT_PATH.'/sources/base/ipsRegistry.php' );
require_once( IPS_ROOT_PATH.'/sources/base/ipsController.php' );
$registry = ipsRegistry::instance();
$registry->init();
$classToLoad = IPSLib::loadLibrary( 'forums/admin/sources/classes/text/parser.php', 'classes_text_parser' );
$parser = new $classToLoad();
$parser->set( array( 'parseArea' => 'topics',
'parseBBCode' => true,
'parseHtml' => false,
'parseEmoticons' => true ) );
and finally where the text you want to parse from BBcode -> HTML use:
print $parser->BBCodeToHtml( $toParse );

How to use wordpress wpdb class to insert data

I am new to wordpress I am try to create table and insert data to that table. so within the wordpress database I created table called 'album' then I created directory called 'my-codes'(within root directory/ same level with 'wp-admin' , 'wp-content, 'wp-includes' directories)
within that directory I created insert.php then i added following code
<?php
global $wpdb;
$wpdb->insert($wpdb->album , array("ID"=>1, "Name"=>'something'), array("%d", "%s"));
?>
but it give this error Fatal error: Call to a member function insert() on a non-object in C:\wamp\www\wordpress\my-codes\insert.php what is the mistake I did, please help me.
You have to load the Wordpress files within your script, so that you have access to Wordpress' $wpdb object:
require_once( '../wp-load.php' );
This will load all of Wordpress, even the functionality you don't need. If you want to only load the database part, read this article.
Update - The first argument to the insert method should be the name of your table:
$wpdb->insert(
'album',
array("ID"=>1, "Name"=>'something'),
array("%d", "%s")
);
require (dirname(dirname(__FILE__)) . '/wp-blog-header.php');
require (ABSPATH . WPINC . '/compat.php');
require (ABSPATH . WPINC . '/functions.php');
require (ABSPATH . WPINC . '/classes.php');
require_wp_db();
global $wpdb; // Look look! Over here! line 270 in wp-settings.php
if ( !empty($wpdb->error) )
dead_db();
//Execute your query here
I would recommend using the WordPress Options API instead of creating a custom table, unless options won't fit your needs. Also, place all your code in your theme's functions.php. That way, you won't need to load any other WordPress files externally. They're already loaded for you automatically if your code is in functions.php.
Here's a quick example of how to store data in the database using options ( taken from the WP Codex article linked above ):
// Create an option to the database
add_option( $option, $value = , $deprecated = , $autoload = 'yes' );
// Removes option by name.
delete_option( $option );
// Fetch a saved option
get_option( $option, $default = false );
// Update the value of an option that was already added.
update_option( $option, $newvalue );
Options are much easier to implement and generally less error prone than direct database access. :)

Joomla 1.5.25 JSession set not writing to db on close after upgrade from 1.5.23

Joomla 1.5.25 just upgraded from 1.5.23 having problems saving to session and persistency, works perfectly on 1.5.23, but session data is not being saved to db when using JSession->set
Wrote custom app on top of joomla, managing users imported from legacy system cant use joomla Users for this ( or at least I haven't and I dont have the time ), login works like follows:
User posts email pass
app checks if user exists
if user exists I save the user object to session
redirect user to resource
Here is the snippet for saving the user to session
$session = JFactory::getSession();
$session->set('appUserData', array(
'data' => $USER_OBJECT,
'timestamp' => time(),
'role' => 0,
'permits' => $permits
);, "custom_namespace");
Now since I'm doing this outside the joomla scope I have to boostrap
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define('JPATH_BASE', dirname(dirname(__FILE__)));
require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');
Once I do $session->set() if I try $session->get() on the same script it does pull the full resource I just saved, but if I try to pull the $session from another script I get nothing, here is the Other script
<?php
error_reporting(E_ALL);
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define('JPATH_BASE', dirname(dirname(__FILE__)));
require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');
$mainframe = JFactory::getApplication('site');
$session = JFactory::getSession();
echo "<pre>";
print_r($_COOKIE);
print_r($session);
print_r($_SESSION);
echo "</pre>";
exit;
Here I only get my cookies array and the Array of the session with the default session info:
Array
(
[__default] => Array
(
[session.counter] => 3
[session.timer.start] => 1329168055
[session.timer.last] => 1329168057
[session.timer.now] => 1329168062
[session.client.browser] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:10.0.1) Gecko/20100101 Firefox/10.0.1 FirePHP/0.7.0
)
)
The db never gets updated with the contents of my newly created session variable, I tried doing some error_logs on the write db session adapter which is the one writing to db, and I think the problem is here ( libraries/joomla/session/storage/database.php ) line 82:
$session = &JTable::getInstance('session');
if ($session->load($id) == true) { /*...*/} // never entering here
else { /*...*/ } // always here
I tried outputting to the log the contents of $id and It does refer to a valid primary key id on the db
error_log('SELECT * FROM jos_session WHERE session_id = "' . $id . '"');
returns something like this SELECT * FROM jos_session WHERE session_id = "38e6468f35f1994425de3919fa767a3d", which I can confirm returns a valid record, I tried pulling the old source from 1.5.23 here but even that wont make it work again, any ideas out there on what might have upgraded and made this fail?
**UPDATE**
I tried truncating the tables too, in fact I think the problem more specifically is that at some point the session fails on write to db, since I have multiple connections to mysql being used, the JSession Database Mysql Storage engine for the session gets confused, even weirder is that on an environment with pure 1.5.23 this confusion doesn't occur, resources get created for each different connection, I went trough the changes from 1.5.23 to 1.5.25 and I can't find anything related to DB resource management or any loose reference to the DBO object, I think I need to profile each connection and check where is the problem, Data lives on same mysql server but on different db's
Problem is JSession is using the database storage JsessionStorageDatabase since I'm connecting to multiple databases through out the script execution my mysql_connect calls weren't really making a new connection, they were reusing the old causing the script to fail when it didn't find the selected db which changed by the time the Storage adapter for JSession wanted to do a write
See mysql_connect documentation here and check this question from another user which helped me understand my problem and come to a solution

Categories