Laravel make directory fails with storage_path - php

Am using faker an i would like to generate images and save them but am getting an error
mkdir(): No such file or directory
So i have
$factory->define(App\User::class, function (Faker $faker) {
$filepath = storage_path('images/fakerusr/'); //this fails
if(!File::exists($filepath)){
File::makeDirectory($filepath);
};
return [
'profile_pic' => $faker->image($filepath,400,300)
];
});
BUt when i use
$filepath = public_path('images/fakerusr/'); //this works
But the path saved in the db starts from ./var/www... but i would like the path from images in the public folder.
I have added both read and write permissions to public folder
sudo chmod a+rw -R /var/www.../public
How do i go about this.

Ensure the images and child directory fakerusr already exists. By default the unix command mkdir requires the -p flag to "Create intermediate directories as required" and the PHP function mkdir also requires the 3rd parameter to be true to create nested directories . File::makeDirectory probably works this way too.

$filepath = storage_path('images/fakerusr/'); //this fails
if(!File::exists($filepath)){
File::makeDirectory($filepath, 0755, true, true);
};

you can check using Storage::has
$directory='images/fakerusr';
if (!Storage::has($directory)) {
$resp= Storage::makeDirectory($directory);
dd($resp);
} else{
echo "already exist";
};
Also note that directory will be created inside storage\app\ .And make sure you have 755 permission to these folders
if you want to create directory inside public folder
$directory='images/fakerusr';
if (File::isDirectory($directory)) {
echo "already exist";
} else{
$result = File::makeDirectory($directory, 0775, true);
}

For Check Directory Exists or Not And making the Directory as Public, I am using..
use Illuminate\Http\File;
$path = public_path('upload/imgaes');
if(!File::isDirectory($path)){
File::makeDirectory($path, 0777, true, true);
}
Hope this work

Related

Laravel 8 returns two different folders for the same path

I'm using Laravel 8.35.1 and try to check if a folder exists or - if not - create it.
The paths are:
data/4d61c171-cd94-48ec-82bb-8fee7394471a/processor/333afcbc-37be-4e19-bddc-605c21e766bb
data/4d61c171-cd94-48ec-82bb-8fee7394471a/downloads/333afcbc-37be-4e19-bddc-605c21e766bb
The folders should be created in storage/app/.
I do the same for both paths:
$processFolder = $fileHelper->existOrCreate('data/4d61c171-cd94-48ec-82bb-8fee7394471a/processor/333afcbc-37be-4e19-bddc-605c21e766bb');
$downloadFolder = $fileHelper->existOrCreate('data/4d61c171-cd94-48ec-82bb-8fee7394471a/downloads/333afcbc-37be-4e19-bddc-605c21e766bb');
public function existOrCreate($path)
{
if (!File::exists($path)) {
if (!File::makeDirectory($path, 0755, true)) {
send_error_mail('Folder could not be created: ' . $path);
}
}
return $path;
}
The problem is, that always the downloads folder is wrongly created in
/public/data/4d61c171-cd94-48ec-82bb-8fee7394471a/downloads/333afcbc-37be-4e19-bddc-605c21e766bb
and the processor folder is correctly created in
/storage/app/data/4d61c171-cd94-48ec-82bb-8fee7394471a/processor/333afcbc-37be-4e19-bddc-605c21e766bb
Any ideas?
Use the Storage facade instead of the File facade.

CakePHP, move_uploaded_file() does not work and I am not getting any errors

I am trying to upload a file using move_uploaded_file() in CakePHP3.
I have used a if statement to check what move_uploaded_file() is returning, and its false. I have attached my code but I think I am using the function correctly.
My target location is webroot/img/work.
I am not getting any errors.
I have changed dir owner sudo chown www-data:www-data work/
I have changed dir permissions sudo chmod 777 work/
I am new to cakePHP so I don't know what else I could try.
Here are my files:
src/Controller/WorkController.php
public function add()
{
// Get file to be uploaded.
$file = $this->request->getData('image');
// Set path to the upload location.
$target = WWW_ROOT . 'img' . DS . 'work' . DS;
$work = $this->Work->newEntity();
if($this->request->is('post')) {
$work = $this->Work->patchEntity($work, $this->request->getData());
// Assign value.
$work['image'] = $file['name'];
// Move uploaded file.
move_uploaded_file( $file['name'], $target );
if($this->Work->save($work)) {
$this->Flash->success(__('New work item added!'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add new work item.'));
}
$this->set('work', $work );
}
src/Template/Work/add.ctp
<?php
echo $this->Form->create($work, array( 'enctype' => 'multipart/form-data'));
echo $this->Form->control('title');
echo $this->Form->control('body', ['rows' => '5']);
echo $this->Form->control('link');
// echo $this->Form->control('image');
echo $this->Form->control('image', array('type' => 'file'));
echo $this->Form->button(__('Add Work'));
echo $this->Form->end();
?>
Not a lot of information given so here is a couple things:
According to php.net on move_uploaded_file()
Returns TRUE on success.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
So obviously it does not issue a warning, so it must not be a valid uploaded file.
Looking at your code you are trying to move the file name. When you upload a file via POST, PHP gives it a "tmp_name" which you can access via $file["tmp_name"].
So you should be doing move_uploaded_file($file["tmp_name"], $target);
I am assuming it failed because it is looking for (myimg.png) instead of (asdagasfas.png) or whatever PHP named it.

Failing to create folder in /Var/www/html from file.php

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
*/

Creating a folder when I run file_put_contents()

I have uploaded a lot of images from the website, and need to organize files in a better way.
Therefore, I decide to create a folder by months.
$month = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
after I tried this one, I get error result.
Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory
If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.
Is there a way to solve this problem?
file_put_contents() does not create the directory structure. Only the file.
You will need to add logic to your script to test if the month directory exists. If not, use mkdir() first.
if (!is_dir('upload/promotions/' . $month)) {
// dir doesn't exist, make it
mkdir('upload/promotions/' . $month);
}
file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
Update: mkdir() accepts a third parameter of $recursive which will create any missing directory structure. Might be useful if you need to create multiple directories.
Example with recursive and directory permissions set to 777:
mkdir('upload/promotions/' . $month, 0777, true);
modification of above answer to make it a bit more generic, (automatically detects and creates folder from arbitrary filename on system slashes)
ps previous answer is awesome
/**
* create file with content, and create folder structure if doesn't exist
* #param String $filepath
* #param String $message
*/
function forceFilePutContents ($filepath, $message){
try {
$isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
if($isInFolder) {
$folderName = $filepathMatches[1];
$fileName = $filepathMatches[2];
if (!is_dir($folderName)) {
mkdir($folderName, 0777, true);
}
}
file_put_contents($filepath, $message);
} catch (Exception $e) {
echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
}
}
i have Been Working on the laravel Project With the Crud Generator and this Method is not Working
#aqm so i have created my own function
PHP Way
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!file_exists($directoryPathOnly))
{
mkdir($directoryPathOnly,0775,true);
}
file_put_contents($fullPathWithFileName, $fileContents);
}
LARAVEL WAY
Don't forget to add at top of the file
use Illuminate\Support\Facades\File;
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!File::exists($directoryPathOnly))
{
File::makeDirectory($directoryPathOnly,0775,true,false);
}
File::put($fullPathWithFileName,$fileContents);
}
I created an simpler answer from #Manojkiran.A and #Savageman. This function can be used as drop-in replacement for file_put_contents. It doesn't support context parameter but I think should be enough for most cases. I hope this helps some people. Happy coding! :)
function force_file_put_contents (string $pathWithFileName, mixed $data, int $flags = 0) {
$dirPathOnly = dirname($pathWithFileName);
if (!file_exists($dirPathOnly)) {
mkdir($dirPathOnly, 0775, true); // folder permission 0775
}
file_put_contents($pathWithFileName, $data, $flags);
}
Easy Laravel solution:
use Illuminate\Support\Facades\File;
// If the directory does not exist, it will be create
// Works recursively, with unlimited number of subdirectories
File::ensureDirectoryExists('my/super/directory');
// Write file content
File::put('my/super/directory/my-file.txt', 'this is file content');
I wrote a function you might like. It is called forceDir(). It basicaly checks whether the dir you want exists. If so, it does nothing. If not, it will create the directory. A reason to use this function, instead of just mkdir, is that this function can create nexted folders as well.. For example ('upload/promotions/januari/firstHalfOfTheMonth'). Just add the path to the desired dir_path.
function forceDir($dir){
if(!is_dir($dir)){
$dir_p = explode('/',$dir);
for($a = 1 ; $a <= count($dir_p) ; $a++){
#mkdir(implode('/',array_slice($dir_p,0,$a)));
}
}
}

Codeigniter -> File Upload Path | Folder Create

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.

Categories