I'm trying to set up a Jodit WYSIWYG and I'm finding their documentation rather confusing. I'm looking at a way to change the file name while uploading.
cause: if I upload the file name with the same name in the root directory it will be replaced the old file.
So, How changing file name while uploading for voiding replace the old name file.
here procedure is upload Image 3 files
1.jpg,2.jpg,3.jpg
when Debug mode the name of the file is in
$files = $_FILES[$source->defaultFilesKey];
in function
public function move(Config $source) {
$files = $_FILES[$source->defaultFilesKey];
/**
* #var $output File[]
*/
$output = [];
try {
if (isset($files) and is_array($files) and isset($files['name']) and is_array($files['name']) and count($files['name'])) {
foreach ($files['name'] as $i => $file) {
if ($files['error'][$i]) {
throw new \Exception(isset(Helper::$upload_errors[$files['error'][$i]]) ? Helper::$upload_errors[$files['error'][$i]] : 'Error', $files['error'][$i]);
}
$path = $source->getPath();
$tmp_name = $files['tmp_name'][$i];
$new_path = $path . Helper::makeSafe($files['name'][$i]);
if (!move_uploaded_file($tmp_name, $new_path)) {
if (!is_writable($path)) {
throw new \Exception('Destination directory is not writeble', Consts::ERROR_CODE_IS_NOT_WRITEBLE);
}
throw new \Exception('No files have been uploaded', Consts::ERROR_CODE_NO_FILES_UPLOADED);
}
$file = new File($new_path);
try {
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getRoot(), pathinfo($file->getPath(), PATHINFO_EXTENSION));
} catch (\Exception $e) {
$file->remove();
throw $e;
}
if (!$file->isGoodFile($source)) {
$file->remove();
throw new \Exception('File type is not in white list', Consts::ERROR_CODE_FORBIDDEN);
}
if ($source->maxFileSize and $file->getSize() > Helper::convertToBytes($source->maxFileSize)) {
$file->remove();
throw new \Exception('File size exceeds the allowable', Consts::ERROR_CODE_FORBIDDEN);
}
$output[] = $file;
}
}
} catch (\Exception $e) {
foreach ($output as $file) {
$file->remove();
}
throw $e;
}
return $output;
}
so $file is keep the name file in array
i need to foreach $fiels and change array['name'] value.
but i don't konw how to change it.
UPDATE after I try i got a solution
use foreach statment for loop $files['name'].
public function move(Config $source) {
$files = $_FILES[$source->defaultFilesKey];
foreach ($files['name'] as $i => $file) {
$files['name'][$i] = round(microtime(true)).($files['name'][$i]);
}
/**
* #var $output File[]
*/
$output = [];
.
.
.
}
You can use saveas method of php to upload new renamed file:
//New name for file
$newName = date("m-d-Y-h-i-s", time())."-".$filename.'.'.$ext;
$model->files = CUploadedFile::getInstance($model,'files');
$fullFileSource = Yii::getPathOfAlias('webroot').'/upload/'.$newName;
$model->files->saveAs($fullFileSource);
Related
I have a folder with some randomly named files that contain data that I need.
In order to use the data, I have to move the files to another folder and name the file 'file1.xml'
Every time a file is moved and renamed, it replaces a previous 'file1.xml' in the destination folder.
The source folder contains all the other randomly named files which are kept as an archive.
The php will be run via a cron job every 48 hours
The following works, but it's for ftp. I need to edit it for local files.
$conn = ftp_connect('ftp.source.com'); ftp_login($conn, 'username', 'password'); // get file list $files = ftp_nlist($conn, '/data'); $mostRecent = array( 'time' => 0, 'file' => null ); foreach ($files as $file) { // get the last modified time $time = ftp_mdtm($conn, $file); if ($time > $mostRecent['time']) { // this file is the most recent so far $mostRecent['time'] = $time; $mostRecent['file'] = $file; } } ftp_get($conn, "/destinationfolder/file1.xml", $mostRecent['file'], FTP_BINARY); ftp_close($conn);
I didn't test it but I think this should work (comparing your ftp script):
<?php
$conn = ftp_connect('ftp.source.com');
ftp_login($conn, 'username', 'password');
// get file list
$files = ftp_nlist($conn, '/data');
$mostRecent = array( 'time' => 0, 'file' => null );
foreach ($files as $file) {
// get the last modified time
$time = ftp_mdtm($conn, $file);
if ($time > $mostRecent['time']) {
// this file is the most recent so far
$mostRecent['time'] = $time;
$mostRecent['file'] = $file;
}
}
ftp_get($conn, "/destinationfolder/file1.xml", $mostRecent['file'], FTP_BINARY); ftp_close($conn);
?>
New:
<?php
$sourceDir = "./data";
$destDir = "./destinationfolder";
if (!is_dir($sourceDir) || !is_dir($destDir)) {
exit("Directory doesn't exists.");
}
if (!is_writable($destDir)) {
exit("Destination directory isn't writable.");
}
$mostRecentFilePath = "";
$mostRecentFileMTime = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceDir), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mostRecentFileMTime) {
$mostRecentFileMTime = $fileinfo->getMTime();
$mostRecentFilePath = $fileinfo->getPathname();
}
}
}
if ($mostRecentFilePath != "") {
if (!rename($mostRecentFilePath, $destDir . "/file1.xml")) {
exit("Unable to move file.");
}
}
?>
I am working on a project and so I am writing Object Oriented PHP. Hence, I have created a class called FileUploader. This class has all the method to validate file size, and file extension type as well as create directories if not existing.
Everything works just fine but I noticed that it only creates empty directories and does not move the uploaded files. I tried accessing the File error form the stored property but it always gives 0 as the error code
This is the FileUploader class
<?php
namespace Utility\Classes;
class FileUploader
{
//property declarations
protected $error_msg = array();
protected $tmp_file_name;
protected $max_file_size;
protected $target_location;
protected $allowed_file_type = array();
protected $File;
protected $default_file_name = true;
private $backlink_step;
private $unit_size; //to keep track of measurement unit of upload sizes MB|KB|BYTES
function __construct(array $file, array $allowed_ext = [], int $file_max_size = 5)
{
$this->File = $file;
$this->backlink_step = '';
$this->set_allowed_extensions($allowed_ext);
$this->set_max_upload_size($file_max_size);
}
/*This method helps to make sure that files are uploaded to the exact location as desired
*as in the case of deep nesting of subdirectory process
*/
function set_backlink_step($prfx)
{
$this->backlink_step = $prfx;
}
function set_target(string $target, $dated = false)
{
$this->target_location = $target;
if ($dated) {
$this->target_location .= "/" . $date = date("M-Y");
}
}
function get_target()
{
return $this->target_location;
}
//method to set valid/allowed file types
function set_allowed_extensions(array $allowed_ext)
{
$this->allowed_file_type = $allowed_ext;
}
//method to get the allowed file extensions
function get_allowed_extensions()
{
return $this->allowed_file_type;
}
function set_error_msg($err)
{
$this->error_msg[] = $err;
}
function get_error_msg()
{
return $this->error_msg;
}
function set_file_name($name)
{
$this->File['name'] = $name;
}
function get_file_name()
{
return $this->File['name'];
}
function get_tmp_name()
{
return $this->File['tmp_name'];
}
/**
* #description: method to return file size in a specified unit
* #param:String ['TB'|'MB'|'KB'|'B'] default MB
* #return: Int file size
* */
function get_file_size(String $unit = "MB")
{
if (strtolower($unit) === "tb") {
$quadrant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$quadrant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$quadrant = 1024;
} elseif (strtolower($unit) === "b") {
$quadrant = 1;
}
$size = $this->file_size() / $quadrant;
return number_format($size, 2);
}
/**
* #return int size of the file
* */
function file_size()
{
$fsize = $this->File['size'];
return $fsize;
}
/* Method to get the extension name of a file eg: jpg,mp4 */
function get_ext()
{
$extension = explode('.', $this->get_file_name());
return "." . end($extension);
}
function validate($allowed_ext = [])
{
//fall back to the object allowed_file_type property if param not set by user
if (empty($allowed_ext)) {
$allowed_ext = $this->get_allowed_extensions();
}
//validate allowed file type if specified in the array
if (!empty($allowed_ext)) {
if (!$this->is_allowed_extension($allowed_ext)) {
$this->set_error_msg("Type of '{$this->get_file_name()} does not match allowed file types [" . implode('|', $this->get_allowed_extensions()) . "]");
return false;
}
}
//validate file size
if ($this->is_above_max_upload_size()) {
$this->set_error_msg("Size of the file '{$this->get_file_name()}' is larger than max allowed size of {$this->get_max_upload_size()}");
return false;
}
return true;
}
/*Method to upload file
* #return: the uploaded target location
*/
function upload_file()
{
//create necessary directories if not in existence
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
//attempt upload of the file
if (move_uploaded_file($this->tmp_file_name, $target)) {
//update target location with the filename
return $target;
} else {
//return false;
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
/*This method sets the maximum upload size for file track and album_art respectively
*This method ignores invalid value for unit and replaces it with bytes*/
function set_max_upload_size($file_size, $unit = "MB")
{
$mulitplicant = 1;
if (strtolower($unit) === "tb") {
$multiplicant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$multiplicant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$multiplicant = 1024;
} else {
$unit = "Bytes";
}
$this->max_file_size = $multiplicant * $file_size; //set max size for file
$this->unit_size = strtoupper($unit);
}
function get_max_upload_size()
{
return $this->max_file_size;
}
/*Method to compare the size of files to be uploaded with the maximum allowed size*/
function is_above_max_upload_size()
{
$file_unit = $this->unit_size;
//return FALSE if upload size > max size otherwise TRUE
return ($this->file_size() > $this->get_max_upload_size()) ? true : false;
}
/*Method to check if upload file is allowed in by extension name
*The first paramater takes the string of the actual file extension
*The second parameter takes an array of allowed extensions
*/
function is_allowed_extension(array $allowed_ext)
{
return (!in_array($this->get_ext(), $allowed_ext)) ? false : true;
}
//method to create directories
function create_dir()
{
//check if user set a storage location and attempt to create the location
if (empty($this->get_target())) {
$this->set_error_msg('Target Not set.');
return false;
}
//Create the directory
$location = explode('/', $this->get_target());
$prepend = $this->backlink_step . "";
foreach ($location as $key => $value) {
if (!is_dir($prepend . $value)) {
mkdir($prepend . $value);
}
$prepend .= $value . "/";
}
}
}
Then I have another php script where I process the uploaded file by instantiating the FileUploader Class with the $_FILES variable process.php
require_once "../vendor/autoload.php";
use Utility\Classes\FileUploader;
//Instantiate new FileUploader with the files to be uploaded.
$LogoUploader = new FileUploader($_FILES['logo'], ['.png', '.jpg']);
//validate logo size and type - Upload to folder if everything Ok
$logo_validated = $LogoUploader->validate();
//upload files that passed validation
if ($logo_validated) {
$LogoUploader->set_target($location);
$LogoUploader->set_backlink_step('../');
$ltarget = $LogoUploader->upload_file();
if (!$ltarget) {
//upload error
print_error($LogoUploader->get_error_msg());
exit;
} else { //upload success
print "Logo uploaded successfully";
}
} else { //validation error
print_error($LogoUploader->get_error_msg());
exit;
}
Please what am I not doing right?? everything is ok, validation is working, user can set the upload target and if it does not exist, it will be created but it does not upload the file into the created directory or anywhere else in my working directory
I think you need to change the following line
if (move_uploaded_file($this->tmp_file_name, $target)) {
to
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
in the upload_file method. ie:
public function upload_file(){
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
return $target;
} else {
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
I need to check if the excel file is currently open using PHPSpreadsheet.
I thought of a solution by handling this line $writer->save(file_name) into if else condition but still doesn't work.
if($writer->save(file_name){
//file is open
}else{
//file is not open
}
What else can I do to solve my problem?
I need to check if the excel file is currently open using PHPSpreadsheet.
Checking if a file is open isn't really useful, since the open/closed state could change at any time, or the failure could be caused by other filesystem problems.
What you need to do is handle the failure during file operations as:
try {
$writer->save(file_name);
}
catch (Exception $e) {
echo 'Unable to save file. Please close any other applications(s) that are using it: [", $e->getMessage(), "]\n";
}
Answered by #terry-carmen will be Incorrect in following situation:
It will still show "Resource Unavailable" error If file is exists but being used by some application and $writer->save() will try to unlink() the file.
To Overcome this situations I edited the save() function as following:
(Located at: "\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx.php")
public function save($pFilename)
{
if ($this->spreadSheet !== null) {
// garbage collect
$this->spreadSheet->garbageCollect();
// If $pFilename is php://output or php://stdout, make it a temporary file...
$originalFilename = $pFilename;
if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
$pFilename = #tempnam(File::sysGetTempDir(), 'phpxltmp');
if ($pFilename == '') {
$pFilename = $originalFilename;
}
}
$saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// Create string lookup table
$this->stringTable = [];
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
}
// Create styles dictionaries
$this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet));
$this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet));
$this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet));
$this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet));
$this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet));
$this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet));
// Create drawing dictionary
$this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet));
$zip = new ZipArchive();
if (file_exists($pFilename)) {
// Added by muhammad.begawala#gmail.com
// '#' will stop displaying "Resource Unavailable" error because of file is open some where.
// 'unlink($pFilename) !== true' will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if (#unlink($pFilename) !== true) {
throw new WriterException('Could not delete file: ' . $pFilename . ' Please close all applications that are using it.');
}
}
// Try opening the ZIP file
if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) {
if ($zip->open($pFilename, ZipArchive::CREATE) !== true) {
throw new WriterException('Could not open ' . $pFilename . ' for writing.');
}
}
// Add [Content_Types].xml to ZIP file
$zip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts));
//if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
if ($this->spreadSheet->hasMacros()) {
$macrosCode = $this->spreadSheet->getMacrosCode();
if ($macrosCode !== null) {
// we have the code ?
$zip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin
if ($this->spreadSheet->hasMacrosCertificate()) {
//signed macros ?
// Yes : add the certificate file and the related rels file
$zip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate());
$zip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet));
}
}
}
//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
if ($this->spreadSheet->hasRibbon()) {
$tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
$zip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data'));
if ($this->spreadSheet->hasRibbonBinObjects()) {
$tmpRootPath = dirname($tmpRibbonTarget) . '/';
$ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
foreach ($ribbonBinObjects as $aPath => $aContent) {
$zip->addFromString($tmpRootPath . $aPath, $aContent);
}
//the rels for files
$zip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet));
}
}
// Add relationships to ZIP file
$zip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet));
$zip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet));
// Add document properties to ZIP file
$zip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet));
$zip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet));
$customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet);
if ($customPropertiesPart !== null) {
$zip->addFromString('docProps/custom.xml', $customPropertiesPart);
}
// Add theme to ZIP file
$zip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet));
// Add string table to ZIP file
$zip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable));
// Add styles to ZIP file
$zip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet));
// Add workbook to ZIP file
$zip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas));
$chartCount = 0;
// Add worksheets
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$zip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts));
if ($this->includeCharts) {
$charts = $this->spreadSheet->getSheet($i)->getChartCollection();
if (count($charts) > 0) {
foreach ($charts as $chart) {
$zip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas));
++$chartCount;
}
}
}
}
$chartRef1 = 0;
// Add worksheet relationships (drawings, ...)
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
// Add relationships
$zip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts));
// Add unparsedLoadedData
$sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
$unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) {
$zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
}
}
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) {
$zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
}
}
$drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
$drawingCount = count($drawings);
if ($this->includeCharts) {
$chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
}
// Add drawing and image relationship parts
if (($drawingCount > 0) || ($chartCount > 0)) {
// Drawing relationships
$zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
// Drawings
$zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
} elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) {
// Drawings
$zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
}
// Add comment relationship parts
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
// VML Comments
$zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
// Comments
$zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
}
// Add unparsed relationship parts
if (isset($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'])) {
foreach ($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'] as $vmlDrawing) {
$zip->addFromString($vmlDrawing['filePath'], $vmlDrawing['content']);
}
}
// Add header/footer relationship parts
if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
// VML Drawings
$zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
// VML Drawing relationships
$zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
// Media
foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
$zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
}
}
}
// Add media
for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
$imageContents = null;
$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
if (strpos($imagePath, 'zip://') !== false) {
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
$imageZip->close();
unset($imageZip);
} else {
$imageContents = file_get_contents($imagePath);
}
$zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
} elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
ob_start();
call_user_func(
$this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
$this->getDrawingHashTable()->getByIndex($i)->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
}
}
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
// Close file
if ( #$zip->close() === false ) { // updated by muhammad.begawala#gmail.com
throw new WriterException("Could not close zip file $pFilename.");
}
// If a temporary file was used, copy it to the correct file stream
if ($originalFilename != $pFilename) {
if (copy($pFilename, $originalFilename) === false) {
throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename.");
}
#unlink($pFilename);
}
return true;
// Return True to make sure that file is created successfully with no ExceptionsAdded by muhammad.begawala#gmail.com
} else {
throw new WriterException('PhpSpreadsheet object unassigned.');
}
}
Major Changes:
1) Handling "Resource Unavailable" error by unlink() as Exception using try catch so that It doesn't show error when file is being used by some applications when we tries to delete it using unlink.
if (file_exists($pFilename)) {
// Added by muhammad.begawala#gmail.com
// '#' will stop displaying "Resource Unavailable" error because of file is open some where.
// 'unlink($pFilename) !== true' will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if (#unlink($pFilename) !== true) {
throw new WriterException('Could not delete file: ' . $pFilename . ' Please close all applications that are using it.');
}
}
2) $writer->save('hello world.xlsx') will return TRUE if file is successfully created else throw Exception.
Usage:
try {
$writer->save('hello world.xlsx');
echo 'File Created';
}
catch (Exception $e) {
echo $e->getMessage(); // Will print Exception thrown by save()
}
I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!
This is my Controller
Image Controller:
class Admin_xxxxController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->layout()->setLayout('admin');
if ($this->_helper->FlashMessenger->hasMessages()) {
$messages = $this->_helper->FlashMessenger->getMessages();
$this->view->messages = $messages[0];
}
}
public function preDispatch()
{
if(!Zend_Auth::getInstance()->hasIdentity()) {
if ('login' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index','login');
} else {
}
}
parent::preDispatch();
}
public function saveAction()
{
try {
if(isset($_POST['submit'])) {
$i=0;
$lmgdata=array();
foreach($_FILES as $k=>$v){
$post=$this->_request->getPost();
$path = "images/landimages";
$thumb="images/landimages/thumbnails";
if(!is_dir($path)){ // to check is folder exist or not
mkdir($path,'0777',true);
}
if(!is_dir($thumb)){ // to check is folder exist or not
mkdir($thumb,'0777',true);
}
$maxWidth="600"; $maxHeidht="500";$thumbwidth="100";$thumbheidht="75";
list($width,$height,$y) = getimagesize($v['tmp_name'][$i]);
$scale = min($maxWidth/$width, $maxHeidht/$height);
$scale1 = min($thumbwidth/$width, $thumbheidht/$height);
$s1=$v['name'][$i]; $destpath = $path.'/'.$s1; $thumbpath = $thumb.'/'.$s1;
if(move_uploaded_file($v['tmp_name'][$i],$destpath)){
//$this->resize($thumbpath, $destpath,$width, $height,$scale1,1);
$this->resize($destpath, $destpath,$width, $height,$scale,0 );
$lmgdata[$i]['lm_image']=$s1; // to save new image name in db
}else{
echo "not uploaded"; die();
}
$i++;
}
}
$post=$this->_request->getPost();
$data=array();
if($post['land_id'])
$data['land_id']=$post['land_id'];
$mapper= new Application_Model_xxxMapper();
$lmmapper= new Application_Model_yyyMapper();
if($lid = $mapper->save($data)){
$lmmapper->save($lmgdata, $lid);
$this->_helper->FlashMessenger(array('success'=>'xxx added Sucessfully'));
}else{
$this->_helper->FlashMessenger(array('failed'=>'xxx not added ,please try again'));
}
$this->_helper->redirector('index','xxxx','admin');
}
catch(Zend_Db_Exception $e)
{
echo $e->getMessage();
}
}
This is my add form where I upload multiple images
Add form:
<form action="<?php echo $this->url(array('controller'=>'lands','action'=>'save'),'admin',true);?>" method="post" enctype="multipart/form-data">
Upload Images:<input type="file" multiple name="land_image[]" id="land_image" class="form-control" autocomplete="off" title="">
I used for loop in controller to save multiple images and When I tried to upload multiple images and submit in add form. Only 1 image is getting save and that too only the thumnail is saved. How to get all the images saved
Your loop should look as follows:
foreach($_FILES['land_image']['tmp_name'] as $key => $tmp_name) {
$fileName = $_FILES['land_image']['name'][$key];
$fileSize = $_FILES['land_image']['size'][$key];
$fileTmp = $_FILES['land_image']['tmp_name'][$key];
$fileType = $_FILES['land_image']['type'][$key];
...
}
The answer is not relevant to the question asked. I will answer to my question:
public function saveAction($lmgdata)
{
try{
if(isset($_POST['submit']))
{ $i = 0;
foreach($_FILES as $k=>$v){
// to test is form submited or not
$post=$this->_request->getPost(); // get post result
$data=array(); // create an array to stroe posted details
$data['land_id']=$_SESSION['lid'];
//$data['lm_order']=$post['lm_order'];
/* below code for create a directory */
$path = "/propladder/public/images/landimages";
$thumb="/propladder/public/images/landimages/thumbnails";
if(!is_dir($path)){ // to check is folder exist or not
mkdir($path,'0755',true);
}
if(!is_dir($thumb)){ // to check is folder exist or not
mkdir($thumb,'0755',true);
}
/* below code for uploading in property image */
$maxWidth="600";
$maxHeidht="500";
list($width,$height,$y) = getimagesize($v['tmp_name'][$i]);
$scale = min($maxWidth/$width, $maxHeidht/$height);
$thumbwidth="100";
$thumbheidht="75";
$scale1 = min($thumbwidth/$width, $thumbheidht/$height);
$s1=$v['name'][$i];
$destpath = $path.'/'.$s1; // this is image fulll path
$thumbpath = $thumb.'/'.$s1; // this is image fulll path
if(move_uploaded_file($v['tmp_name'][$i],$destpath)){ // to upload image to destination
$this->resize($thumbpath, $destpath,$width, $height,$scale1,1);
$this->resize($destpath, $destpath,$width, $height,$scale,0 );
$data['lm_image']=$s1; // to save new image name in db
}else{
echo "not uploaded"; die();
}
$mapper=new Application_Model_xxxxMapper();
if($mapper->save($data)){
$this->_helper->FlashMessenger(array('success'=>'xxxx added sucessfully'));
}else{
$this->_helper->FlashMessenger(array('failed'=>'xxxx not added ,Try again'));
}
$i++;
}
} // end is post
//$this->_helper->redirector('index','xxxx','admin');
}catch(Zend_Db_Exception $e){
echo $e->getMessage();
}
}