Copy logs file to another path laravel - laravel

I want to get a copy of the logs file using programmability, I just tried to copy the files using this command
$co= Storage::copy('logs/laravel-'.$start.'.log',$filename);
dd($co);
but I have an error which says the file does not exist,
I believe that is because storage looking in the default driver of the config file, how can I tell laravel to look in logs folder when I want to run the copy command, is there any way to do that .

Hi You can get the path of the log file with storage_path() and copy your file anywhere you want with php copy function
I think that is a easy way that you can do it:
<?php
function copyLogFile($logFileName, $destination)
{
$logPathDir = storage_path().'/logs/';
$logFilePath = $logPathDir . $logFileName;
if (file_exists($logFilePath)) {
if( !#copy($logFilePath, $destination) ) {
echo "File can't be copied! \n";
$errors= error_get_last();
echo "COPY ERROR TYPE: ".$errors['type'].PHP_EOL;
echo "COPY ERROR MESSAGE: ".$errors['message'];
}
else {
echo "File has been copied! \n";
}
} else {
echo "The file $logFilePath does not exist";
}
}
// Store the path of destination file
$destination = '/home/azibom/Desktop/backup.log';
// Your log file name
$start = "2020-01-01";
$logFileName = 'laravel-'.$start.'.log';
copyLogFile($logFileName, $destination);
?>

Related

Laravel - "file does not exist or is not readable", but the file is moved successfully

I get the follow error:
The "C:\xampp\tmp\php49D8.tmp" file does not exist or is not readable.
But the file is copied successfully
My controller code is:
$fileResult=$file->move(self::UPLOAD_DIR, $name_file);
if(!$fileResult){
$result = array("status" => "500",
"error"=> array("error" => "Error in the file move"));
return response(json_encode( $result ), $result["status"])
->header("Content-Type", "application/json");
}
Screenshot: here
Why can be the problem?
Call $validator->fails() can delete uploading file
use
$file = $request->file('file');//get your file
$fileResult=$file->move(self::UPLOAD_DIR, $file->getClientOriginalName());

Laravel Storing Image File Retrieved From External Url in Spesific Folder

I'm getting users' profile pictures from another site. I want to create a folder for users who have a URL for the image. Because every user's profile picture must be in its own file. This is what I want to do. I'm running with custom artisan commands.
foreach ($adminUser as $user) {
$a= DB::table('users')->where('email', $user['email'])->first();
if($a) {
echo "\n ", $a->name, " this user already exists. \n";
continue;
} else {
$a = User::create($user);
echo "\n ", $user['name'], " created. \n";
if (isset($user['link']) && strlen($user['link']) > 0) {
$folder_Path = public_path().'/user_images/' . $a->id;
File::makeDirectory($folder_Path, $mode = 0777, true, true);
$contents = file_get_contents($user['link']);
$file_name = basename($user['link']);
Storage::disk('uploads')->put($file_name, $contents);
$this->info(" |--> Profile picture uploaded.");
}
}

ZipArchive::extractTo doesn't working on Windows Platform

I'm using the following code (Windows Hosting - Plesk/Win) :
<?php
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$path = getcwd();
$path = str_replace("/","\\",$path);
echo $path;
$zip->extractTo('E:\\Vhosts\\domain.com\\httpdocs\\test\\');
$zip->close();
echo 'Ok!';
} else {
echo 'Error!';
}
?>
When I run this code, the following message appears:
Warning:
ZipArchive::extractTo(E:\Vhosts\domain.com\httpdocs\test/image1.jpg)
[ziparchive.extractto]: failed to open stream: Permission denied in
E:\Vhosts\domain.com\httpdocs\test\extractphp.php on line 10
I don't now why this command put a slash before the unzipped file (test/image1.jpg).
How can I resolve this issue ?

Magento Index Management issues, products not displaying in category pages

This is a Magento issue - using the Enterprise edition. Unfortunately their support technicians are all in San Francisco, and I am based in the UK, so their support to me is restricted to a certain time window.
I have categories which are active, set to display products, and/or products and static blocks, and are sub categories of the default root category.
I also have test products, which are enabled, in stock, with quantities, visible in Catalog, Search, and are assigned to these sub categories.
The problem is, my test products (or any product!) do not show on the category page. I am using the default/default themes, and have not changed the page_layout.
I have cleared/flushed all caches, and reindexed.
However, most of my indexes appear as status 'SCHEDULED' and have never been updated - there are no checkboxes next to these, so I cannot select them to 'reindex data'.
See the screenshot.
If anyone has any clues on how to fix this, I will be very happy.
Thanks
Reindex is somewhat required to display products on front, especially if you have flat tables enabled (Admin Panel > System > Configuration > Catalog > Frontend: "Use Flat Catalog Category" and "Use Flat Catalog Product").
The situation with indexes is a bit of strange. It you do it on your local workstation or you have access to shell on hosting you can manually force indexes by running this command:
pwd$ php shell/indexer.php reindexall
If you have enabled flat tables you can try to disable them, to check if products will be visible on front.
You need to also put right permissions on var and media folders and theirs content. 755 should be ok.
Problem solved. Thanks guys for your answers but it was none of the above.
I had installed a Product Feature module incorrectly. I was under the assumption that when developing in app/code/local/... anything that didn't work would fall back to app/code/core/...
Sadly this was not the case. My fault, and everyone knows the phrase about making assumptions.
Magento has a very steep learning curve!
Thats really interesting, I had a similar issue recently where a reindex was not fully working. However I didnt get scheduled being displayed.
Can I ask what version of Enterprise are you using ?
As Ventus suggested a tried and tested method of forcing a reindex is to use the shell script, To do this you need to SSH into your server. Then use the cd command ( change directory ) to where your website is located on the file system. E.g. cd /var/www/....
From here run php shell/indexer.php reindexall
Set cron to run this will take care of reindexing provided you have not changed crontab values.
From your screen it looks like you have never run a cron on this setup.
Put this code below into a .php file in your magento install and then run it from your URL, this will clean and re-index everything. You can run it from a cron job. Any errors then you have a problem with yor database in witch case you should back it up and then re-creat it in a new DB instance.
<?php
set_time_limit(0);
require_once dirname(__FILE__) . '/app/Mage.php';
//get all stores
$websites = Mage::app()->getWebsites();
$thisstore = $websites[1]->getDefaultStore()->getCode();
echo "Store: ".$thisstore."<br/>";
//clean var dir
$dirs = array(
'downloader/.cache/*',
'var/cache/',
'var/locks/',
'var/log/',
'var/report/',
'var/minifycache/',
'var/mincache/',
'var/tmp/'
);
foreach($dirs as $v => $k) {
exec('rm -rf '.$k);
}
/*
//clean out sessions
$dirs = array('var/session/');
foreach($dirs as $v => $k) {
exec('rm -rf '.$k);
}
*/
//clean db log files
$xml = simplexml_load_file('./app/etc/local.xml', NULL, LIBXML_NOCDATA);
$db['host'] = $xml->global->resources->default_setup->connection->host;
$db['name'] = $xml->global->resources->default_setup->connection->dbname;
$db['user'] = $xml->global->resources->default_setup->connection->username;
$db['pass'] = $xml->global->resources->default_setup->connection->password;
$db['pref'] = $xml->global->resources->db->table_prefix;
global $db;
$tables = array(
'catalogsearch_fulltext',
'dataflow_batch_export',
'dataflow_batch_import',
'log_customer',
'log_quote',
'log_summary',
'log_summary_type',
'log_url',
'log_url_info',
'log_visitor',
'log_visitor_info',
'log_visitor_online',
'importexport_importdata',
'core_url_rewrite',
'report_viewed_product_index',
'report_event',
'core_cache',
'core_cache_option',
'core_cache_tag'
);
mysql_connect($db['host'], $db['user'], $db['pass']) or die(mysql_error());
mysql_select_db($db['name']) or die(mysql_error());
foreach($tables as $v => $k) {
mysql_query('SET FOREIGN_KEY_CHECKS=0; '.'TRUNCATE `'.$db['pref'].$k.'`;'.' SET FOREIGN_KEY_CHECKS=1; ') or die(mysql_error());
}
///---------------------------------//
// now run standard magento cleanup file
## Function to set file permissions to 0644 and folder permissions to 0755
function AllDirChmod( $dir = "./", $dirModes = 0755, $fileModes = 0644 ){
$d = new RecursiveDirectoryIterator( $dir );
foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){
if( $path->isDir() ) chmod( $path, $dirModes );
else if( is_file( $path ) ) chmod( $path, $fileModes );
}
}
## Function to clean out the contents of specified directory
function cleandir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && is_file($dir.'/'.$file)) {
if (unlink($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (file) NOT deleted!<br />'; }
}
else if ($file != '.' && $file != '..' && is_dir($dir.'/'.$file)) {
cleandir($dir.'/'.$file);
if (rmdir($dir.'/'.$file)) { }
else { echo $dir . '/' . $file . ' (directory) NOT deleted!<br />'; }
}
}
closedir($handle);
}
}
function isDirEmpty($dir){
return (($files = #scandir($dir)) && count($files) <= 2);
}
// rebuild everything!!!
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');
$processes->walk('reindexAll');
$processes->walk('reindexEverything');
echo "----------------------- CLEANUP START -------------------------<br/>";
$start = (float) array_sum(explode(' ',microtime()));
echo "<br/>*************** SETTING PERMISSIONS ***************<br/>";
echo "Setting all folder permissions to 755<br/>";
echo "Setting all file permissions to 644<br/>";
AllDirChmod( "." );
echo "Setting pear permissions to 550<br/>";
echo "<br/>****************** CLEARING CACHE ******************<br/>";
if (file_exists("var/cache")) {
echo "Clearing var/cache<br/>";
cleandir("var/cache");
}
if (file_exists("var/session")) {
echo "Clearing var/session<br/>";
cleandir("var/session");
}
if (file_exists("var/minifycache")) {
echo "Clearing var/minifycache<br/>";
cleandir("var/minifycache");
}
if (file_exists("downloader/pearlib/cache")) {
echo "Clearing downloader/pearlib/cache<br/>";
cleandir("downloader/pearlib/cache");
}
if (file_exists("downloader/pearlib/download")) {
echo "Clearing downloader/pearlib/download<br/>";
cleandir("downloader/pearlib/download");
}
if (file_exists("downloader/pearlib/pear.ini")) {
echo "Removing downloader/pearlib/pear.ini<br/>";
unlink ("downloader/pearlib/pear.ini");
}
if (file_exists("media/catalog/product/cache/")) {
echo "Removing media/catalog/product/cache/<br/>";
unlink ("media/catalog/product/cache/");
}
if (file_exists("media/tmp/")) {
echo "Removing media/tmp/<br/>";
unlink ("media/tmp/");
}
date_default_timezone_set("Europe/London");
echo "Start Cleaning all caches at ... " . date("Y-m-d H:i:s") . "<br/>";
ini_set("display_errors", 1);
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();
$types = Mage::app()->getCacheInstance()->getTypes();
try {
echo "Cleaning data cache... <br/>";
flush();
foreach ($types as $type => $data) {
echo "Removing $type ... ";
echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
echo "<br/>";
}
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "<br/>";
try {
echo "Cleaning stored cache... ";
flush();
echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
echo "<br/>";
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
try {
echo "Cleaning merged JS/CSS...";
flush();
Mage::getModel('core/design_package')->cleanMergedJsCss();
Mage::dispatchEvent('clean_media_cache_after');
echo "[OK]<br/>";
} catch (Exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
try {
echo "Cleaning image cache... ";
flush();
echo Mage::getModel('catalog/product_image')->clearCache();
echo "[OK]<br/>";
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "<br/>************** CHECKING FOR EXTENSIONS ***********<br/>";
If (!isDirEmpty("app/code/local/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/local folder<br/>";
}
If (!isDirEmpty("app/code/community/")) {
echo "-= WARNING =- Overrides or extensions exist in the app/code/community folder<br/>";
}
$end = (float) array_sum(explode(' ',microtime()));
echo "<br/>------------------- CLEANUP COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>";
//sitemap refresh
$collection = Mage::getModel('sitemap/sitemap')->getCollection();
foreach ($collection as $sitemap) {
try {
$sitemap->generateXml();
}
catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
?>

Mage registry key "_singleton/core/resource" already exists in magento

I am facing this problem on my site Mage registry key "_singleton/core/resource" already exists, Please help me how to solve this error.
I have checked the folder and file permission
changed the lib/Zend/Cache/Backend/File.php as 'cache_dir' => null, to 'cache_dir' => 'tmp',
Changes in the index.php commented the line
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
Mage::setIsDeveloperMode(true);
}
After doing these changes it was working well and today it stops again and displaying the same problem
I have tried each and every way but not get the success.
I stumbled upon this problem before, and this was because of the cache. if you could still access the Magento Admin panel, go and flush your Cache Storage (the two main buttons near the top of the System -> Cache Management page).
You can also refer to this blog post for more help on the cache problem.
It is very important to clear the Compiler cache and after that turn it on in backend of Magento.
Clear the cache
SSH:
find ./var/cache -type f -delete
FTP:
mrm -r ./var/cache ; mkdir ./var/cache
Disable/Clear Magento compilation
SSH:
php -f shell/compiler.php -- disable
php -f shell/compiler.php -- clear
FTP:
mv ./includes ./includes.unused
Put this file in your Magento root folder ie: clear-cache.php and execute it through terminal.
php /home/magento/www/clear-cache.php
This will clear all cache and rebuild all indexes.
Fixed the issue you described in Magento Enterprise 1.11.2 when I could not load any page or get into admin and deleting /var/cache did not fix the issue.
<?php
// Include Magento
require_once dirname(__FILE__).'/app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
// Set user admin session
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
Mage::getSingleton('admin/session')->setUser($userModel);
// Call Magento clean cache action
Mage::app()->cleanCache();
// Enable all cache types
$enable = array();
foreach(Mage::helper('core')->getCacheTypes() as $type => $label){
$enable[$type] = 1;
}
Mage::app()->saveUseCache($enable);
// Refresh cache's
echo 'Refreshing cache...';
try {
Mage::getSingleton('catalog/url')->refreshRewrites();
echo 'Catalog Rewrites was refreshed successfully';
} catch ( Exception $e ) {
echo 'Error in Catalog Rewrites: '.$e->getMessage();
}
// This one caused an error for me - you can try enable it
/*try {
Mage::getSingleton('catalog/index')->rebuild();
echo 'Catalog Index was rebuilt successfully';
} catch ( Exception $e ) {
echo 'Error in Catalog Index: '.$e->getMessage();
}*/
try {
$flag = Mage::getModel('catalogindex/catalog_index_flag')->loadSelf();
if ( $flag->getState() == Mage_CatalogIndex_Model_Catalog_Index_Flag::STATE_RUNNING ) {
$kill = Mage::getModel('catalogindex/catalog_index_kill_flag')->loadSelf();
$kill->setFlagData($flag->getFlagData())->save();
}
$flag->setState(Mage_CatalogIndex_Model_Catalog_Index_Flag::STATE_QUEUED)->save();
Mage::getSingleton('catalogindex/indexer')->plainReindex();
echo 'Layered Navigation Indices was refreshed successfully';
} catch ( Exception $e ) {
echo 'Error in Layered Navigation Indices: '.$e->getMessage();
}
try {
Mage::getModel('catalog/product_image')->clearCache();
echo 'Image cache was cleared successfully';
} catch ( Exception $e ) {
echo 'Error in Image cache: '.$e->getMessage();
}
try {
Mage::getSingleton('catalogsearch/fulltext')->rebuildIndex();
echo 'Search Index was rebuilded successfully';
} catch ( Exception $e ) {
echo 'Error in Search Index: '.$e->getMessage();
}
try {
Mage::getSingleton('cataloginventory/stock_status')->rebuild();
echo 'CatalogInventory Stock Status was rebuilded successfully';
} catch ( Exception $e ) {
echo 'Error in CatalogInventory Stock Status: '.$e->getMessage();
}
try {
Mage::getResourceModel('catalog/category_flat')->rebuild();
echo 'Flat Catalog Category was rebuilt successfully';
} catch ( Exception $e ) {
echo 'Error in Flat Catalog Category: '.$e->getMessage();
}
try {
Mage::getResourceModel('catalog/product_flat_indexer')->rebuild();
echo 'Flat Catalog Product was rebuilt successfully';
} catch ( Exception $e ) {
echo 'Error in Flat Catalog Product: '.$e->getMessage();
}
echo 'Cache cleared';
// Rebuild indexes
echo 'Rebuilding indexes';
for ($i = 1; $i <= 9; $i++) {
$process = Mage::getModel('index/process')->load($i);
try {
$process->reindexAll();
} catch ( Exception $e ) {
echo 'Error rebuilding index '.$i.': '.$e->getMessage();
}
}
echo 'Indexes rebuilt';
echo 'Finished!';
In index.php put this directly after require_once $mageFilename;
$app = Mage::app();
$cache = $app->getCache();
$cache->clean();
Refresh your broken web page, then remove the code.
I can see this being quite old thread, but I came across similar problem today. I have two observers on catalog_product_prepare_save and catalog_product_save_after, both are triggered in one php execution.
It turns out we were using methods from ProductObserver.php file (XXXX_Persona_Model_ProductObserver class) as listeners. It worked fine on Windows and Macs, but was failing with similar message on production (Linux). You guessed it - Linux is case sensitive. Correcting file name to Productobserver.php (and class name accordingly) solved the problem for us.

Resources