run script in background(shell_exec) fails on composer/PHP-DI function - php

I run that script manually and everything works,
$container = require '../config/bootstrap.php';
try {
$test = $container->get(Test::class);
$test->run();
}
catch(\Exception $e) {
echo $e->getMessage() . "\n";
die;
}
but when I call that file from another folder like the following :
$script = __DIR__ .'/folder/test-service.php';
$output = shell_exec('php '.$script);
var_dump($output);
I get the following error:
Fatal error: require(): Failed opening required '../config/bootstrap.php' (include_path='.:') in /anotherFolder/folder/test-service.php on line 13
and also after that, I got a lot of error that files do not exist.
bootstrap.php include the class mapping of PHP-DI
require '../vendor/autoload.php';
use DI\ContainerBuilder;
$containerBuilder = new ContainerBuilder;
$containerBuilder->addDefinitions(__DIR__ . '/config.php');
$container = $containerBuilder->build();
return $container;

The require instruction is relative to your current directory.
You could replace the line with require __DIR__.'/../config/bootstrap.php';

Related

PHP autoload can't find the class in php project

Project file structure
I'm getting
127.0.0.1:52368 [500]: GET /controllers/login - Uncaught Error: Class "App\Core\Database" not found in /path/to/my/Php/project/src/controllers/index.php:9
Stack trace:
#0 {main}
thrown in /path/to/my/Php/project/src/controllers/index.php on line 9
and the class firing an error
<?php
namespace App\controllers;
use App\Core\Database;
//$conn = Database::getConnection();
try {
$conn = new Database(__DIR__ . './../config.php');
} catch (\Exception $e) {
}
$query = "SELECT id, username, image, aboutme
FROM users
LEFT JOIN persons on users.id = persons.user_id
LIMIT 24";
$tbh = $conn->prepare($query);
$tbh->execute();
$persons = $tbh->fetchAll();
require_once basename("/") . 'views/index.view.php';
also my autoload_classmap.php
return array(
'App\\Core\\Database' => $baseDir . '/src/Core/Database.php',
'App\\Core\\DotEnv' => $baseDir . '/src/Core/DotEnv.php',
'App\\Core\\Router' => $baseDir . '/src/Core/Router.php',
'App\\Entity\\Person' => $baseDir . '/src/Entity/Person.php',
'App\\Entity\\User' => $baseDir . '/src/Entity/User.php',
And I'm launching server from src directory :
php -S localhost:8000
Any help would be appreciated. Thank you.
Edit ...
I'm calling index.php from url : localhost:8000 and even with this code in index.php
<?php
namespace App;
//use App\core\Database;
use App\Core\Router;
require 'functions.php';
//$config = require_once ('config.php');
//$db = new Database($config);
//require 'Entity/User.php';
$uri = parse_url($_SERVER['REQUEST_URI'])['path'];
$router = new Router();
$router->getRoute($uri);
//require 'router.php';
I'm getting
127.0.0.1:53738 [500]: GET / - Uncaught Error: Class "App\Core\Router" not found in
You must create a class and add data inside it .
prepare($query);
$tbh->execute();
$persons = $tbh->fetchAll();
require_once basename("/") . 'views/index.view.php';
}

ZF2 Uncaught Error:Class 'ArrayUtils' not found in E:\Temp\htdocs\zf-tutorial\public\index.php:43

I am new at Zend2 and i am following the Album tuturial on Zend. I get the following error:
Fatal error: Uncaught Error: Class 'ArrayUtils' not found in E:\Temp\htdocs\zf-tutorial\public\index.php:43 Stack trace: #0 {main} thrown in E:\Temp\htdocs\zf-tutorial\public\index.php on line 43
I can't find whats the problem, what do i do wrong? Do i miss some code? Or do i miss some rules in the tutorial?
here is my index.php file
<?php
use Zend\Mvc\Application;
/**
* Display all errors when APPLICATION_ENV is development.
*/
if ($_SERVER['APPLICATION_ENV'] === 'development') {
error_reporting(E_ALL);
ini_set("display_errors", 1);
}
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
$path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (__FILE__ !== $path && is_file($path)) {
return false;
}
unset($path);
}
// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';
if (! class_exists(Application::class)) {
throw new RuntimeException(
"Unable to load application.\n"
. "- Type `composer install` if you are developing locally.\n"
. "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
. "- Type `docker-compose run zf composer install` if you are using Docker.\n"
);
}
// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/../config/development.config.php')) {
$appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}
// Run the application!
Application::init($appConfig)->run();
To be able to use the Zend\Stdlib\ArrayUtils class, you have to either:
add a use statement at the top of your file: use Zend\Stdlib\ArrayUtils; or
change your ArrayUtils invocation to Zend\Stdlib\ArrayUtils

PDO query in Slim causes PHP Fatal error: Uncaught RuntimeException: Unexpected data in output buffer

So my basic slim app goes along these lines:
<?php
session_start();
if (!file_exists( __DIR__ . '/settings.php')) { die("Error 500: application configuration problem."); }
require __DIR__ . '/../vendor/autoload.php';
$config = require __DIR__ . '/settings.php';
$app = new \Slim\App($config);
$container = $app->getContainer();
$container['s4s'] = function ($container) {
$db = $container['settings']['s4s'];
return new PDO('sqlsrv:Server='.$db['host'].';Database='.$db['database'], $db['username'], $db['password']);
};
$app->get('/ff', function ($request, $response) {
$sql = 'SELECT "dbo"."ZAKAZKA"."ZAKAZKA ID" FROM "dbo"."ZAKAZKA" WHERE ("ZAKAZKA ID" LIKE \'1216%\' ) ORDER BY "dbo"."ZAKAZKA"."ZAKAZKA ID" DESC';
$stmt = $this->s4s->prepare($sql);
if($stmt->execute()){
echo $stmt->debugDumpParams();
$results=$stmt->fetchAll();
}
});
this works fine and dandy. If I move the query code to a controller
<?php
namespace Glued\Playground;
use \PDO;
use Glued\Controllers\Controller;
class pdo_test extends Controller
{
public function test($request, $response)
{
$sql = 'SELECT "dbo"."ZAKAZKA"."ZAKAZKA ID" FROM "dbo"."ZAKAZKA" WHERE ("ZAKAZKA ID" LIKE \'1216%\' ) ORDER BY "dbo"."ZAKAZKA"."ZAKAZKA ID" DESC';
echo $sql;
$stmt = $this->container->s4s->prepare($sql); // this line breaks things
if($stmt->execute()){
echo $stmt->debugDumpParams();
$results=$stmt->fetchAll();
}
}
}
and add to the main code
$app->get('/playground/fff', '\Glued\Playground\Pdo_test::mytest');
it starts to break at the $stmt assignment with the error
PHP Fatal error: Uncaught RuntimeException: Unexpected data in output buffer. Maybe you have characters before an opening finalize(Object(Slim\Http\Response))\n#1 /opt/Web/html/glued/vendor/slim/slim/Slim/App.php(298): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))\n#2 /opt/Web/html/glued/public/index.php(4): Slim\App->run()\n#3 {main}\n thrown in /opt/Web/html/glued/vendor/slim/slim/Slim/App.php on line 552
since this doesnt apply to other controllers I wrote sofar, I'm either overlooking something obvious or PDO (which I dont usually use) causes the premature output. Not sure how to debug this as well.
Hints and solutions very welcome, thanks in advance!
note: I usually dont work with mssql as well, but I got the same problem against a mysql db.

Creating a new instance of another file

I have a php file called index which is the entry point for my api with the following code
//Entry point...
try {
echo (new requestHandler($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']))->DoStuff();
} catch (Exception $e) {
echo json_encode(Array('error' => $e->getMessage()));
}
Then the requestHandler.php handles the request
public function __construct($request)
{
echo "constructor";
//do some things
}
However when i call index.php it seems to give an error
PHP Fatal error: Class 'requestHandler' not found in .../index.php
Note: both are separate files...
In this particular case, I suggest you simply add this to the top of your index script...
require_once __DIR__ . '/requestHandler.php';
This is of course assuming the requestHandler class is defined in a file named requestHandler.php.
If you want to try using an autoloader, you need to stick to a convention of class to file names. In your case, it seems like this should suffice (again, in your index script)...
spl_autoload_register(function($class) {
$path = sprintf('%s/%s.php', __DIR__, $class);
if (is_readable($path)) {
require $path;
}
});

What's wrong with my autoloader?

I'm trying to register a few autoloaders and I get an HTTP 500. My error log says the following:
[05-Aug-2013 04:32:38 UTC] PHP Fatal error: Uncaught exception
'LogicException' with message 'Function 'Autoloader::config' not
callable (non-static method Autoloader::config() should not be called
statically)' in /home2/canforce/public_html/index.php:5
There was some stack trace part on the end of the error log, but it came showed up in huge letters so I took it out, I didn't think it was important.
I think my autoloader should work based on what I've read but for some reason it doesn't, here's the code:
index.php
include("config/autoloader.php");
spl_autoload_register('Autoloader::config');
spl_autoload_register('Autoloader::controller');
spl_autoload_register('Autoloader::service');
config/autoloader.php
class Autoloader {
function config($class) {
$file = 'config/' . $class . '.php';
if(file_exists($file)) {
require_once $file;
}
}
function controller($class) {
$file = 'presentation/controllers/' . $class . '.php';
if(file_exists($file)) {
require_once $file;
}
}
function service($class) {
$file = 'model/services/' . $class . '.php';
if(file_exists($file)) {
require_once $file;
}
}
}
You need to create an instance of the Autoloader class and then pass it to the register function.
include("config/autoloader.php");
$autoloader = new Autoloader();
spl_autoload_register(array($autoloader, 'loader'));

Categories