JDoe
JDoe

Reputation: 61

classes/Logger.php / PHP Error

CodeIgniter: A PHP Error was encountered

Severity: Warning

Message: fopen(scanner/logs/eventlogs_2018-05-06.txt): failed to open stream: No such file or directory

Filename: classes/Logger.php

Logger.php

<?php

class Logger{

    private $logFile;
    private $fp;

    public function lfile($path) {
        $this->logFile = $path;
    }

    public function lwrite($message){

        if(!$this->fp) 
            $this->lopen();
        $scriptName = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
        $time = date('H:i:s:ms');
        fwrite($this->fp, "$time ,$scriptName, $message\n");
    }

    private function lopen(){

        $lfile = $this->logFile;
        $today = date('Y-m-d');
        $this->fp = fopen($lfile . '_' . $today . '.txt', 'a') or exit("Can't open $lfile!");
    }
}
?>

Bear in mind that my directory is not /scanner/logs/eventlogs/ but its /application/user/views/scanner/ so I have no idea why logger is trying to fopen there... Can anyone help?

I am using this as a form to web scan! a snippet

$log = new Logger();
			$log->lfile('scanner/logs/eventlogs'); // THIS IS WHERE ERROR POPS UP

			$log->lwrite('Connecting to database');

			$connectionFlag = connectToDb($db);

			if(!$connectionFlag)
			{
				$log->lwrite('Error connecting to database');
				echo 'Error connecting to database';
				return;
			}

Upvotes: 1

Views: 491

Answers (2)

Carl Johnson
Carl Johnson

Reputation: 87

Use the __DIR__ constant, which returns the current directory of the script.

public function lfile($path) {
    $this->logFile = __DIR__ . "/" . $path; // sprintf("%s/%s", __DIR__, $path);
}

Learn more: http://php.net/manual/en/language.constants.predefined.php

Upvotes: 0

Alex
Alex

Reputation: 9265

You should change this function (which seems to set the path for the other functions):

public function lfile($path) {
    $this->logFile = $path;
}

To something like:

public function lfile($path) {
    $this->logFile = FCPATH . $path;
}

This way all your paths will be from C:\xampp\htdocs\ (FCPATH example) and not depend on the current working directory where you are calling your function from.

Upvotes: 1

Related Questions