\Zend\File\Transfer\Adapter\Http() and filerenameupload - php

I'm trying to use the 'filerenameupload' filter with \Zend\File\Transfer\Adapter\Http():
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->addFilter('filerenameupload', array(
'target' => BASE_DIR . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR .
'img' . DIRECTORY_SEPARATOR . 'gallery' .
DIRECTORY_SEPARATOR . 'image.jpg',
'randomize' => true,
));
var_dump($adapter->isValid()); // true
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
Always having the error,
File '/tmp/somefile.png' could not be renamed. An error occurred while processing the file.
/tmp/somefile.png - exists, is readable an writable, distention folder too is readable an writable
Error comes from class RenameUpload:
protected function moveUploadedFile($sourceFile, $targetFile)
{
ErrorHandler::start();
$result = move_uploaded_file($sourceFile, $targetFile);
$warningException = ErrorHandler::stop();
if (!$result || null !== $warningException) {
throw new Exception\RuntimeException(
sprintf("File '%s' could not be renamed. An error occurred while processing the file.", $sourceFile), 0, $warningException
);
}
return $result;
}
So maybe someone have an example or know how to fix this error? Or what I'm doing wrong?

Thanks for #hemangpatel from #zftalk for advice, so the working action looks like:
public function uploadAction()
{
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination(BASE_DIR . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR .
'img' . DIRECTORY_SEPARATOR . 'gallery' . DIRECTORY_SEPARATOR);
// Returns all known internal file information
$adapter->addFilter('File\Rename', array('target' => $adapter->getDestination() .
DIRECTORY_SEPARATOR . rand(2, 10) . '.jpeg',
'overwrite' => true));
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
return new ViewModel(['messages' => $messages]);
} else {
$this->flashMessenger()->addSuccessMessage('Upload success');
$this->redirect()->toRoute('admin', ['controller' => 'gallery',
'action' => 'index']);
}
}

Related

How to fix Sometimes happen 500 error in Laravel

I have done configurations to fetch data from database and assign corresponding to it.
It works Fine. but sometimes issues happen like undefined index or target class not found.if i refresh again issues not happen that time.
Note: sometimes happens only. so i can't find what exact issue.
AppserviceProvider in boot method i call below function
public function CustomInit(){
if (env('DB_DATABASE') != '') {
// Configuration Setup for Email Settings
if (Schema::hasTable('email_settings')) {
$result = DB::table('email_settings')->get();
$mail_config = array(
"default" => $result[0]->value,
"from" => [
"address" => $result[3]->value,
"name" => $result[4]->value
],
"mailers" => [
"smtp" => [
'transport' => 'smtp',
"host" => $result[1]->value,
"port" => $result[2]->value,
"encryption" => $result[5]->value,
"username" => $result[6]->value,
"password" => $result[7]->value,
'timeout' => null,
],
]
);
Config::set('mail',$mail_config);
$site_settings = SiteSettings::all();
Config::set(
[
'laravel-backup.backup.name' => $site_settings[0]->value,
'laravel-backup.monitorBackups.name' => $site_settings[0]->value,
'laravel-backup.notifications.mail.from' => $result[3]->value,
'laravel-backup.notifications.mail.to' => $result[3]->value,
]
);
}
if (Schema::hasTable('site_settings')) {
$site_settings = DB::table('site_settings')->get()->pluck('value', 'name');
$rand = str_random(6);
if ($site_settings['site_url'] == '' && $_SERVER['HTTP_HOST']) {
$url = "http://" . #$_SERVER['HTTP_HOST'];
$url .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", #$_SERVER['SCRIPT_NAME']);
SiteSettings::where('name', 'site_url')->update(['value' =>$url]);
}
if (!#$_SERVER['HTTP_HOST']) {
Config::set('app.url', $site_settings['site_url']);
URL::forceRootURL($site_settings['site_url']);
}
View::share("site_name", $site_settings['site_name']);
View::share("version", $site_settings['version']);
View::share("version", str_random(4));
View::share('favicon', url('logos/' . $site_settings['favicon'] . '?v=' . $rand));
View::share('logo_web_1', url('logos/' . $site_settings['logo_web_1'] . '?v=' . $rand));
View::share('logo_web_2', url('logos/' . $site_settings['logo_web_2'] . '?v=' . $rand));
View::share('email_logo', url('logos/' . $site_settings['email_logo'] . '?v=' . $rand));
View::share('web_favicon', url('logos/' . $site_settings['favicon'] . '?v=' . $rand));
define('SITE_NAME', $site_settings['site_name']);
define('LOGO_URL', url('logos/' . $site_settings['logo_web_1'] . '?v=' . $rand));
define('EMAIL_LOGO', url('logos/' . $site_settings['email_logo'] . '?v=' . $rand));
define('FAV_ICON', url('logos/' . $site_settings['favicon'] . '?v=' . $rand));
}
if (Schema::hasTable('join_us')) {
$join_us = DB::table('join_us')->get()->pluck('value', 'name');
View::share("app_store", $join_us['app_store']);
View::share("play_store", $join_us['play_store']);
}
if (Schema::hasTable('api_credentials')) {
// For Google Key
$google_map_result = DB::table('api_credentials')->where('site', 'GoogleMap')->get();
define('MAP_KEY', $google_map_result[0]->value);
define('MAP_SERVER_KEY', $google_map_result[1]->value);
View::share('map_key', $google_map_result[0]->value);
// For TWILLO Key
$twillo_result = DB::table('api_credentials')->where('site', 'Twillo')->get();
define('TWILLO_SID', $twillo_result[0]->value);
define('TWILLO_TOKEN', $twillo_result[1]->value);
define('TWILLO_FROM', $twillo_result[2]->value);
// For TWILLO Key
$fcm_result = DB::table('api_credentials')->where('site', 'FCM')->get();
Config::set(
['fcm.http' => [
'server_key' => $fcm_result[0]->value,
'sender_id' => $fcm_result[1]->value,
'server_send_url' => 'https://fcm.googleapis.com/fcm/send',
'server_group_url' => 'https://android.googleapis.com/gcm/notification',
'timeout' => 10,
],
]
);
}
$current_route = url()->current();
if (Route::current()) {
$current_route = Route::current()->uri();
}
View::share('current_route', $current_route);
}
}
Thanks in Advance...
Short answer is don't try and read the .env file in your controller, retrieve the values through a corresponding config file instead.
Long answer - since Laravel 5.2.0 "if you use the config:cache command during deployment you MUST make sure you are only calling the env function from within your configuration files, and not from anywhere else in your application" - https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0
In the code you've cited you're calling the .env file direct with :
if (env('DB_DATABASE') != '') {
Depending on which driver you're using, instead you want to retrieve this through the config/database.php file :
if(config('database.mysql.database' != '') {
That will provide a more stable method of retrieving the relevant value so you can see if it is empty or not.

Laravel Undefined variable: file

I have a small app to sell online courses.
Everytime I reset my migrations by doing php artisan migrate:reset, I get this error if I try to update a field in my Ecourses edit blade file.
Here's my controller
public function update(Request $request, $id)
{
$slugify = new Slugify();
$this->validate($request, [
'name' => 'required',
'price' => 'nullable',
'category_id' => 'required',
'level_id' => 'required',
'subtitle' => 'required',
'description' => 'required',
'video_link' => 'required',
'document' => 'nullable|file',
'status' => 'required|integer'
]);
$ecourse = Ecourse::findOrFail($id);
$ecourse->name = $request->name;
$ecourse->slug = $slugify->slugify($request->name);
$ecourse->price = $request->price;
$ecourse->status = $request->status;
$ecourse->description = $request->description;
$ecourse->subtitle = $request->subtitle;
$ecourse->video_link = $request->video_link;
$ecourse->category_id = $request->category_id;
$ecourse->level_id = $request->level_id;
$document = $request->file('document');
if ($request->hasFile('document')) {
$documentFullname = $document->getClientOriginalName();
$documentName = pathinfo($documentFullname, PATHINFO_FILENAME);
$extension = $document->getClientOriginalExtension();
$file = time() . '_' . $documentName . '.' . $extension;
$document->storeAs('public/ecourses-files/', $file );
}
$fileToDelete = 'public/ecourses-files'. '/' . $ecourse->document;
if (Storage::exists($fileToDelete)) {
Storage::delete($fileToDelete);
}
$ecourse->document = $file;
$ecourse->save();
return redirect()->route('admin.ecourses.index')->with('success','Formation mise à jour');
}
The error is due to this line $ecourse->document = $file; and to make it work I have to comment it, update my Ecourse blade and then uncomment it.
I really don't know what's happening here...
Any help or explanation would be appreciated.
Thanks and take care.
Well it looks like that $request->hasFile('document') return false in this case this block of code will never run
if ($request->hasFile('document')) {
$documentFullname = $document->getClientOriginalName();
$documentName = pathinfo($documentFullname, PATHINFO_FILENAME);
$extension = $document->getClientOriginalExtension();
$file = time() . '_' . $documentName . '.' . $extension;
$document->storeAs('public/ecourses-files/', $file );
}
So there is no variable $file is defined, to solve this you can do
$file = null;
if ($request->hasFile('document')) {
$documentFullname = $document->getClientOriginalName();
$documentName = pathinfo($documentFullname, PATHINFO_FILENAME);
$extension = $document->getClientOriginalExtension();
$file = time() . '_' . $documentName . '.' . $extension;
$document->storeAs('public/ecourses-files/', $file );
}
This will solve the problem but in case that column document cannot be null it will give you an error so you you will have to make it required in validation rules and check why $request->hasFile('document') returns false
Alternative solution, check $file with isset(), if not define then define it, as like :
if(!isset($file)){
$file = null;
}
$ecourse->document = $file;
There is an operator for this:
$course->document = $file ?? null;

Laravel 5.5: File download FileNotFoundException?

I'm building a projectmanagement system, where users can upload file attachments to tasks. These attachments are stored in directory 'storage/app/public/projects//'. Uploading works like it should, in the right directory under the right ID.
However when I want to download said attachment, somehow the file can't be found. I've provided the code from my up- and download methods, as well as my 'local' driver configuration.
Driver configuration:
'local' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'storage'
],
Upload method:
$sExt = $request->file('attachment')->getClientOriginalExtension();
$sHashedName = substr(
sha1(str_replace(' ', '', pathinfo($request->file('attachment')->getClientOriginalName(), PATHINFO_FILENAME))
), 0, 14);
if ( ! Storage::disk('local')->exists($sHashedName . '.' . $sExt)) {
$request->file('attachment')->storeAs(
'/projects/'.$oTask->project->id, $sHashedName . '.' . $sExt, 'local'
);
}
$oTask->attachments()->create([
'name' => $request->name,
'location' => $sHashedName . '.' . $sExt,
'user_id' => Auth::id()
]);
Current download method:
public function downloadAttachment(Project $project, Task $task, Attachment $attachment)
{
var_dump(rtrim(env('APP_URL'), '/') . public_path('/projects/' . $project->id . '/' . $attachment->location));
if (rtrim(env('APP_URL'), '/') . public_path('/projects/' . $project->id . '/' . $attachment->location)) {
return response()->download(rtrim(env('APP_URL'), '/') . public_path('/projects/' . $project->id . '/' . $attachment->location));
} else {
return $this->redirectWithAlert(
'error',
'download',
'attachment',
$attachment->name,
'/projects/'.$project->id.'/tasks/'.$task->id
);
}
}
This was my last attempt before posting this question. I have also tried Storage::url('/projects/<project_id>/<filename>') and a number of other things, but none work. I have linked a public storage directory according to the Laravel docs (with php artisan storage:link). I'm probably missing something logical here, but I'm completely lost.
The public_path function refers to ./public/, and not the storage disk 'public' that can be found in ./storage/app/public/
One way of solving this would be to replace public_path('/projects/' with storage_path('app/public/projects/'

Unable to open using mode r: fopen(): AWS Elastic Beanstalk

Error:Unable to open using mode r: fopen(): Filename cannot be empty I keep getting this error when I try to upload larger files (more than 5MB). I have uploaded the PHP app to AWS Elastic Beanstalk and I upload the files to AWS S3. I don't even have fopen() in the code.
Alson when I test the site using XAMPP I don't get this error.
This is the code I use to upload file to S3:
<?php
session_start();
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'tolga20.images';
$IAM_KEY = '******************';
$IAM_SECRET = '*************************';
$feedback = '';
$unqiue_num = mt_rand(1000, 9999);
if(isset($_FILES['fileToUpload'])) {
$user_set_id = $_POST['user_set_id'];
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'eu-west-2'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
$temp_name = explode(".", $_FILES["fileToUpload"]["name"]);
$newfilename = $unqiue_num . "-" . $user_set_id . '.' . end($temp_name);
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
$keyName = 'images/' . basename($newfilename);
$pathInS3 = 'https://s3.eu-west-2.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["fileToUpload"]['tmp_name'];
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
//$feedback = 'File uploaded! Custom name: ' . '<b><i>' . $newfilename;
$_SESSION['newfilename'] = $newfilename;
header("Location: next.php");
}
?>
Try to increase the POST_MAX_SIZE and UPLOAD_MAX_FILESIZE values in your php.ini!
$file = $_FILES["fileToUpload"]['tmp_name'];
change to
$file = $_FILES["fileToUpload"]['name'];
Hope it will solve your problem.

Uploading facebook event picture throws error

I am trying to create event with picture, but when i upload picture to facebook it throws me an error (#324) Missing or invalid image file
this is the function to upload picture.
public function uploadFacebookEventPicture($fullPath, $eventId) {
$mainImage = '#' . $fullPath;
$imgData = array(
'picture' => $mainImage
);
try {
$data = $this->facebook->api('/'.$eventId, 'post', $imgData);
return $data;
} catch (FacebookApiException $e) {
error_log('Failed to attach picture to event. Exception: ' . $e->getMessage());
}
return null;
}
the par of code i use after form post
if ($file[$name]['error'] == 0) {
$fileName = $file[$name]['name'];
$fileInfo = pathinfo($fileName);
$newFileName = md5($fileName . microtime()) . '.' . $fileInfo['extension'];
$fullPath = $this->config->applications->uploadPath . $newFileName;
$form->$name->addFilter('Rename', $fullPath);
if ($form->$name->receive()) {
$resize = new SimpleImage();
$resize->load($fullPath);
$resize->resizeToWidth($this->config->applications->resize->width);
$resize->save($fullPath);
// Gathering data for saving files information
$fileInfo = array(
'name' => $newFileName,
'type' => FileTypes::IMAGE,
'description' => 'Application: Uploaded from Events form in back-end',
);
$fileId = $dbFiles->save($fileInfo);
$eventFileData = array(
'event_id' => $eventId,
'file_id' => $fileId,
'main_image' => ($name == 'mainImage') ? 1 : 0
);
$dbEventFiles->save($eventFileData);
if ($name === 'mainImage') {
$success = **$this->uploadFacebookEventPicture($fullPath, $eventData['fb_event_id']**);
}
}
}
facebook object is created with upload file true
$facebook = new Facebook(array(
'appId' => $config->facebook->appId,
'secret' => $config->facebook->secret,
'fileUpload' => true
));
According to Facebook bug tracker, this bug has been fixed:
Bug tracker post
Status changed to Fixed
Code above works fine for uploading facebook event picture.

Categories