Home » Php » Include statement not working in PHP/Yii2

Include statement not working in PHP/Yii2

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have two files, the first one being in the main directory, console_output.php:

<?php
class console_output
{
  function write_to_logfile($text) {
    file_put_contents("log.txt", $text);
  }
}
?>

and the second one in a subdirectory, xController.php

<?php 
...import stuff...
include ("../console_output.php");

class xController extends Controller{
  ...do_stuff..

  function doMoreStuff(){
  ...

    $console_output = new console_output();
    $console_output->write_to_logfile("did Stuff");
  }
}
?>

This is all in Yii2 framework, in case that matters. I have tried with apps/console_output.php and ../console_output.php, but it fails either way.
When I use apps/console_output.php, the error is

include(app/console_output.php) [https://secure.php.net/manual/en/function.include.php’>function.include.php]: failed to open stream: No such file or directory

The error is shown right at the include statement.

Using ../console_output.php in the include statement gives me an error at

$console_output->write_to_logfile("did Stuff");

with the message

Class ‘app\controllers\console_output’ not found

I have no idea what I’m doing wrong here. Can you help me out please?

How to&Answers:

You relative path Def nation is wrong. You are using .. that mean you moving a director up from current script. You need to use “subdirectory/script.php”