Recursive copy directories - php

I have a function for recursive copy directories. But I'm getting error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(/temp/install_5630013a79723/site, /temp/install_5630013a79723/site): The system cannot find the file specified. (code: 2)'
public static function copyDir($source, $dest) {
#mkdir($dest, 0755);
foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) {
if ($item->isDir()) {
#mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
} else {
#copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
}
How can I fix/improve my function?

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 :(

Fatal error: Uncaught LogicException: Function autooad not found

I would know if there something speficic in php 7.3.3-1+0~20190307202245.32+stretch~1.gbp32ebb2
because I have this error when I try to install a software.
:autoload' not found (class 'Core\\OM\\CORE' not found)
Got error 'PHP message: PHP Fatal error: Uncaught LogicException: Function 'Core\\OM\\CORE::autoload' not found (class 'Core\\OM\\CORE' not found) in /var/www/.........../application.php:21\nStack trace:\n#0 /var/www/........./application.php(21): spl_autoload_register('Core\\\\OM...')\n#1 /var/www/clients/........./install/index.php(12): require('/var/www/client...')\n#2 {main}\n thrown in /var/www/........../install/includes/application.php on line 21'
On my localhost under linux, I have not this problem and everything works fine.
php : PHP Version 7.3.2-3
Thank you
For example in install.php directory :
use Core\OM\CORE;
use Core\OM\HTML;
// set the level of error reporting
error_reporting(E_ALL & ~E_DEPRECATED);
define('CORE_BASE_DIR', realpath(__DIR__ . '/../../includes/') . '/Core/');
require(CORE_BASE_DIR . 'OM/CORE.php');
spl_autoload_register('Core\OM\CORE::autoload')
about CORE.PHP
public static function autoload($class) {
$prefix = 'Core\\';
if (strncmp($prefix, $class, strlen($prefix)) !== 0) {
return false;
}
if (strncmp($prefix . 'OM\Module\\', $class, strlen($prefix . 'OM\Module\\')) === 0) { // TODO remove and fix namespace
$file = dirname(CORE_BASE_DIR) . '/' . str_replace(['Core\OM\\', '\\'], ['', '/'], $class) . '.php';
$custom = dirname(CORE_BASE_DIR) . '/' . str_replace(['Core\OM\\', '\\'], ['Core\Custom\OM\\', '/'], $class) . '.php';
} else {
$file = dirname(CORE_BASE_DIR) . '/' . str_replace('\\', '/', $class) . '.php';
$custom = str_replace('Core/OM/', 'Core/Custom/OM/', $file);
}
if (is_file($custom)) {
require($custom);
} elseif (is_file($file)) {
require($file);
}
}

How do i exit when error from new CallbackFilterIterator

I'm trying to get the files in a directory in my filesystem. Did some research here and found the necessary info to create the following piece of code that works perfectly!
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define(FILM_IMG_UPLOAD_DIR, DOCUMENT_ROOT . '/filmography/img/films/');
$files = new filesystemiterator(FILM_IMG_UPLOAD_DIR, FilesystemIterator::SKIP_DOTS);
$filter_files = new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
$num_files = iterator_count($filter_files);
...
The problem is when the directory does NOT exist, i get the error
Fatal error: Uncaught exception 'UnexpectedValueException' with
message
'FilesystemIterator::__construct(C:/public_html/filmography/img/films/,C:/public_html/filmography/img/films/)...
So, how do I exit the code when i get an error from new CallbackFilterIterator ?
Looks to me like you need to wrap the code in a try-catch block.
define('DOCUMENT_ROOT', '/usr/local/share');
define('FILM_IMG_UPLOAD_DIR', DOCUMENT_ROOT . '/film/');
try {
$files = new filesystemiterator(FILM_IMG_UPLOAD_DIR, FilesystemIterator::SKIP_DOTS);
$filter_files = new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
$num_files = iterator_count($filter_files);
}
catch(UnexpectedValueException $e) {
echo "App Exception: " . $e->getMessage() . "\n";
}

PHP unlink() Error: "Directory not empty"

I have the following recursive method to delete a directory and all its sub-directories and files:
protected function _rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != '.' && $object != '..') {
if (filetype($dir . '/' . $object) == 'dir') {
_rrmdir($dir . '/' . $object);
} else {
unlink($dir . '/' . $object);
}
}
}
reset($objects);
rmdir($dir);
}
}
On occasion, the get a Warning, "Directory not empty".
The directory is actually created as a temporary holder for files. The files are downloaded from the Internet using the following snippet:
file_put_contents($filename, file_get_contents($file))
After they are downloaded (a write operation), they are then uploaded to a website (a read operation). Once done uploading, the temporary folder and its files are then deleted.
The odd thing is that when I look inside the temporary folder, there are no files there. It's as if the code tried to delete the folder while the last file was in the process of being deleted?
Any ideas what might be wrong and how to resolve it? I need this code to run on Windows and *nix, so a *nix only solution is not an option.
The constant DIRECTORY_SEPARATOR might help you with Windows/Unix compatibility.
For the folder not empty, try this:
protected function _rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != '.' && $object != '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
_rrmdir($dir . DIRECTORY_SEPARATOR . $object);
} else {
if( is_file($dir . DIRECTORY_SEPARATOR . $object) ) {
if(!unlink($dir . DIRECTORY_SEPARATOR . $object)) {
// code in case the file was not removed
}
// wait a bit here?
} else {
// code for debug file permission issues
}
}
}
}
reset($objects);
rmdir($dir);
}
}
It might happen that you try to remove a file which permissions are not at php exec level.
The is_file() method will return FALSE only if no read permissions, mind that write permissions are needed by the execution owner to delete files.

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

Categories