Currently I have the following:
$config['upload_path'] = 'this/path/location/';
What I would like to do is create the following controller but I am not sure how to attack it!!
$data['folderName'] = $this->model->functionName()->tableName;
$config['upload_path'] = 'this/'.$folderName.'/';
How would I create the $folderName? dictionary on the sever?
Jamie:
Could I do the following?
if(!file_exists($folderName))
{
$folder = mkdir('/location/'$folderName);
return $folder;
}
else
{
$config['upload_path'] = $folder;
}
am not sure what they are talking about by using the file_exist function since you need to check if its the directory ..
$folderName = $this->model->functionName()->tableName;
$config['upload_path'] = "this/$folderName/";
if(!is_dir($folderName))
{
mkdir($folderName,0777);
}
please note that :
i have added the permission to the folder so that you can upload files to it.
i have removed the else since its not useful here ( as #mischa noted )..
This is not correct:
if(!file_exists($folderName))
{
mkdir($folderName);
}
else
{
// Carry on with upload
}
Nothing will be uploaded if the folder does not exist! You have to get rid of the else clause.
$path = "this/$folderName/";
if(!file_exists($path))
{
mkdir($path);
}
// Carry on with upload
$config['upload_path'] = $path;
Not quite sure what you mean by 'dictionary', but if you're asking about how to create a variable:
$folderName = $this->model->functionName()->tableName;
$config['upload_path'] = "this/$folderName/";
To add/check the existence of a directory:
if(!file_exists($folderName))
{
mkdir($folderName);
}
else
{
// Carry on with upload
}
Not 100% sure what you want from your description so here are a few suggestions:
If you need to programmatically create a folder using PHP you can use the mkdir() function, see: http://php.net/manual/en/function.mkdir.php
Also, check out the Codeignitor file helper for reading and writing files:
http://codeigniter.com/user_guide/helpers/file_helper.html
If the folder already exists, you need to make sure the permissions are write-able. On windows you can right click on the folder, properties, security and edit there. On Linux you'll want the chmod command.
Related
In my Laravel 5.5 project I am having a problem in showing uploaded files. I uploaded the files using Storage. The part of store action of the controller is indicated below.
if ($request->hasFile('content_uz'))
{
$path = $request->file('content_uz')->store('/content/lesson'.$topic->lesson->id.'/topic'.$topic->id);
$data->content_uz = $path;
}
if ($request->hasFile('content_ru'))
{
$path = $request->file('content_ru')->store('/content/lesson'.$topic->lesson->id.'/topic'.$topic->id);
$data->content_ru = $path;
}
Uploading happened successfully. The path to uploaded 'content_uz' file is stored with "storage/app/content/lesson2/topic3" path and content_uz column is stored in my db as below:
content\lesson2\topic3\WSjrlG9a1ermGDOvRJTjn9iEIhfFvhVzjaOs6l79.mp4
How can I display the files in my Blade template? I searched the web, but with no result.
You can use method like this,
public function showFile() {
header("Content-type: video/mp4");
return Storage::get($filePath);
}
I hope this will help.
You may access the files of storage directory by two ways.
If your files are publicly accessible then you may follow laravel public disk.
If your files are protected or private then you may declare a route to access the files.
Route::get('content/{lesson}/{topic}/{file}', function($lesson, $topic, $file)
{
//Check access logic
$filePath = '/content/' . $lesson . '/' . $topic . '/' . $file;
return Storage::get($filePath);
});
how to delete images file from public/images folder in laravel 5 ??
i found some example from this site, but i know they are just using the file name in their record table, but i'm using something like URL e.g localhost/project/uploads/filename.jpg on my record table. so if i tried like this :
$image_path = $data->image; // the value is : localhost/project/image/filename.format
if(File::exists($image_path)) {
File::delete($image_path);
}
the file is not deleted
help pls, thanks
If you want to delete image from your server, you have to reference location of file in directory server, means you could not reference by url link to delete it.
Commonly, Laravel 5 file is locate in public folder.
Example: your files are located in public/images
$image_path = "/images/filename.ext"; // Value is not URL but directory file path
if(File::exists($image_path)) {
File::delete($image_path);
}
If I can delete image from server by reference URL then Google is the first target :)
You can use the normal PHP delete file keyword ( #unlink )
$image_path = "the name of your image path here/".$request->Image;
if (file_exists($image_path)) {
#unlink($image_path);
}
This is what I do to delete an image:
public function SliderDelete(String $slider_id)
{
$slider = Slider::findOrFail($slider_id);
$image_path = public_path("\storage\images\sliders\\") .$slider->photo;
if(File::exists($image_path)) {
File::delete($image_path);
}
else{
$slider->delete();
//abort(404);
}
$slider->delete();
return response()->json(['success'=>'Slider deleted successfully!']);
}
in laravel 8 you do it like
// import Storage class
use Illuminate\Support\Facades\Storage;
Storage::disk('public')->delete('path-of-file');
you can use disk of your choice like
Storage::disk('s3')->delete('path-of-file');
$filename = public_path($fileloc);
if(File::exists($filename)) {
File::delete($filename);
}
call this function and pass two parameter
$filepath = path where your file exist
$filename = name of your file
public static function UnlinkImage($filepath,$fileName)
{
$old_image = $filepath.$fileName;
if (file_exists($old_image)) {
#unlink($old_image);
}
}
public function destroy($id)
{
$imagePath = YourModelName::select('image')->where('id', $id)->first();
$filePath = $imagePath->image;
if (file_exists($filePath)) {
unlink($filePath);
YourModelName::where('id', $id)->delete();
}else{
YourModelName::where('id', $id)->delete();
}
}
To be able to delete the image it should be in the following form :
"/uploads/img1.jpg" where uploads directory is in the public directory then use the following code:
$image_path = puplic_path("/uploads/img1.jpg")
if (file_exists($image_path)) {
File::delete($image_path);
}
Here is the correct and easy way .
if (file_exists(public_path() . '/storage/gallery/images/'. $item->image)) {
unlink(public_path() . '/storage/gallery/images/'. $item->image);
}
I have a AWS EC2 server with phpMyAdmin to manage it.
Everything is working correctly but I would like to be able to create another folder in the /var/www/html directory to add files..
This is my code but it just keeps returning the error to me! any ideas??
// STEP 2.2 Create a folder in server to store posts'pictures
$folder = "/var/www/html/bloggerFiles/Posts/" . $id;
if(!file_exists($folder)){
if (!mkdir($folder, 0777, true)) {//0777
die('Failed to create folders...');
}
}
I would normally create that folder in the terminal by using sudo mkdir, but when I add sudo Nothing works!
Any help is appreciated!
Thanks in advance.
Make sure the folder(s) you are accessing are set to read and write folder permissions, then use this function:
function newFolder($path, $perms)
$path = str_replace(' ', '-', $path);
$oldumask = umask(0);
mkdir($path, $perms); // or even 01777 so you get the sticky bit set (0777)
umask($oldumask);
return true;
}
This fixed it for me.
You can create new folder doing this: newFolder('PathToFolder/here', 0777);
EDIT: Please have a look at: https://www.youtube.com/watch?v=7mx2XOFBp8M
EDIT: Also have a look at http://php.net/manual/en/function.mkdir.php#1207
EDIT: Storing functions in classes and safely use the function
class name_here
{
public function newFolder($path, $perms, $deny_if_folder_exists){
$path = 'PATH_TO_POSTS/'.$path; // This is for setting the root to PATH TO POSTS
$path = str_replace('../', '', $path); // Deny the path to go out of var/www/html/PATH_TO_POSTS/$path
if( $deny_if_folder_exists === true ){
if(file_exists($path)){return false;}
$old_umask = umask(0);
mkdir($path, $perms);
umask($old_umask);
}elseif( $deny_if_folder_exists === false ){
$old_umask = umask(0);
mkdir($path, $perms);
umask($old_umask);
}else{
return false; // Unknown
}
}
}
/* Call the function by doing this: */
$manage = new name_here;
$manage->newFolder('test', 777, true); // Test will appear in /var/www/html/PATH_TO_POSTS/$path, but if the folder exists it will return false and not create the folder.
EDIT: If this file is called from html it will re create the path, so I will it has to be called from /html/
EDIT: How to use the name_here class
/*
How to call the function?
$manage = new name_here; Creates a variable to an object (The class)
$manage->newFolder('FolderName', 0777, true); // Will create a folder to the path,
but this fill needs to be called from the html the root directory is set to the
"PATH_TO_POSTS/" basicly means you cannot do this function from "html/somewhere/form.php",
UNLESS the "PATH_TO_POSTS" is in the same directory as form.php
*/
I need help for how to upload a file in WordPress, I don't want to upload files into the default path of media files i.e. into uploads/../.., I want to upload my files into wp-content/uploads/my_folder, I just created one file in wp-admin folder and added some functionality there, from that form I want to upload my file (not creating plugin).
Is it possible to do like this? If yes then how? If no then what I want to do for uploading file?
I tried the following solution for it:
$path_array = wp_upload_dir();
$upload_path = $path_array['baseurl'].'/myfoldername/';
$target_path = $upload_path."/".$file_name;
$file_name = $_FILES['fieldname']['name'];
$tmp_name = $_FILES["fieldname"]["tmp_name"];
upload_user_file($_FILES,$upload_path); // Called this function
In functions.php of my theme, I defined the above called function upload_user_file() like as follows:
function upload_user_file( $file = array(),$path) {
if(!empty($file))
{
$uploaded=move_uploaded_file($file['fieldname']['tmp_name'],$path.$file['fieldname']['name']);
if($uploaded)
{
echo "Uploaded successfully ";
}
else
{
echo "Some error in upload ";
print_r($file['error']);
}
}
}
Please help me for this issue.
Thanks.
It's not working because of FILES array loses its values very soon..
Upload it in the same code where you called function it will work...
Thanks cale_b its really helpful.
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.