Below is the code that throws some errors while getting executed. What I'm trying to do is the last line of the code gets executed no matter what (Error or no Error).
<?php
require 'main.php';
function create_photo($file_path) {
# Upload the received image file to Cloudinary
#$result = \Cloudinary\Uploader::upload($file_path, array(
"tags" => "backend_photo_album",
));
#unlink($file_path);
error_log("Upload result: " . \PhotoAlbum\ret_var_dump($result));
$photo = \PhotoAlbum\create_photo_model($result);
return $result;
}
$files = $_FILES["files"];
$files = is_array($files) ? $files : array($files);
$files_data = array();
foreach ($files["tmp_name"] as $index => $value) {
array_push($files_data, create_photo($value));
}
?>
<script>window.location.replace('index.html')</script>
Any help would be much appreciated. Thanks
I think depending on your php version, you can use a "try/catch/finally" bloc like that:
try
{
// code that may throw an exception
}
catch(Exeption $e) // The exception you want to catch
{
// Exception treatment
}
finally
{
// Executed no matter what
}
Maybe take a look about how to use that.
Related
I am fetching results from database and then creating excel sheet from it.
This stores the file in storage path.
public function downloadResults(array $filterArr) {
unset($queryArr);
$start = 0;
$limit = 10000;
$response = $this->getFilterResults($filterArr, true, $start, $limit);
$resultHits = $response['resultHits'];
# if results are empty, throw an exception
if($resultHits->isEmpty())
throw new \Exception("No results found for given filter.", 1);
# otherwise continue with the download process...
$exportArr = [];
foreach($resultHits as $key=>$value) {
$list = (array) $value;
array_push($exportArr, $list);
}
$type = 'xls';
$export = Excel::create('result_set_download_'.time(), function($excel) use ($exportArr) {
$excel->sheet('mysheet', function($sheet) use ($exportArr) {
$sheet->fromArray($exportArr);
});
})->store($type, storage_path('app/public/exports'), true);
return $export;
}
If export and store is successful, then stored filename is sent back to browser, else error message is sent.
try {
$exportArr = $this->product->downloadResults($filterArr);
$status = true;
$jsonArr['filename'] = $exportArr['file'];
} catch (\Exception $e) {
$status = false;
$jsonArr['message'] = $e->getMessage();
} finally {
$jsonArr['success'] = $status;
echo json_encode($jsonArr);
}
This is working fine until now, but in case of few exports I get this error:
mysheet!Z2898 -> Formula Error: Unexpected ,
There's not any calculation done while exporting.
I also found a similar post here
Laravel Excel Formula Error: Unexpected operator '='
And this is the answer to that post:
// Enable calculation
$reader->calculate();
// Disable calculation
$reader->calculate(false);
But I am confused as to where to put this.
If you want to enable any formula, first export your laravel-excel config
php artisan vendor:publish
Search Maatwebsite then publish it. In my case is 12. Type 12 then Enter.
That will copy a config file to your config folder.
Then from config/excel.php change this line:
excel.php
'pre_calculate_formulas' => true, // default is false
What I want to do is a small web page that a user can upload a SQLite file, but I want to avoid those uploads that aren't SQLite format, so I try to verify it before I execute "move_uploaded_file". Above there's an example of what I've tried to do, but it doesn't work.
function isFileOkay($filedir) {
try
{
$db = new PDO("sqlite:".$filedir);
$sql = "PRAGMA schema_version;";
$ret = $db->query($sql);
if(!$ret)
{
$db = NULL;
return -1;
}
$row = $ret->fetchAll(PDO::FETCH_BOTH);
$value = (int) $row[0]['schema_version'];
$db = NULL;
return $value;
}
catch (PDOException $exception) {
echo $exception->getMessage();
return -1;
}
}
...
$test = isFileOkay($_FILES['upload_file']['tmp_name']);
...
The $test variable should be "-1" if the file isn't a SQLite file, or $value. $value = 0 also indicates that the file is not okay, but any value greater than 0 indicates that it is a valid SQLite file.
The point is that when I test this code manually inserting a path for $filedir, e.g a file already existing in this machine, the output is correct. But when I try to verify "$_FILES['upload_file']['tmp_name']" it doesn't work, and the page crashes.
I am new at web programming, especially in PHP, so I think there might be a misunderstanding about the $_FILE variable.
You should be able to check the mime type of the uploaded file:
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['upload_file']['tmp_name']);
// SQLite is application/x-sqlite3
if ($mime == 'application/x-sqlite3') {
// Is SQLite
} else {
// Is something else
}
I am trying to use Imagine to batch make 250x250 thumbnail of more than 90k+ relatively small mobile images. The problem is, when I run a loop,
foreach ($images as $c) {
$imagine = new Imagine();
$image = $imagine->open($c);
$image->resize(new Box(250, 250))->save($outFolder);
}
sometimes, the image is corrupted and the open() method fails, throwing exception:
Unable to open image
vendor/imagine/imagine/lib/Imagine/Gd/Imagine.php
Line: 96
and completely breaks the loop. Is there a way, to check if open failed? something like:
foreach ($images as $c) {
$imagine = new Imagine();
$image = $imagine->open($c);
if ($image) {
$image->resize(new Box(250, 250))->save($outFolder);
} else {
echo 'corrupted: <br />';
}
}
Hope somebody can help. or if its not possible, can you suggest a PHP image library that I can pragmatically resize by batch?
Thank you
For handling the exception just use try-catch.
From the library documentation
The ImagineInterface::open() method may throw one of the following exceptions:
Imagine\Exception\InvalidArgumentException
Imagine\Exception\RuntimeException
Try it like this:
$imagine = new Imagine(); // Probably no need to instantiate it in every loop
foreach ($images as $c) {
try {
$image = $imagine->open($c);
} catch (\Exception $e) {
echo 'corrupted: <br />';
continue;
}
$image->resize(new Box(250, 250))->save($outFolder);
}
I need to do a list of all files on a server from an other server.
I don't have access to PHP config like maximum timeout of the remote server.
The maximum timeout could be very short like 30s. In some case, the following code gives a Timeout issue, because the iterator don't have enough time to get all the files.
public function getStructure($path)
{
$structure = new \stdClass();
$structure->dirs = array();
$structure->files = array();
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file)
{
if ($file->isDir())
{
$structure->dirs[] = $file->getRealpath();
}
else
{
$structure->files[] = $file->getRealpath();
}
}
return $structure;
}
I'm looking for a way to get the structure in multiple calls. Something like : myremotesite.com/api/v1/structrue?start=xxxx where start is the point where the last call stop.
Thanks for your help
sounds like you need a dir with save/resume functionality... i would probably implement it in SQLite, due to its synchronous-by-default nature.
since i was bored.. UNTESTED, but should work in theory. DO NOT try to implement beginTransaction() / commit() optimizations to this code, that would defeat the whole "synchronous and tolerates crashing at any moment" part of the code;
<?php
//will return bool(true) when it's finished creating the database.
//should be timeout/unstable system resistant,
//relying on SQLite's syncronous-by-default nature.
function dirToSQLite($dir,$sqldb){
if(!is_readable($dir)){
throw new InvalidArgumentException('argument 1 must be a readable dir, but is not readable.');
}
if(!is_dir($dir)){
throw new InvalidArgumentException('argument 1 is not a valid dir');
}
$db=new PDO('sqlite:'.$sqldb,'','',array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->exec('CREATE TABLE IF NOT EXISTS `dir` (`id` INTEGER PRIMARY KEY,`path` TEXT UNIQUE,`type` TEXT);');
$db->query('INSERT OR IGNORE INTO `dir` (`path`,`type`) VALUES('.$db->quote($dir).',\'dirUnexplored\');');
$stm=$db->prepare('INSERT INTO `dir` (`path`,`type`) VALUES(:path,:type);');
$stmExplored=$db->prepare('UPDATE `dir` SET `type` = \'dir\' WHERE id = ? ');
$path='';
$type='';
$stm->bindParam(':path',$path,PDO::PARAM_STR);
$stm->bindParam(':type',$type,PDO::PARAM_STR);
while(true){
$found=false;
foreach($db->query('SELECT `id`,`path` FROM `dir` WHERE `type` = \'dirUnexplored\'') as $res)
{
$found=true;
$di=new DirectoryIterator($res['path']);
foreach($di as $file){
if($file->isDot()){
continue;
} else
if($file->isLink()){
$type='link';
} else
if($file->isDir()){
$type='dirUnexplored';
} else
if($file->isFile()){
$type='file';
} else
{
$type='unknown';
}
$path=$file->getPathname();
$stm->execute();
}
$stmExplored->execute(array($res['id']));
}
if(!$found){
break;
}
}
return true;
}
if(true===dirToSqlite('/home/foo','homefoo.db3')){
echo "finished!";
}else {
throw new Exception();
}
then just keep calling that url until it returns the string "finished!", then you can download the SQLite database directly, no php involved in the download.
I'm using the Apache Chemistry CMIS PHP client to upload documents from a local folder to Alfresco Community Edition 5.1 via ATOM. Here's the script I'm using to do so:
require_once ('cmis_repository_wrapper.php');
require_once ('cmis_service.php');
$repo_url = "http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom";
$repo_username = "user";
$repo_password = "pass";
$client = new CMISService($repo_url, $repo_username, $repo_password);
$repo_folder = "/alfrescoFolder";
$source_folder = "localFolder/";
$source_files = array_diff(scandir("$source_folder", 1), array('..', '.'));
$myfolder = $client->getObjectByPath($repo_folder);
foreach($source_files as $file)
{
try
{
$upload = $client->createDocumentFromSource($myfolder->id, $file, "$source_folder/$file");
}
catch(Exception $e)
{
echo "Some error here.";
}
}
This script works fine and documents are uploaded without problem, provided that the document doesn't already exist in the Alfresco repository. For example, let's say I have a document in my Alfresco repository named example.txt, and so, if I try to upload a document from my local folder with the same name, I get a CMIS constraint exception. I dont't know how I can upload a new version of an existing document.
This is what I've tried so far, but it doesn't work:
$objs = $client->getChildren($myfolder->id);
foreach($source_files as $file)
{
foreach($objs->objectList as $obj)
{
if($obj->properties['cmis:name'] == $file)
{
try
{
$checkedout = $client->checkOut($obj->id);
$client->checkIn($checkedout->id);
}
catch(Exception $e)
{
echo "Some error here.";
}
}
else
{
try
{
$upload = $client->createDocumentFromSource($myfolder->id, $file, "$source_folder/$file", array('cmis:objectTypeId'=>'D:ex:document'));
}
catch(Exception $e)
{
echo "Some error here";
}
}
}
}
I get this error:
DEBUG: postEntry: myURL = http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom/checkedoutDEBUG: postEntry: entry_template = {title} {SUMMARY} {CONTENT} {PROPERTIES} DEBUG: postEntry: properties_xml = b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0 DEBUG: postEntry: hash_values = Array ( [PROPERTIES] => b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0 [SUMMARY] => {summary} ) DEBUG: postEntry: post_value = b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0
What's funny is that the document is in fact locked for editing, so I don't really know what's going on. I also don't know if checking out and then checking in a document is how I'm supposed to version a document.
TL;DR
I want to be able to specify that the document I'm uploading is a new version of an existing document. Does anyone know how I can do that?
The function coverage page on the Apache Chemistry web site lists what the CMIS PHP client can and cannot do. Check out, check in, and cancel checkout are all unsupported at the present time. I know they would welcome contributions.
The underlying CMIS specification supports it, of course, so you can either update the library to support checkout/checkin or use the raw binding.
I'm not an expert on CMIS, but I think that this forum post answers the question. See the answer from "jevon" that provides an example and a link to this page (see the "Updating a document" section)
I've recently found out about an alternative CMIS PHP library that implements versioning services, including example usage. I've used it to successfully solve the problem I posted in my question.
Edit: additional information added.
So, to get versioning working, I used the example code provided in the library. The script I used can be used to create new documents and to update and version existing documents. So, here it is:
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
if (!is_file(__DIR__ . '/conf/Configuration.php')) {
die("Please add your connection credentials to the file \"" . __DIR__ . "/conf/Configuration.php\".\n");
} else {
require_once(__DIR__ . '/conf/Configuration.php');
}
$major = (boolean) isset($argv[1]) ? $argv[1] : false;
$httpInvoker = new \GuzzleHttp\Client(
array(
'defaults' => array(
'auth' => array(
CMIS_BROWSER_USER,
CMIS_BROWSER_PASSWORD
)
)
)
);
$parameters = array(
\Dkd\PhpCmis\SessionParameter::BINDING_TYPE => \Dkd\PhpCmis\Enum\BindingType::BROWSER,
\Dkd\PhpCmis\SessionParameter::BROWSER_URL => CMIS_BROWSER_URL,
\Dkd\PhpCmis\SessionParameter::BROWSER_SUCCINCT => false,
\Dkd\PhpCmis\SessionParameter::HTTP_INVOKER_OBJECT => $httpInvoker,
);
$sessionFactory = new \Dkd\PhpCmis\SessionFactory();
// If no repository id is defined use the first repository
if (CMIS_REPOSITORY_ID === null) {
$repositories = $sessionFactory->getRepositories($parameters);
$repositoryId = $repositories[0]->getId();
} else {
$repositoryId = CMIS_REPOSITORY_ID;
}
$parameters[\Dkd\PhpCmis\SessionParameter::REPOSITORY_ID] = $repositoryId;
$session = $sessionFactory->createSession($parameters);
$rootFolder = $session->getObject($session->createObjectId($session->getRootFolder()->getId()));
try {
$document = null;
$stream = \GuzzleHttp\Stream\Stream::factory(fopen($filePath, 'r'));
foreach ($rootFolder->getChildren() as $child) {
if ($child->getName() === $fileName) {
$document = $child;
break;
}
}
if (!$document) {
$properties = array(
\Dkd\PhpCmis\PropertyIds::OBJECT_TYPE_ID => 'cmis:document',
\Dkd\PhpCmis\PropertyIds::NAME => $fileName
);
$document = $session->createDocument($properties, $rootFolder, $stream);
$document = $session->getObject($document);
}
$checkedOutDocumentId = $document->getVersionSeriesCheckedOutId();
if ($checkedOutDocumentId) {
$checkedOutDocumentId = $session->createObjectId($checkedOutDocumentId);
} else {
$checkedOutDocumentId = $document->checkOut();
}
$checkedInDocumentId = $session->getObject($checkedOutDocumentId)->checkIn(
$major,
array(
\Dkd\PhpCmis\PropertyIds::DESCRIPTION => 'New description'
),
$stream,
'Comments'
);
} catch (\Dkd\PhpCmis\Exception\CmisVersioningException $e) {
echo "********* ERROR **********\n";
echo $e->getMessage() . "\n";
echo "**************************\n";
exit();
}