I need the last 7 days' storage logs to move a new folder. But, I can't move them and got this error.
rename(/var/www/html/eMarketing/storage/logs/old-log-2020-02-27,/var/www/html/eMarketing/storage/logs/laravel-2020-02-27.log): Not a directory
My Code is here
public function logs()
{
$today = \Carbon\Carbon::today()->format('Y-m-d');
$days = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');
$newDirectoryPath = storage_path('logs/old-log-'.$days);
if (!\File::isDirectory($newDirectoryPath)) {
\File::makeDirectory($newDirectoryPath);
}
$path = storage_path('logs/');
$allFiles = \File::allFiles($path);
foreach($allFiles as $files) {
$file = pathinfo($files);
$logDay = str_replace('laravel-','', $file['filename']);
if ($logDay >= $days && $logDay < $today) {
\File::move($newDirectoryPath, $path.$file['basename']);
}
}
}
Problem
The problem is, you don't have files to move.
$newDirectoryPath = storage_path('logs/old-log-' . $days);
if (!\File::isDirectory($newDirectoryPath)) {
\File::makeDirectory($newDirectoryPath);
}
The move() method may be used to rename or move an existing file to a new location. But
$newDirectoryPath is a folder not a file.
Solution
You need to change :
\File::move(
$path . $file['basename'], // old file
$newDirectoryPath . '/' . $file['basename'] // new file
);
public function logs()
{
$today = \Carbon\Carbon::today()->format('Y-m-d');
$days = \Carbon\Carbon::today()->subDays(7)->format('Y-m-d');
$newDirectoryPath = storage_path('logs/old-log-' . $days);
if (!\File::isDirectory($newDirectoryPath)) {
\File::makeDirectory($newDirectoryPath);
}
$path = storage_path('logs/');
$allFiles = \File::allFiles($path);
foreach ($allFiles as $files) {
$file = pathinfo($files);
$logDay = str_replace('laravel-', '', $file['filename']);
if ($logDay >= $days && $logDay < $today) {
\File::move($path . $file['basename'], $newDirectoryPath . '/' . $file['basename']);
}
}
}
Related
Is it possible to customize the chunk configuration in Filepond such that the chunk information is provided to the upload server:
as query parameters instead of headers
with custom query parameter names instead of Upload-Length, Upload-Name, and Upload-Offset
I am trying to fit Filepond's chunk implementation to a third party upload endpoint that I don't have control over.
I have found the Advanced configuration where you provide a process function which I've played with a little bit to see what comes through the options param -- however that appears (I think) to make the chunking calculations my responsibility. My original thought was to manipulate the options.chunkServer.url to include the query params I need but I don't believe this processes individual chunks.
In case it makes a difference, this is being done in React using the react-filepond package.
I made and implementation in Laravel 6 using Traits and some "bad practices" (I didn't have time because ... release in prod) to join chunks into a file
Basically:
post to get unique id folder to storage
get chunks and join together
profit!
Here's the full code:
<?php
namespace App\Http\Traits\Upload;
use Closure;
use Faker\Factory as Faker;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait Uploadeable
{
public function uploadFileInStorage(Request $request, Closure $closure)
{
// get the nex offset for next chunk send
if (($request->isMethod('options') || $request->isMethod('head')) && $request->has('patch')) {
//get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// reead all chunks in directory
$patch = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// read offsets for calculate
$offsets = array();
$size = 0;
$last_offset = 0;
foreach ($patch as $filename) {
$size = Storage::size($filename);
list($dir, $offset) = explode('file.patch.', $filename, 2);
array_push($offsets, $offset);
if ($offset > 0 && !in_array($offset - $size, $offsets)) {
$last_offset = $offset - $size;
break;
}
// last offset is at least next offset
$last_offset = $offset + $size;
}
// return offset
return response($last_offset, 200)
->header('Upload-Offset', $last_offset);
}
// chunks
if ($request->isMethod('patch') && $request->has('patch')) {
// get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// read headers
$offset = $request->header('upload-offset');
$length = $request->header('upload-length');
// should be numeric values, else exit
if (!is_numeric($offset) || !is_numeric($length)) {
return response('', 400);
}
// get the file name
$name = $request->header('Upload-Name');
// sleep server for get a diference between file created to sort
usleep(500000);
// storage the chunk with name + offset
Storage::put($dir . 'file.patch.' . $offset, $request->getContent());
// calculate total size of patches
$size = 0;
$patch = Storage::files($dir);
foreach ($patch as $filename) {
$size += Storage::size($filename);
}
// make the final file
if ($size == $length) {
// read all chunks in directory
$files = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// create output file
//Log::info(storage_path('app'));
$new_file_name = $final_name = trim(storage_path('app') . DIRECTORY_SEPARATOR . $dir . $name);
$file_handle = fopen($new_file_name, 'w');
// write patches to file
foreach ($files as $filename) {
// get offset from filename
list($dir, $offset) = explode('.patch.', $filename, 2);
// read chunk
$patch_handle = fopen(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename), 'r');
$patch_contents = fread($patch_handle, filesize(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename)));
fclose($patch_handle);
// apply patch
fseek($file_handle, $offset);
fwrite($file_handle, $patch_contents);
}
// done with file
fclose($file_handle);
// file permission (prefered 0755)
chmod($final_name, 0777);
// remove patches
foreach ($patch as $filename) {
$new_file_name = storage_path('app') . DIRECTORY_SEPARATOR . trim($filename);
unlink($new_file_name);
}
// simple class (no time to explain)
$file = new UploadedFile(
$final_name,
basename($final_name),
mime_content_type($final_name),
filesize($final_name),
false
);
$dir = $request->patch . DIRECTORY_SEPARATOR;
$object = new \stdClass();
$object->full_path = (string)$file->getPathname();
$object->directory = (string)($dir);
$object->path = (string)($dir . basename($final_name));
$object->name = (string)$file->getClientOriginalName();
$object->mime_type = (string)$file->getClientMimeType();
$object->extension = (string)$file->getExtension();
$object->size = (string)$this->formatSizeUnits($file->getSize());
// exec closure
$closure($file, (object)$object, $request);
}
// response
return response()->json([
'message' => 'Archivo subido correctamente.',
'filename' => $name
], 200);
}
// get dir unique id folder temp
if ($request->isMethod('post')) {
$faker = Faker::create();
$unique_id = $faker->uuid . '-' . time();
$unique_folder_path = $unique_id;
// create directory
Storage::makeDirectory($unique_folder_path);
// permisos directorio
chmod(storage_path('app') . DIRECTORY_SEPARATOR . $unique_folder_path . DIRECTORY_SEPARATOR, 0777);
// response with folder
return response($unique_id, 200)
->header('Content-Type', 'text/plain');
}
}
private function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
}
ยดยดยด
I have the below code, which gives a download link for all files with a .sh extension. I am trying to modify it to give the link only for latest 5 files, and it's not working.
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'sh')
{
echo ''.$file.''."<br>";
}
}
closedir($handle);
}
array_multisort(array_map('filemtime', ($files = glob("*.sh*"))), SORT_DESC, $files );
$newest = array_slice($files, 0, 5);
foreach($newest as $value){
echo ''.$value.''."";
}
I have two model : User & Book. I want create a book for each user with a specific QR code
$users = User::get();
$date = ... ;
$finalCount = 0;
$code = 150;
$userCount = count($users);
foreach ($users as $user) {
$book = new Book();
$book->unique_id = uniqid('', true);
$book->user_id = $user->unique_id;
$book->code = "PP-" . strval(mt_rand(100, 999)) . strval($code);
$book->create_date = $date;
$book->status = 'active';
$book->save();
$QRCode = new BaconQrCodeGenerator;
$file = public_path('/images/book/' . $book->code . '.png');
$QRCode->encoding('UTF-8')
->format('png')
->merge('/public/image/logo.png', .15)
->size(1000)
->generate($book->unique_id, $file);
if (File::exists($file))
$finalCount++;
$code++;
if ($finalCount == $userCount)
break;
}
After this function called, i have 20 book for each user. I used an if statement for break the loop ( if ($finalCount == $userCount) ) but it doesn't work.
I can't understand whats going on here and also i have not any error log
Instead of
$file = public_path('/images/book/' . $book->code . '.png');
try
$file = public_path().'/images/book/' . $book->code . '.png';
I am trying to unlink files that were created the day before
I have a custom application > core > MY_Log.php file and it creates a log for each error level. For easier reading.
logs > DEBUG-04-08-2016.php
logs > ERROR-04-08-2016.php
logs > INFO-04-08-2016.php
logs > DEBUG-03-08-2016.php
logs > ERROR-03-08-2016.php
logs > INFO-03-08-2016.php
Question how am I able to modify the write_log so could delete / unlink files that were created the day before?
<?php
class MY_Log extends CI_Log {
public function write_log($level, $msg)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
&& ! isset($this->_threshold_array[$this->_levels[$level]]))
{
return FALSE;
}
$filepath = $this->_log_path . $level .'-'. date('d-m-Y').'.'.$this->_file_ext;
$message = '';
if ( ! file_exists($filepath))
{
$newfile = TRUE;
// Only add protection to php files
if ($this->_file_ext === 'php')
{
$message .= "";
}
}
if ( ! $fp = #fopen($filepath, 'ab'))
{
return FALSE;
}
flock($fp, LOCK_EX);
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->_date_fmt, 'u') !== FALSE)
{
$microtime_full = microtime(TRUE);
$microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short, $microtime_full));
$date = $date->format($this->_date_fmt);
}
else
{
$date = date($this->_date_fmt);
}
$message .= $this->_format_line($level, $date, $msg);
for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($message, $written))) === FALSE)
{
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === TRUE)
{
chmod($filepath, $this->_file_permissions);
}
return is_int($result);
}
}
First of use
$config['log_threshold'] = 1;
For only error message, so there will be less number of files
Add below code just before $filepath; to delete previous date logs
$unlink_date = date('Y-m-d',strtotime("-1 days"));
$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext;
if ( file_exists($filepath_unlink))
{
unlink($filepath_unlink);
}
I my code is throwing error
Unable to create the "app/uploads/Rescom Summit Bangalore 2016/1578/3" directory
if (Input::file($key)->isValid()) {
$destinationPath = 'app/uploads/'.$event.'/'.$userid.'/3'; // upload path
$extension = Input::file($key)->getClientOriginalExtension(); // getting image extension
$name = Input::file($key)->getClientOriginalName();
$curFilesize = Input::file($key)->getClientSize();
$mime =Input::file($key)->getMimeType();
// dd($mime);
//$fileName = $name; // renameing image
//$exstFileSize = Input::file($destinationPath, $fileName);
if (!File::exists($destinationPath."/boq-".$name)){
//creating details for saving inthe file_handler Table
$fileTblObj->user_id = $userid;
$fileTblObj->eventName = $event ;
$fileTblObj->fileName = "boq-".$name;
$fileTblObj->formPage =3 ;
$fileTblObj->filePath = $destinationPath."/";
$fileTblObj->mime= $mime;
$ans->answer_text = 'Yes';
Input::file($key)->move($destinationPath, "boq-".$name); // uploading file to given path
//Input::file($key)->move($boqPath, $boqname); // uploading file to given path
//Save filedetails
$fileTblObj->save();
$ans->save();
Session::flash('success', 'Upload successfully');
}else if(File::size($destinationPath."/".$name) != $curFilesize){
$fileDtls = $fileTblObj->where('uid',$userid)->where('fileName',$name)->where('formPage',3)->first();
Input::file($key)->move($destinationPath, $name);
$ans->answer_text = 'Yes';
$ans->save();
$fileTblObj->where('id',$fileDtls->id)->update(array('updated_at'=>date("Y-m-d h:m:s",time())));
}
//return Redirect::to('upload');
}
Also in the Browser I am getting
protected function getTargetFile($directory, $name = null)
{
if (!is_dir($directory)) {
if (false === #mkdir($directory, 0777, true)) {
throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
}
} elseif (!is_writable($directory)) {
This completely works fine on my local system
I have changed the permission
chmod -R 777 /var/www/laravel/app
Can anyone help me out with this
Thanks