How to create a folder in php? - php

Now in my code one folder is createed like private/119 when I logged into my application. The code is,
if (!is_dir('private/'.$q->row()->userId)) {
$oldmask = umask(0);
$q=mkdir('private/' .$q->row()->userId,0777,true);
umask($oldmask);
copy('public/images/default_user.png','private/'.$q->row()->userId.'/default-profile_pic.png');
}
Now I want to create a one more folder inside that userId(119) folder. How to do that? I have tried something like that $q=mkdir('private/' .$q->row()->userId .'/beforeconvert',0777,true); but it is not working.
Or is the following code is correct?
if (!is_dir('private/'.$q->row()->userId) && !is_dir('private/'.$q->row()->userId .'/beforeconvert')) {
$oldmask = umask(0);
$q=mkdir('private/' .$q->row()->userId,0777,true);
$create_folder = mkdir('private/' .$q->row()->userId .'/beforeconvert',0777,TRUE);
umask($oldmask);
copy('public/images/default_user.png','private/'.$q->row()->userId.'/default-profile_pic.png');
}

According to your code direcoty beforeconvert will not created if parent directory : $q->row()->userId already exist.
Also you don't need to create first parent directory then child. You can directly create child directory with mkdir it will create parent directory also.
Change your code as below:
<?php
if (!is_dir('private/'.$q->row()->userId .'/beforeconvert')) {
$oldmask = umask(0);
$create_folder = mkdir('private/' .$q->row()->userId .'/beforeconvert',0777,TRUE);
umask($oldmask);
copy('public/images/default_user.png','private/'.$q->row()->userId.'/default-profile_pic.png');
}

Related

Delete folder if no files exist within it - Google Drive API

I currently have the function:
function deleteFileUsingID($fileID) {
$this->service->files->delete($fileID);
}
How would I have to modify it such that after deleting the file, if no files exists within that folder, it deletes the folder itself.
I believe your goal as follows.
When there are no files in the specific folder, you want to delete the folder.
In this case, you can check whether the files are in the folder using the method of "Files: list" in Drive API.
Modified script:
Please set the folder ID to $folderId = '###';.
function deleteFileUsingID($fileID) {
$this->service->files->delete($fileID);
$folderId = '###'; // Please set the folder ID.
$fileList = $this->service->files->listFiles(array("q" => "'{$folderId}' in parents"));
if (count($fileList->getFiles()) == 0) {
$this->service->files->delete($folderId);
}
}
Or, when you want to retrieve the folder ID from $fileID, you can also use the following script.
function deleteFileUsingID($fileID) {
$folderIds = $this->service->files->get($fileID, array("fields" => "parents"))->getParents();
$this->service->files->delete($fileID);
if (count($folderIds) > 0) {
$folderId = $folderIds[0];
$fileList = $this->service->files->listFiles(array("q" => "'{$folderId}' in parents"));
if (count($fileList->getFiles()) == 0) {
$this->service->files->delete($folderId);
}
}
}
In this modified script, after $this->service->files->delete($fileID); was run, it checks whether the files are in the folder using the method of "Files: list". When no files in the folder, the folder is deleted.
Note:
In this case, the folder is deleted. So please be careful this. I would like to recommend to use the sample folder for testing the script.
Reference:
Files: list

Create Path at Microsoft Azure with PHP

Im building an application where I need to dynamically create some directories using the Azure's PHP SDK.
I did it using a loop but Im unsure if thats the correct way of doing it so heres my code;
I cant create a path that already exists so I have to check level by level if a directory and exists, than enters it and repeat.
public function generateDirectory($path)
{
$pathArray = explode("/", $path);
$currentPath = "";
try {
foreach ($pathArray as $key => $slice) {
$directories = $this->fileClient->listDirectoriesAndFiles("abraco", $currentPath)->getDirectories();
$currentPath .= $slice . "/";
$exists = false;
foreach ($directories as $key => $directory) {
if ($directory->getName() === $slice) {
$exists = true;
break;
}
}
if (!$exists) {
$this->fileClient->createDirectory("abraco", $currentPath);
}
}
return true;
} catch (Exception $e) {
return false;
}
}
Doesnt it should have a method to create a full path with subfolders? I think that this way is not performatic.
Doesnt it should have a method to create a full path with subfolders? I think that this way is not performatic.
I agree with you that there is a method to create a full path with subfolders will be better.
But currently, as you metioned that if we want to create full path with subfolders, we need to create the directory folder level by level.
If you use fiddler to capture request while you create multi-level directory structure via PHP SDK,you could find it use the following Rest API
https://myaccount.file.core.windows.net/myshare/myparentdirectorypath/mydirectory?
restype=directory
For more information please refer to Azure file Storage Create directory API.
myparentdirectorypath Optional. The path to the parent directory where mydirectory is to be created. If the parent directory path is omitted, the directory will be created within the specified share.
If specified, the parent directory must already exist within the share before mydirectory can be created.

Laravel make directory fails with storage_path

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

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

Mkdir in php set wrong permission

I have the following code :
if (!file_exists('/public_html/'.'classic/'.'test'.'/')) {
if(!mkdir('/public_html/'.'classic/'.'test'.'/', 0777, true)) {
return false;
}
}
This create only the folder /classic witch have the permission 0755 and another owner. How to change to create recusively 2 folders : /classic/test/ ? Thx in advance and sorry for my english
I found a solution by using umask :
$oldumask = umask(0);
mkdir('mydir', 0777); // or even 01777 so you get the sticky bit set
umask($oldumask);

Categories