I've used PSR logger to get logs. But it will create just one file for all dates. I need to get separate log files to each date. How to do that?
require_once '../../logger/vendor/autoload.php';
require_once '../../logger/Psr/Log/Logger.php';
use Katzgrau\KLogger\Logger;
use Psr\Log\LogLevel;
$logPath = '/var/www/html/logs';
$logger = new Logger($logPath, LogLevel::DEBUG, array ( 'filename' => 'driver_api' , 'extension' => 'log' ));
$logger->log( $level, $message , $context);
`
use log rotator
protected function log_rotate($logpath, $filename, $extention){
$logfilename = $logpath.'/'.$filename.'.'.$extention; //not needed when included
$logfilestokeep = 15;
$fileDate = '';
if (file_exists($logfilename)) {
if (date("Y-m-d", filemtime($logfilename)) !== date('Y-m-d')) {
$fileDate = date("Y-m-d", filemtime($logfilename));
$newName = $logpath .'/'.$filename. "_" . $fileDate.'.'.$extention;
if (file_exists($logfilename)) {
rename($logfilename, $newName);
}
}
}
}
Related
I want to read and write XLSM type file using PHP. I tried using PHPSpreadsheet for this but it doesn't support XLSM extension.
One possible solution could be to use EasyXLS (https://www.easyxls.com/manual/basics/import-from-xlsx-file-format.html)
// Create an instance of the class that imports XLSM files
$workbook = new COM("EasyXLS.ExcelDocument");
// Import XLSM file
$workbook->easy_LoadXLSXFile("C:\\Samples\\Excel to import.xlsm");
// Get the table of the second worksheet
$xlsSecondTable = $workbook->easy_getSheet("Second tab")->easy_getExcelTable();
// Add more data to the second sheet
$xlsSecondTable->easy_getCell_2("A1")->setValue("Data added by Tutorial37");
for ($column=0; $column<5; $column++)
{
$xlsSecondTable->easy_getCell(1, $column)->setValue("Data " . ($column + 1));
}
// Generate the XLSM file
$workbook->easy_WriteXLSXFile("C:\Samples\Excel with macro.xlsm");
But I was unable to find any Library for this.
Does anyone have any possible solution for this or some other way for this?
function excel($excelfile, $sheet = false){//from stores.blade.php
$tempfile = resource_path("uploads/excel.xlsm");//it just needs a place to store the XML file temporarily, this function only works in Laravel, replace with a filename
if($sheet){//load XML file
//$XML = file_get_contents($tempfile);
$XML = simplexml_load_file($excelfile);
$XML = json_decode(json_encode((array)$XML), TRUE);
$excelfile = pathinfo($sheet)['basename'];
if($excelfile == "workbook.xml"){
$RET = [];
foreach($XML["sheets"]["sheet"] as $data){
$RET[ $data["#attributes"]["sheetId"] ] = $data["#attributes"]["name"];
}
return [
'Filename' => $excelfile,
'SheetName' => "sys_workbook",
'SheetData' => $RET,
];
} else if($excelfile == "sharedStrings.xml"){
foreach($XML["si"] as $index => $value){
if(isset($value["t"])){
$value = $value["t"];
} else {
foreach($value["r"] as $index2 => $value2){
if(is_array($value2["t"])){
$value2["t"] = $value2["t"][0];
}
$value["r"][$index2] = $value2["t"];
}
$value = implode("", $value["r"]);
}
if(is_array($value)){
$value = $value[0];
}
$XML["si"][$index] = $value;
}
return [
'Filename' => $excelfile,
'SheetName' => "sys_strings",
'SheetData' => $XML["si"],
];
} else if(isset($XML["sheetPr"])){
return [
'Filename' => $excelfile,
'SheetName' => $XML["sheetPr"]["#attributes"]["codeName"],
'SheetData' => $XML["sheetData"]["row"],
];
}
return false;
} else {//load ZIPped XLSM file
$files = [];
$zip = new ZipArchive;
if ($zip->open($excelfile) === TRUE) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
if(startswith($filename, "xl/worksheets/") || $filename == "xl/workbook.xml" || $filename = "xl/sharedStrings.xml"){
copy("zip://" . $excelfile . "#" . $filename, $tempfile);
$XML = excel($tempfile, $filename);
if($XML !== false){
$files[ $XML["SheetName"] ] = $XML["SheetData"];
}
}
}
#unlink($tempfile);
$zip->close();
}
var_dump($files);
die();
}
}
I started work on this, I got this far. The problem is, I don't know how the shared strings (sys_strings) are referenced, and you'd need an equation evaluator to handle the functions. I HOPE, the sheets are in order, so Sheet1 becomes the first array value in sys_workbook.
For anyone still looking for a solution to this problem, the following XLSX reader can parse XLSM without a problem. Also saves the headache in interpreting Excel timestamps and data formats. Tried and tested.
I did not test the Writer though, yet!
https://github.com/shuchkin/simplexlsx
After hours of trying to figure out why php "ZipArchive" does not work as expected, due to Mac OS adding a "__MACOSX" folder in the zip compression process.
How would I go about deleting "__MACOSX" folder in a zip archive during the upload process in a form?
Below is what I'm working with:
<?php
public function uploadZip($file)
{
$advert_index;
$zip = new \ZipArchive;
if (true === $zip->open($file['tmp_name'])) {
$source = trim($zip->getNameIndex(0), '/');
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
// Determine output filename (removing the `$source` prefix).
$substring_name = substr($name, strlen($source)+1);
$file = $this->option['uploads_path'] . $this->option['advert_id'] . '/' . $substring_name;
// Store the adverts `index.html` file URL to be returned.
if ('html' === pathinfo($name, PATHINFO_EXTENSION)) {
$advert_index = basename($name);
}
// Create the directories if necessary.
$dir = dirname($file);
if (! is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Read from Zip and write to disk.
$fpr = $zip->getStream($name);
$fpw = fopen($file, 'w');
while ($data = fread($fpr, 1024)) {
fwrite($fpw, $data);
}
fclose($fpr);
fclose($fpw);
}
$zip->close();
return array(
'status' => true,
'message' => array(
'index' => $advert_index,
'type' => 'text/html', // #HACK: Set MIME type manually. #TODO: Read MIME type from file.
),
);
}
return array(
'status' => false,
'message' => 'Upload failed',
);
}
Any help would be much appreciated :)
Note: I Managed to find the file just can't get it to be removed.
// Check to see the __MACOSX
if($zip->getNameIndex($i) === "__MACOSX/") {
error_log($zip->getNameIndex($i) . ' - Error here continue');
$zip->deleteName("__MACOSX/");
continue; // Move on to the next iteration
// $zip->deleteIndex($i);
} else {
$name = $zip->getNameIndex($i);
}
It was actually very simple, instead to trying to delete the folder within the zip-archive just had to skip all indexes aka filename that begin with a certain string while looping through the files.
if(substr($zip->getNameIndex($i), 0, 9) === "__MACOSX/") {
continue;
} else {
$name = $zip->getNameIndex($i);
}
Hi Here i am using CActiveFrom fileField to upload the file in the server but the pdf files not saving remaining all the extensions are saving here is my controller code to save the file
controller
if(isset($_POST['Uploadinfo']))
{
$model->attributes=$_POST['Uploadinfo'];
$file = CUploadedFile::getInstance($model, 'imageId');
$model->imageId=CUploadedFile::getInstance($model, 'imageId');
$valid = $model->validate();
date_default_timezone_set('Asia/Kolkata');
$serverTime = date("Y-m-d H:i:s", time());
if(!empty($file->name) && $valid)
{
$modelFileLocation->filename = microtime() . $file->name;
$modelFileLocation->orgfilename = $file->name;
$modelFileLocation->type = 1;
$modelFileLocation->createdOn = $serverTime;
$modelFileLocation->lastModifiedBy = 'lecturer';
$valid = $modelFileLocation -> validate();
$modelFileLocation->deptId = $_POST['Uploadinfo']['departmentId'];
print_r($file);
if ($modelFileLocation->save())
{
$file = CUploadedFile::getInstance($model, 'imageId');
print_r($modelFileLocation);
print_r($file);
die();
$model->userId = $_POST['Uploadinfo']['userId'];
$model->imageId = $modelFileLocation->id;
$model->departmentId = 1;
$model->createdOn = $serverTime;
$model->lastModifiedBy = 'lecturer';
if ($model->save())
{
$modeldocumentinfo->property = $file->type;
$modeldocumentinfo->fileName = $modelFileLocation->filename;
$modeldocumentinfo->creator = 'lecturer';
$modeldocumentinfo->lastUploadedOn = $serverTime;
$modeldocumentinfo->uploadId = $model->id;
$modeldocumentinfo->viewers = 0;
$modeldocumentinfo->save();
$file->saveAs('uploads/files/' . $modelFileLocation->filename);
print_r($file);
die();
//Yii::app()->user->setFlash('uploadsuccess', "File Uploaded Successfully...");
$this->redirect(array('lmaterialitview'));
}
}
in above code i print the instance of file before and after the $modelFileLocation model saving before this model is saving the file instance is getting but after this saving the model the file instance getting empty
here is the instance code
instance message
CUploadedFile Object ( [_name:CUploadedFile:private] => example.pdf [_tempName:CUploadedFile:private] => C:\wamp\tmp\php4BB.tmp [_type:CUploadedFile:private] => application/pdf [_size:CUploadedFile:private] => 205374 [_error:CUploadedFile:private] => 0 [_e:CComponent:private] => [_m:CComponent:private] => )
and in the second print_r() it is disappering but for remaining extensions it is getting appear and saving
just set the $deleteTempFile argument to false
$file->saveAs('uploads/files/' . $modelFileLocation->filename, false);
i have an issue with uploading multiple files to disk. here is my code.
i have a request with 2 pictures that gets sent to a upload function. the 2 pictures are in a var called $multiUpload
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$file = array();
$filename = array();
foreach($multiUpload as $key=>$val){
// get the file extension
$file[] = explode('.',$val);
// create custom file name
$filename[] = time().'.'.$file[$key][1];
//send to the upload function
$this->uploadToDisk($folderPath, $filename[$key]);
// sleep 1 sec so that the pic names will be different
sleep(1);
}
return $filename;
}
public function uploadToDisk($folderPath, $filename)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->setDestination($folderPath);
$adapter->addFilter( 'Rename',array(
'target' => $folderPath."/".$filename,
'overwrite' => true
) );
if ($adapter->receive()) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
this will return
Array
(
[0] => Array
(
[0] => 1332977938.jpg
[1] => 1332977939.jpg
)
)
but only array[0][0] or 1332977938.jpg will actually get saves to the disk.
Why are they now both get saved? wired
any ideas?
I suspect the second call to uploadToDisk is returning fail because you can only call Zend_File_Transfer_Adapter_Http::receive() once for each file. Since you are not specifying a file when calling receive, it is receiving all of the files the first time you call uploadToDisk and subsequently is failing with a File Upload Attack error.
Here is some code you can try. This tries to receive each file individually and then save them one at a time with each call to uploadToDisk.
A few notes about the code:
The first parameter to uploadToDisk ($val) may need to be changed as I am not sure what the original values are. It should correspond to one of the element names used for the file upload (See Zend_File_Transfer_Adapter_Http::getFileInfo()) for a list of the files.
I changed the method for generating a unique filename so you don't have to sleep(1)
Zend_File_Transfer_Adapter_Abstract::setDestination() is deprecated and will go away in the future. Instead, just use the Rename filter. When using Rename, setDestination() has no effect.
And here it is...
<?php
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$filenames = array();
foreach($multiUpload as $key => $val){
// get the file extension
$ext = explode('.', $val);
$ext = $ext[sizeof($ext) - 1];
// create custom file name
do {
$filename = uniqid(time()) . '.' . $ext;
$diskPath = $folderPath . $filename;
} while (file_exists($diskPath));
$filenames[$key] = $filename;
//send to the upload function
// $val is the file to receive, $diskPath is where it will be moved to
$this->uploadToDisk($val, $diskPath);
}
return $filename;
}
public function uploadToDisk($file, $filename)
{
// create the transfer adapter
// note that setDestination is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($file)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
I've got this PHP script I'm working on to import pay-stubs into Drupal. It's doing everything the way I want except the script is not attaching the uploaded PDF file to the node.
A few notes; Drupal's filesystem is set to private, not sure if this makes a difference or not. Second, the pdf files are already in the correct location 'paystubs/[uid]/paystub_1.pdf' so I think my problem is that the file is not being associated to the node correctly.
Here is the code
function create_drupal_node($employeeID, $employeeDate, $drupalUid, $file2) {
$sourcePDF = "/var/www/html/mgldev.************.com/burst_pdfs/pdfs/" . $file2;
$destinationPDF = '/paystubs/' . $drupalUid . '/' . $file2;
$destination = '/paystubs/' . $drupalUid . '/';
if (!file_check_directory($destination, TRUE)){
echo "Failed to check dir, does it exist?";
mkdir($destination);
echo "trying to drupal mkdir...";
}
// Copy the file to the Drupal files directory
if (file_exists($sourcePDF)) {
if(!rename($sourcePDF, $destinationPDF)) {
echo "Failed to move file\n";
}
}
//Create node and attach file uplaod
$file_drupal_path = "paystubs/" . $drupalUid . "/" . $file2;
$mime = 'pdf/application';
$file = new stdClass();
$file->filename = $file2;
$file->filepath = $file_drupal_path;
$file->filemime = $mime;
$file->filesize = filesize($file_drupal_path);
$file->uid = $drupalUid;
$file->status = FILE_STATUS_PERMANENT;
$file->timestamp = time();
drupal_write_record('files', $file);
$node = new StdClass();
$node->type = 'paystub';
$node->body = $employeeID;
$node->title = $employeeDate;
$node->field_paystub_upload = array(
array(
'fid' => $file->fid,
'title' => $file2,
'filename' => $file->filename,
'filepath' => $file->filepath,
'filesize' => $file->filesize,
'mimetype' => $mime,
'data' => array(
'description' => $file2,
),
'list' => 1,
),
);
$node->uid = $drupalUid;
$node->status = 1;
$node->active = 1;
$node->promote = 1;
node_save($node);
}
The node is created and the title and body of the node have the right values. When I look at the node using Devel module I can see that the 'field_paystub_upload' array is null. So for some reason its doing everything right except attaching the file to the node and that is what I've been banging my head on for days. Best response gets on free internet?
Drupal's file.inc file_save_upload uses $_FILES, which is a global, magically set by PHP. Drupal expects an uploaded file, not a file that exists locally.
You best just call a custom file-saver method, to process local files. Make sure its path up in the files database-table too. file_save_upload will be valuable for creating such a helper method.
Big thanks to berkes for helping me solve this problem. Turns out that since the files were already on the drupal webserver and not being uploaded to PHP $_FILES global variable, I was unable to programmatically upload the file correctly.
This was causing every other way I've tried to fail. I tried using Drupals defualt upload module and I also tried using CCK's fielfield module both were not working. Thanks to berkes suggestion I found a function that comes with CCK's filefield widget to save uploaded files that are already on the server. Hopefully this helps someone else.
This is the function I found that can save a file thats already on the web-server.
Here is the working code I used to create the node and attach the file after calling field_file_save_file.
function create_drupal_node($employeeID, $employeeDate, $drupalUid, $file2){
$file_remove_html_extention = substr($file2, 0, -7);
$file_pdf = $file_remove_html_extention . '.pdf';
$node = new stdClass();
$node->type = 'paystub';
$node->status = 1;
$node->uid = $drupalUid;
$node->title = $employeeDate . ' - eStub';
$node->body = $employeeID;
$node->created = time();
$node->changed = $node->created;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;
$node->language = 'en';
$file = '/var/www/html/mgldev.foobar.com/burst_pdfs/pdfs/' . $file_pdf;
// Get the path to your Drupal site's files directory
$dest_folder = '/paystubs/' . $drupalUid;
$dest = 'paystubs/' . $drupalUid . '/' . $file_pdf;
if (!file_check_directory($dest_folder, TRUE)){
mkdir($dest_folder);
}
// Load the CCK field
$field = content_fields('field_paystub_upload', 'paystub');
// Load the appropriate validators
$validators = array_merge(filefield_widget_upload_validators($field));
// Create the file object
$file = field_file_save_file($file, $validators, $dest_folder);
// Apply the file to the field, this sets the first file only, could be looped
// if there were more files
$node->field_paystub_upload = array(0 => $file);
// The file has been copied in the appropriate directory, so it can be
// removed from the import directory
unlink($file);
// change file status to permanent
file_set_status($file,1);
node_save($node);
}
</pre></code>
Thanks again berkes