classes/Logger.php / PHP Error - php

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;
}

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.

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

Related

ImageIntervention & Laravel 9: file_put_contents ERROR Failed to open stream: No such file or directory

I'm using Laravel 9 and Image Intervetion to resize uploaded images:
public static function resize($file, $fileName)
{
$path = self::route();
foreach (self::size() as $key => $value) {
$resizePath = self::route() . "{$value[0]}x{$value[1]}_" . $fileName;
Image::make($file->getRealPath())
->resize($value[0], $value[1], function ($constraint) {
$constraint->aspectRatio();
})
->save(storage_path($resizePath));
$urlResizeImage[] = ["upf_path" => $resizePath, "upf_dimension" => "{$value[0]}x{$value[1]}"];
}
self::$urlResizeImage = $urlResizeImage;
}
But the line ->save(storage_path($resizePath)); returns this error:
Can't write image data to path
So in the Image Facade of Intervention, there's a #file_put_contents:
public function save($path = null, $quality = null, $format = null)
{
$path = is_null($path) ? $this->basePath() : $path;
// dd($path);
if (is_null($path)) {
throw new NotWritableException(
"Can't write to undefined path."
);
}
if ($format === null) {
$format = pathinfo($path, PATHINFO_EXTENSION);
}
$data = $this->encode($format, $quality);
$saved = #file_put_contents($path, $data);
if ($saved === false) {
throw new NotWritableException(
"Can't write image data to path ({$path})"
);
}
// set new file info
$this->setFileInfoFromPath($path);
return $this;
}
And I tried removing # from #file_put_contents to see what's going wrong here, but then I got this:
file_put_contents(C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/107200x200_1671289517402.jpg): Failed to open stream: No such file or directory
So it basically says that it can not find the $path and when I uncomment dd($path), this is the output:
C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/108200x200_1671289517402.jpg
So what's going wrong here?
How can I properly save the resized images into this directory?
Please I beg you to help me with this because it's been a week that I'm struggling with this error and got headache!
UPDATE #1:
Here is the route():
public static function route()
{
return "upload/" . jdate()->format('Y') . "/" . jdate()->format('m') . "/" . self::$typeFile . "/" . strtolower(self::$catType)."s" . "/" . self::$objId;
}
And I changed it to this:
public static function route()
{
return "upload".DIRECTORY_SEPARATOR.jdate()->format('Y').DIRECTORY_SEPARATOR.jdate()->format('m').DIRECTORY_SEPARATOR.self::$typeFile.DIRECTORY_SEPARATOR.strtolower(self::$catType)."s".DIRECTORY_SEPARATOR.self::$objId;
}
But still the same error occurs :(

Yii get variable from other function in same Controller

Is that possible to get variable from other function in same Controller ?
So I just updated my code ... the huge code is my real code ... so I wish to get the $hashfilename_filename to another function so I able to save it into DB
Example:
class HappyController extends Controller{
public function actionUploadFile()
{
if (isset($_FILES['Filedata']['tmp_name']) && is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
$today = date("Ymd");
$slash = Yii::app()->params['slash'];
$tmp_folder = Yii::app()->params['tmp_folder'];
$tmp_folder_with_index_file = $tmp_folder . $slash . 'index.html';
$tmp_folder_with_date = Yii::app()->params['tmp_folder'] . $today;
if (!is_dir($tmp_folder_with_date)){
mkdir($tmp_folder_with_date, 0755);
copy($tmp_folder_with_index_file, $tmp_folder_with_date . $slash . 'index.html');
}
$filesize = sprintf("%u", filesize( $_FILES['Filedata']['tmp_name'] ));
$hashfilename_filename = md5(time() + 1) . '.apk';
$full_path = $tmp_folder_with_date . $slash . $hashfilename_filename;
if (!move_uploaded_file ($_FILES['Filedata']['tmp_name'], $full_path)){
$result['statusCode'] = "500";
echo json_encode($result);
die();
}
$result['statusCode'] = "200";
$result['today'] = $today;
$result['tmp_folder_with_date'] = $tmp_folder_with_date;
$result['filesize'] = $filesize;
$result['hashfilename_filename'] = $hashfilename_filename;
$result['full_path'] = $full_path;
}else{
$result['statusCode'] = "400";
}
echo json_encode($result);
die();
}
public function actionLife(){
$model = new ThisisLife();
$model->sad = $hashfilename_filename;
$model->save();
}
}
In public function actionLife , I wish to get the variable from other function, any suggestion to do that ?
try storing it in a session variable;
public function actionAbc(){
$full_path = a + b;
Yii::app()->user->setState('full_path', $full_path);
}
public function actionXyz(){
$full_path = Yii::app()->user->getState('full_path');
}
In this way you can access this variable from anywhere across whole platform.
What you are trying to do is not the right way in my opinion. The idea behind OOP i to encapsulate code belonging together. So if you need to determine a path which is needed in more than one place (or action) just extract it into its own private function within the controller. That way you could call this method from both actions and reuse your code.
If you need this variable between two calls I'd rather pass it as a GET/POST-Parameter as the otherway around you risk using the same filename again if you forget to reset the var...as it says, it lasts the whole session!
Your method could look like this:
private function generatePath()
{
$folder = Yii::app()->params['tmp_folder'] . date("Ymd");
$folderWithIndex = Yii::app()->params['tmp_folder'] . DIRECTORY_SEPARATOR . 'index.html';
if (!file_exists($folder)) {
mkdir($folder, 0755);
copy($folderWidthIndex, $folder . DIRECTORY_SEPARATOR . 'index.html');
}
$filename = md5(time() + 1) . '.apk';
return $folder . DIRECTORY_SEPARATOR . $filename;
}
The constant DIRECTORY_SEPARATOR is a php default constant to automatically fill in the "slash" of the current filesystem.
One more input: Instead of defining the path in your params, you could set it as a yii-alias. This makes life much easier in the long run. Make sure to check it out here: https://github.com/yiisoft/yii2/blob/master/docs/guide/concept-aliases.md
I hope it helped!
cheers, pascal
If you need to access variable through controllers, why don't u make it a private field in controller. So that you can access it in whole Controller class. You then may have getter, setters if needed, as it should as we are talking about OOP.

php - Class 'Browscap' not found in

I'm using Browscap downloaded from Github.
So I have a _class.php
require_once dirname(__FILE__) . "/core/CORE.php";
require_once dirname(__FILE__) . "/core/Browscap.php";
// use phpbrowscap\Browscap;
class _class extends CORE {
//put your code here
public function __construct($mysql_setup = null) {
parent::__construct($mysql_setup);
$bc = new Browscap(dirname(__FILE__) . "/../cache"); //this is the error line
$get_browser = $bc->getBrowser(null, true);
$get_browser["HTTP_REFERER"] = $_SERVER["HTTP_REFERER"];
$get_browser["REQUEST_TIME"] = date("Y-m-d H:i:s", $_SERVER["REQUEST_TIME"]);
$this->dbCreateTable();
$user = $_SERVER['REMOTE_ADDR'] . ";" . session_id();
if ($this->insertUser($user) !== false) {
$http_user_id = $this->dbLastInsertID();
foreach ($get_browser as $k => $v) {
if (($type_id = $this->getHttpUserTypeDB($k)) !== false) {
$this->dbInsert("http_user_agent_infos", array("info" => $v, "http_user_agent_id" => $http_user_id, "http_user_agent_type_id" => $type_id));
}
}
}
}
My directory hierarchy is like this
C:\xampp\htdocs\test
classes(folder)
core(folder)
Browscap.php
CORE.php
_class.php
form.php
cache(folder)
browscap.ini
cache.php
php_browscap.ini
The error is
Fatal error</b>: Class 'Browscap' not found in <b>C:\xampp\htdocs\job6b\classes\_class.php</b> on line <b>28</b><br />
I'm not sure where I have my error...or did I put the path wrongly?
Thanks

spl_autoload_reqister classes not getting loaded

I have a folder structure that looks like
base_dir-
Includes.php
Libs-
Database.php
Log.php
Cofing.php
Models-
someClass.php
Scheduled-
test.php
My Includes.php has
spl_autoload_register(NULL, FALSE);
spl_autoload_extensions('.php, .class.php, lib.php');
function libLoader($name) {
$file = 'Libs/' . $name . '.php';
if (!file_exists($file)) {
// throw new Exception("Error Loading Library: $file does not exists!", 1);
return FALSE;
}
require_once $file;
}
function modelLoader($name) {
$file = 'Models/' . $name . '.php';
if (!file_exists($file)) {
// throw new Exception("Error Loading Library: $file does not exists!", 1);
return FALSE;
}
require_once $file;
}
spl_autoload_register('libLoader');
spl_autoload_register('modelLoader');
My someClass.php has
require_once '../Includes.php';
class someClass extends Database
{
public function __construct() { return 'hello world'; }
}
And test.php has
require_once '../Includes.php';
try {
$loads = new someClass();
} catch (Exception $e) {
echo "Exception: " . $e->getMessage();
}
When I run test.php I get someClass not found on .../Scheduled/test.php
Does spl works with extended classes like someClass.php or do I need to include the class to be exended?
And why it wouldnt find someClass.php?
Thanks
Change
$file = 'Models/' . $name . '.php';
to
$file = __DIR__ . '/Models/' . $name . '.php';
in your models autoloader (and the equivalent in your libLoader) to ensure that it's searching from the correct directory, and not the directory where your test.php file is located

Spl_Auto_register not loading class properly

I'm trying to learn about spl_autoload_register().
My index.php is under document root, my MyClass.php is put under document root /MyProject/MyClass/MyClass.php
Here's my index.php
<?php
define('CLASSDIR', 'mylib');
define('BASEPATH', #realpath( dirname (__FILE__).'/../').'/'.CLASSDIR);
spl_autoload_register(null, false);
spl_autoload_extensions('.php');
// PSR-0 provided autoloader.
function autoLoader($className){
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= BASEPATH.'/'.str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
spl_autoload_register('autoLoader');
$obj = new MyClass();
$obj->test();
?>
Here's my Class: MyClass.php
<?php
namespace MyProject\MyClass;
class MyClass{
public function __contruct(){
echo('weird');
}
function test(){
echo 'issue';
}
}?>
Here's the error:
Fatal error: Call to undefined method MyClass::test() in /path/to/file/index.php on line 26
So, I'm assuming it found the class (since it didn't complain)? But the messages 'weird' and 'issue' are not displayed. Telling me that the constructor didn't fire.
Okay, assuming your class file is located in a seperate folder called classes (example)
Structure like this:
DOCUMENT_ROOT/
->index.php
->classes/
->Myclass/
->Myclass.php
Somewhere on your index.php You'd have something looking like this:
<?php
DEFINE('__BASE', realpath(dirname(__FILE__)));
require_once('load.php');
?>
Now your load.php file should have the __autoload() function in there, looking something like this:
// Auto load function to load all the classes as required
function __autoload($class_name) {
$filename = ucfirst($class_name) . '.php';
$file = __BASE . DIRECTORY_SEPARATOR .'classes/' . ucfirst($class_name) . $filename;
// First file (model) doesnt exist
if (!file_exists($file)) {
return false;
} else {
// include class
require $file;
}
}
EDIT:
If you'd like to do it with spl_autoload_register(), you'd have something similar to this in your load.php
// Auto load function to load all the classes as required
function load_classes($class_name) {
$filename = ucfirst($class_name) . '.php';
$file = __BASE . DIRECTORY_SEPARATOR .'classes/' . ucfirst($class_name) . $filename;
// First file (model) doesnt exist
if (!file_exists($file)) {
return false;
} else {
// include class
require $file;
}
}
spl_autoload_register('load_classes');

Categories