There is a piece of code which keeps throwing this error:
RuntimeException: SplFileObject::__construct(86a03f5ac14227ae4e596750c3a90db1612f77ce1b00e4aa6cbd4b2dc5e69835.icturee.jpg): failed to open stream: No such file or directory in /home/site/vendor/tray-labs/oracle-storage/src/Object/File.php:42 Stack trace: #0 /home/site/vendor/tray-labs/oracle-storage/src/Object/File.php(42): SplFileObject->__construct('86a03f5ac14227a...') #1 /home/site/vendor/tray-labs/oracle-storage/src/Service/UploadService.php(25): TrayLabs\OracleStorage\Object\File->getFile() #2 /home/site/vendor/tray-labs/oracle-storage/src/OracleStorage.php(64): TrayLabs\OracleStorage\Service\UploadService->handle('86a03f5ac14227a...', Object(TrayLabs\OracleStorage\Object\File)) #3 /home/site/includes/storageProcessor.php(15): TrayLabs\OracleStorage\OracleStorage->upload('86a03f5ac14227a...', Object(TrayLabs\OracleStorage\Object\File)) #4 /home/site/wwwroot/chumba.html(470): storeFile(Object(TrayLabs\OracleStorage\OracleStorage), '86a03f5ac14227a...', '86a03f5ac14227a...') #5 {main}
I have tried my best to follow the integration document of the traylabs\oracle-storage package like:
Add this line in composer.json file in the web app project's root folder
require traylabs/oracle-storage
Execute this command to install the package in the vendors directory
php composer.phar update
Create the configuration file conf.php
return [ 'user'=>[
'username'=>'example#gmail.com',
'password'=>'#password'
], 'account'=>[
'identifier'=>'bucket',
'auth_url'=>'https://oraclecloud.com/object-storage/buckets/f4yay/items'
], 'storage'=>[
'container'=>'items',
'local_path'=>'/home/site/wwwroot/destination/',
'cache'=>true
] ];
creating the processing.php file for encapsulating the file upload to cloud functionality as shown:
<?php
use \TrayLabs\OracleStorage\OracleStorage;
use \TrayLabs\OracleStorage\Object\File;
use \TrayLabs\OracleStorage\ExceptionFileNotFound;
require_once("../vendor/autoload.php");
function getClient() {
$client=new OracleStorage(require '/home/site/includes/Conf.php');
return $client;
}
//utility
function storeFile($client,$filename) {
$calledname=$client->upload("$filename", new File($filename));
return $calledname;
}
?>
include the processing.php file via require_once() function in several products.html files from which image files i.e jpeg/ping etc will be uploaded to the web app server and later to the oracle cloud object storage as shown here under:
<?php
use \TrayLabs\OracleStorage\OracleStorage;
use \TrayLabs\OracleStorage\Object\File;
use \TrayLabs\OracleStorage\ExceptionFileNotFound;
require_once('./../includes/processing.php');
require_once("./../vendor/autoload.php");
if ($_SERVER["REQUEST_METHOD"]=="POST")
{
if ($_FILES['picha']['error'] == UPLOAD_ERR_OK)
{
$tmpName = $_FILES['picha']['tmp_name'];
$name = basename($_FILES['picha']['name']);
$ext = strtolower(substr($name, strripos($tmpName, '.')+1));
$filename = hash_file('sha256', $tmpName) . '.' . $ext;
$destination=__DIR__."/warehouse/$filename";
$message=move_uploaded_file($tmpName,$destination);
$filepath=$destination;
$contents=fopen($filepath,'r');//getfilecontents($filepath);
try
{
$client=new getClient();
$itemname=storeFile($client,$filename);
}
catch(Exception $ex)
{
$ex->getMessage();
echo $ex;
}
unlink($destination);
//some more code goes here
}
}
?>
For brevity I have removed some code such as html form elements and other associated data element for particular product
I have got the solution. I remembered something that I should put on the checklist. I simply went to the kudu console for my app which is hosted in azure app service and changed the owner of folder where I kept the multimedia files to www-data and soon after that retest my app it is running smoothly as it supposed to do.
Related
Is there a way to zip and download files and folders which are in Amazon S3 bucket, together in Laravel? I Want to zip the three folders and one file in the picture together and download it
Here's a half baked solution in a route file. Hope it helps.
https://flysystem.thephpleague.com/docs/adapter/zip-archive/
composer require league/flysystem-ziparchive
I put this in routes/web.php just to play with.
<?php
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Filesystem;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
Route::get('zip', function(){
// see laravel's config/filesystem.php for the source disk
$source_disk = 's3';
$source_path = '';
$file_names = Storage::disk($source_disk)->files($source_path);
$zip = new Filesystem(new ZipArchiveAdapter(public_path('archive.zip')));
foreach($file_names as $file_name){
$file_content = Storage::disk($source_disk)->get($file_name);
$zip->put($file_name, $file_content);
}
$zip->getAdapter()->getArchive()->close();
return redirect('archive.zip');
});
You'll definitely want to do something different than just plopping it in the public dir. Maybe stream it out straight out as a download or save it somewhere better. Feel free to post comment/questions and we can discuss.
I did it the following way after looking at some solutions by streaming the zip directly to the client by using https://github.com/maennchen/ZipStream-PHP :
if ($uploads) {
return response()->streamDownload(function() use ($uploads) {
$opt = new ArchiveOptions();
$opt->setContentType('application/octet-stream');
$zip = new ZipStream("uploads.zip", $opt);
foreach ($uploads as $upload) {
try {
$file = Storage::readStream($upload->path);
$zip->addFileFromStream($upload->filename, $file);
}
catch (Exception $e) {
\Log::error("unable to read the file at storage path: $upload->path and output to zip stream. Exception is " . $e->getMessage());
}
}
$zip->finish();
}, 'uploads.zip');
}
I have a simple open (file) method which should throw an exception if it fails to open or create a file in the given path:
const ERR_MSG_OPEN_FILE = 'Failed to open or create file at %s';
public function open($filePath)
{
ini_set('auto_detect_line_endings', TRUE);
if (false !== ($this->handler = #fopen($filePath, 'c+'))) {
return true;
} else {
throw new \Exception(
sprintf(self::ERR_MSG_OPEN_FILE, $filePath)
);
}
}
There is unit-test around it using PHPUnit and VFSStream:
$structure = [
'sample.csv' => file_get_contents(__DIR__ . '/../sampleFiles/small.csv')
];
$this->root = vfsStream::setup('exampleDir', null, $structure);
$existingFilePath = vfsStream::url('exampleDir') . DIRECTORY_SEPARATOR . 'sample.csv';
$this->file = new File();
$this->file->open($existingFilePath);
The above setup creates a virtual directory structor containing a mock file (read/cloned from an existing CSV file) and this satisfy the open method's requirement to open a file. And also if I pass a different path (none existing file) it will be created in the same virtual structor.
Now in order to cover the exception I want to add a ready-only directory to the existing structor, lets say a folder belong to another user and I don't have write permission on it, like this when I try to open a non existing file in that folder, attempt to creating one should fail and the open method should throw the exception.
The only problem is,.... I don't know how to do it :D
Any Advice, hint and guidance will be appreciated :)
You could simply point your mock directory's url to an incorrect path.
$existingFilePath = vfsStream::url('badExampleDir') . DIRECTORY_SEPARATOR . 'incorrect.csv';
considering the badExampleDir never been setup your method will fail to create the file in it.
I am trying to install a Magento package, but I get No file was uploaded
Its coming from this code because $_FILES is an empty array in /downloader/Maged/Controller.php
/**
* Install uploaded package
*/
public function connectInstallPackageUploadAction()
{
if (!$_FILES) {
echo "No file was uploaded";
return;
}
if(empty($_FILES['file'])) {
echo "No file was uploaded";
return;
}
$info =& $_FILES['file'];
if(0 !== intval($info['error'])) {
echo "File upload problem";
return;
}
$target = $this->_mageDir . DS . "var/" . uniqid() . $info['name'];
$res = move_uploaded_file($info['tmp_name'], $target);
if(false === $res) {
echo "Error moving uploaded file";
return;
}
$this->model('connect', true)->installUploadedPackage($target);
#unlink($target);
}
It might be worth noting that product uploads work fine.
The only log output I get is
2014-07-03T18:44:15+00:00 ERR (3): Warning: array_key_exists() expects parameter 2 to be array, null given in /var/www/vhosts/example.com/httpdocs/app/code/core/Mage/Captcha/Model/Observer.php on line 166
exception.log was empty
Make sure that your var folder in magento installation is fully writable. 777 permission. All folders and files.
You can try uploading a small dummy file first to check if the error stays the same.
There is a file upload limit which might be reached.
File upload often fails due to upload_max_filesize or post_max_size being too small as mentioned in Common Pitfalls section of the PHP documentation.
Use firebug in firefox to check if your form does has enctype="multipart/form-data".
Check the user group it was created with,
To explain, recently I had some file saving issues. Turned out I had created the folder using the Root user for the server, and the CPanel user ( the one php was running under ) didn't have permission to write in folders owned by the Root account, even when setting the permissions to 777.
Just a thought.
First check if your installation is configured properly
see#http://php.net/manual/en/features.file-upload.common-pitfalls.php
Also, if you upload with PUT/xhr the file is on the input stream
$in = fopen('php://input','r');
see#http://php.net/manual/en/features.file-upload.put-method.php and https://stackoverflow.com/a/11771857/2645347,
this would explain the empty $FILES array, in case all else is ok and the upload works via xhr/PUT.
$_FILES is an associative array of items uploaded to the current script via the HTTP POST method. All uploaded files are stored in $HTTP_POST_FILES contains the same initial information, but is not a superglobal. So, ... be sure that method is POST
Always check that your form contains correct enctype:
<form ... enctype="multipart/form-data"> ... </form>
Sometimes happens that when someone upload multiples file, $_FILES return empty. This could happen when I select files that exceed some size. The problem can be in the POST_MAX_SIZE configuration.
On
app/code/core/mage/captcha/model/observer.php
change
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$loginParams = Mage::app()->getRequest()->getPost('login');
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
to
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$login = Mage::app()->getRequest()->getPost('username');
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
Your issue is:
"Captcha Observer throws an error if login in RSS feed" issue #208
or if you wish you could only replace the variable $login to be like this:
$login = array_key_exists('username', array($loginParams)) ? $loginParams['username'] : null;
You may try out below points.
Use Magento Varien File Uploaded Classes to Upload the files.
Magento File Uploader
1) Check enctype="multipart/form-data" in your form.
2) Use Magento Form Key in your form.
3) Use Varien file uploader to upload your files using below links answers.
I wanna give all my website authors a possiblity to post their articles on our facebook page without having go give them admin access to it.
So i created a simple form, where the author types in: URL, URL to image, message
On submit, this form will send a ajax request to facebook.php where the magic "should" happen.
The first problem occurs at "require_once".
It's not possible to require all 4 files without having an error.
If i get rid of the facebook exception, then everything works except the request itself.
There seems to be an PHP Error, because i get no ajax response at all.
session_start();
require_once($_SERVER['DOCUMENT_ROOT'].'/sys/facebook/FacebookSession.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/sys/facebook/FacebookRequest.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/sys/facebook/GraphObject.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/sys/facebook/FacebookRequestException.php');
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphObject;
use Facebook\FacebookRequestException;
$message = safe($_POST["message"]);
$url = safe($_POST["url"]);
$image = safe($_POST["image"]);
if($message == "" OR $url == "" OR $image == ""){
echo "incomplete";
return;
}
FacebookSession::setDefaultApplication('{APP ID}','{APP SECRET}');
$session = new FacebookSession('{Page Access Token}');
if($session) {
try {
$response = (new FacebookRequest(
$session, 'POST', '/{Page ID}/feed', array(
'message' => $message,
'link' => $url,
'picture' => $image
)
))->execute()->getGraphObject();
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
} else {
echo "No Session available!";
}
Update: June, 27 2014, The SDK now comes with a built-in autoloader for those who can't use composer.
require __DIR__ . '/path/to/facebook-php-sdk-v4/autoload.php';
If that doesn't automatically find the path for you, you can define it with FACEBOOK_SDK_V4_SRC_DIR.
define('FACEBOOK_SDK_V4_SRC_DIR', '/path/to/facebook-php-sdk-v4/src/Facebook/');
require __DIR__ . '/path/to/facebook-php-sdk-v4/autoload.php';
The internals of the SDK rely on several other classes that you're not including. That's why autoloading is really important here.
Autoloading With Composer
The best way to do this is to install composer. And add the SDK in a composer.json file to the root of your project.
{
"require" : {
"facebook/php-sdk-v4" : "4.0.*"
}
}
Then run composer install from the command line where the composer.json file is. Then include the autoloader at the top of your script.
require_once __DIR__ . '/vendor/autoload.php';
Manual Autoloading
An alternative way to autoload these files is to replace your require_once's at the top with this solution from rm-vanda:
function facebookLoader($class) {
require "/path/to/facebook-php-sdk-v4-master/src/" . str_replace("\\", "/", $class) . ".php";
}
spl_autoload_register("facebookLoader");
Here I got my solution fixing on updating the Facebook Graph SDK, I do apologize for the short answer.
I updated, php.ini file and enabled, the fileinfo extension by uncommenting
;extension=fileinfo
Removing the ; tag to
extension=fileinfo
Then do the command,
composer update
Credits: StackOverflow, Bing, and Google search.
Warning: I'm using, Laravel, Wnmp as a local webserver.
Note: This comment may require revisions.
Hi i try to add mobile template into current zend application but it return server error.
Following are my configuration as i follow on several sites.
application.in
resources.frontController.plugins[] = "Rate_Application_Mobile"
resources.useragent.wurflapi.wurfl_api_version = "1.1"
resources.useragent.wurflapi.wurfl_lib_dir = APPLICATION_PATH "/../library/wurfl/WURFL/"
resources.useragent.wurflapi.wurfl_config_file = APPLICATION_PATH "/configs/wurfl-config.php"
wurfl-config.php
<?php
$resourcesDir = dirname(__FILE__) . '/../../data/wurfl/';
$wurfl['main-file'] = $resourcesDir . 'wurfl-2.0.27.zip';
$wurfl['patches'] = array($resourcesDir . 'web_browsers_patch.xml');
$persistence['provider'] = 'file';
$persistence['dir'] = $resourcesDir . 'cache/';
$cache['provider'] = null;
$configuration['wurfl'] = $wurfl;
$configuration['persistence'] = $persistence;
$configuration['cache'] = $cache;
Mobile Plugin
/var/www/library/Rate/Application/Mobile.php
class Rate_Application_Mobile extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $req)
{
$front = Zend_Controller_Front::getInstance();
$bootstrap = $front->getParam("bootstrap");
$userAgent = $bootstrap->getResource('useragent');
$device = $userAgent->getDevice(); --> this part return server error when switching to mobile browser, otherwise it return desktop when view as desktop browser
}
}
Thanks!!
Update: Error return as follow
Warning: include(/var/www/library/wurfl/WURFL/Storage/.php): failed to open stream: No such file or directory in /var/www/library/wurfl/WURFL/ClassLoader.php on line 42
Warning: include(): Failed opening '/var/www/library/wurfl/WURFL/Storage/.php' for inclusion (include_path='/var/www/application/../library:/var/www/library:.:/usr/share/php:/usr/local/Zend/library') in /var/www/library/wurfl/WURFL/ClassLoader.php on line 42
Fatal error: Class 'WURFL_Storage_' not found in /var/www/library/wurfl/WURFL/Storage/Factory.php on line 43
This is an answer I gave in the comments above, copied and pasted just for the sake of upvoting and accepting.
This is PHP error stating that class file was not found. You're including empty name PHP file, so WURFL probably can't detect what it needs to load. Please do a debug_backtrace() before error line in ClassLoader.php:42 (first error) and check what storage it tries / needs to load in Factory.php:43. If it's this file: Factory.php you're trying to load a file provider which should be specified in provider config tree which you do provide, but it's not read.
For now please clear ZF cache, and check if
$persistence['provider'] = 'file';
$cache['provider'] = null;
$configuration['persistence'] = $persistence;
do not interfere.