I am trying to obtain the username variable from an external PHP script that is not part of Drupal or a Drupal Module.
For Drupal 7 there was drupal_bootstrap to load the required Drupal dependencies. However, after a long search all I found for Drupal 8 was a note that drupal_bootstrap is deprecated for Drupal 8.
And indeed, I get a
Call to undefined function drupal_bootstrap()
when I try to call it after including as in
<?php
define('DRUPAL_ROOT', '/var/www/html/drupal7'); // Define the DRUPAL_ROOT constant which is used in many places.
$base_url = 'http://'.$_SERVER['HTTP_HOST'].'/drupal7'; // Again, this is used in many places.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; // Include the boostrap file.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); // Start things up to whatever level you need.
global $user;
echo $user->name;
So how can I use the Drupal 8 API from an outside script?!
Posted this on another forum and I got this code, but it just doesn't work, so I would like to know what's going wrong. I know that something's missing, but I don't know how to echo the name of the current user who's logged on:
<?php
define('DRUPAL_DIR', __DIR__ .'/../../drupal');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
?>
Thanks in advance
Related
Ok so I have been learning vanilla php and wanted to delve into making use of packages. so I tried implementing fabpot\Goutte to the teeth.
I did install the package using Composer and placed the src code in the root folder where the Composer-generated files sit. As I run the script, I get an initializing class not found error.
How do I get around with this? I have followed the instructions and it's making me crazyyyyyyyyyyyy
Code I got:
<?php
use Goutte\Client;
// Initialize object
$client = new Client();
// Issue GET request to URI
$crawler = $client->request("GET", "http://www.symfony.com/blog");
$client->getClient()->setDefaultOption("config/curl".CURLOPT_TIMEOUT, 60);
// Navigate the client through the use of links
$link = $crawler->selectLink("Security Advisories")->link();
$crawler = $client->click($link);
// Extract data
$crawler->filter("h2 > a")->each(function($node) {
print $node->text()."\n";
});
?>
The error I am getting:
Fatal error: Class 'Goutte\Client' not found in **line 6**
On top of your script.. You need to include composer's autoloader like this:
require __DIR__ . "/vendor/autoload.php";
I am integrating google spreadsheet in my project. I have to save form data into google spreadsheet.
For this i am using asimqt php-google-spreadsheet-client library.
I have single form on site that form is submitting using ajax. For this i have written function in function.php.
Getting error when initializing object of DefaultServiceRequest class.
Error: Fatal error: Class 'Google\Spreadsheet\DefaultServiceRequest' not found
require '/vendor/autoload.php';
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
function spreadsheet_feeds()
{
$access_tok = 'xyz-token';
$serviceRequest = new DefaultServiceRequest($access_tok); // Getting error
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
}
add_action( 'wp_ajax_nopriv_spreadsheet_data', 'spreadsheet_feeds' );
add_action('wp_ajax_spreadsheet_data','spreadsheet_feeds');
Any help why this error is occurring because class is already include using "use" statement ?
This seems to be an issue with the location of your vendor folder.
Make sure that the vendor folder is accessible by the file
Considering your folder hierarchy to be
-wp-content
--themes
---your-theme
----functions.php
If you have your vendor folder in your-theme/vendor then in your functions.php
you should write
require 'vendor/autoload.php';
and if vendor is in the root directory of WP make sure you traverse back to the root folder using something like :
require __DIR__ .'/../../../../vendor/autoload.php';
Just replace require '/vendor/autoload.php'; to require_once('vendor/autoload.php');
Just now I tried this here for you myself and it works.
I'd like to use Cakephp classes (models) from regular php code unrelated to cakephp.
I tried this but it didn't work:
include('/lib/Cake/Core/App.php');
App::uses('Business', 'Model');
$b = new Business();
The last line gives me an error, and I've also tried several workarounds with no success...
I'll be ever grateful for a good answer :)
EDIT: Here's the solution I found! (Thanks, #Burzum!):
I copied webroot/index.php to webroot/cake_setup.php and removed the last few lines so it will only include stuff and not actually execute anything:
App::uses('Dispatcher', 'Routing');
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(
new CakeRequest(),
new CakeResponse()
);
Then, this worked from external php code:
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
include_once(__DIR__ . DS . '..' . DS . 'v2' . DS . 'app' . DS . 'webroot' . DS . 'cake_setup.php');
App::uses('AppModel', 'Model');
App::uses('Business', 'Model');
$b = new Business();
Thanks a lot guys!
CakePHP is not made to be used piece by piece. If you're looking for a standalone ORM go for doctrine or propel.
You can keep trying it but you'll have to run the bootstrapping process of the framework (see what it does inside webroot/index.php) and register it's class loader and point it the the core include path.
Edit:
While looking at this again today, I think the proper solution here would be to expose the stuff your need from your CakePHP app through an API that the other non-Cake app can consume. REST is pretty easy with CakePHP you might want to look at that solution. You don't tight couple your other app on the CakePHP app then. You can even upgrade to 3.0 without having to touch the other non-Cake app then.
I am seeking a way of allowing my PHP applications to be perfectly portable. My problem is, although I am utilizing relative path to include PHP classes, I always face issues when I try to deploy me application in a new environment.
For example, I have implemented an application under Ubuntu and it just run perfectly. However, when I moved it to a shared hosting running Centos, I had to modify all the include statements.
So, I am asking about the best way to include classes, considering having multiple folders which contain various classes that are dependent on another multiple classes in different levels of the folder hierarchy.
just keep one "main" folder.
In your index.php (for ex.) configure the "main" folder location and either use that as the 'base' for includes (I suppose you hard-code the include/require path?)
Else use the 'base' within the autoload functionality.
Now you are able to move the 'main' folder around and all you need to do is update just one line of code in your index.php
It is still a manual update. True that. You can also ofc. use something like glob() and search for you "mainlib.php" file (for ex.) and 'cache' that folders location to use it in the next calls?
This for example is how I do it:
<?php
/**
* cfg.php
*
* Main config file
*
* #package Public
*/
// Compatibility
$version = '5.2.3';//restricted by htmlentities()' 4th parameter
if(version_compare(PHP_VERSION, $version, '<')) {
die('Required PHP version is ' . $version . ', current is ' . PHP_VERSION);
}
// Environment
define('DEVELOPMENT', in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')));
define('PRIVATE_DIR', DEVELOPMENT ? 'private' . DIRECTORY_SEPARATOR : '..'.DIRECTORY_SEPARATOR.'private_html'.DIRECTORY_SEPARATOR.'tickets');
define('APPLICATION_LINK','application_red'.DIRECTORY_SEPARATOR);
define('LIBRARY_LINK','library'.DIRECTORY_SEPARATOR);
define("MEM_START",memory_get_usage(true));
// Behavior
if(DEVELOPMENT) {
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);//report all errors
}
else {
ini_set('display_errors', 'Off');
error_reporting(0);
}
// Timezone
date_default_timezone_set('Europe/Amsterdam');
// Constants
define('ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
define('APP', ROOT . '..'.DIRECTORY_SEPARATOR.PRIVATE_DIR.''.APPLICATION_LINK);
define('LIB', ROOT . '..'.DIRECTORY_SEPARATOR.PRIVATE_DIR.''.LIBRARY_LINK);
define('CACHE', APP.'cache'.DIRECTORY_SEPARATOR);
index.php/utest.php:
<?php
include("cfg.php");
// Start library
require_once LIB.'Library.php';
$library = new Library();
//etc.......
You don't need to make reference to a hardwired folder at all. In my current project I do this:
public static function getProjectRoot()
{
return realpath(
dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '..' .
DIRECTORY_SEPARATOR . '..'
);
}
The class in which this features is two folder levels inside the project - hence the two .. operators to traverse up the directory structure. Since that location will never change in relation to the project root, this doesn't need changing, and I don't ever need to hardwire any paths.
Edit: in relation to include/require statements, use an autoloader, and (apart from a couple of bootstrap files) you don't generally need to use includes/requires at all.
I am trying to accomplish something which I think is getting beyond my current PHP skills!
I have working code in a Magento .phtml template file that calls an external PHP class e.g.
$ExternalLibPath=Mage::getModuleDir('', 'My_Module') . DS . 'lib' . DS .'class.authentication.php';
require_once ($ExternalLibPath);
$myauth = new Authentication();
$credentials = $myauth->get("account_credentials");
echo "Connecting as " . $credentials->user_name ;
(In the .phtml file the classes are called from an include). I'm trying to move the code from the frontend template files to a Magento module/extension with a class triggered on an event. My module works fine up until the external classes are accessed where trying to access *$credentials->user_name* causes an Undefined property: stdClass: error.
I don't understand why the code works in a .phtml template and not in the module, or what I am doing wrong!
Any help would be appreciated.
Pete.
You should call the class directly from the phtml:
$credentials = Mage::getModel('namespace/custom_class')->getAccountCredentials();
and return whatever you need to.