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
*/
Related
I've created a basic page where people "sign up" to upload/delete files in their own isolated folder.
The uploading/deleting of files are secure, however I would also like to allow admins to "deny" files.
The code alone works, except if anyone changes the URL to somewhere else on the server, they can "deny" any file on the system putting it at risk. I am looking to create a system function of which detects if the file they are targeting exists anywhere in the directory tree.
Here's the code that I am using of which I'd like to create a function that returns either true/false.
<?php
if(isset($_GET['deny'])) {
$tree_start = "Uploads";
$targeted_file = $_GET['deny'];
$safe_to_delete = in_directory_tree($tree_start, $targeted_file); <-- Looking for this
if( $safe_to_delete == false ) {die("This file does not exist in the directory tree");}
rename($_GET['deny'], "./Uploads/#Denied/". basename($_GET['deny']) );
}
?>
My Directory tree:
.htaccess <-- Prevent downloading of the database
admin.php <-- Problematic file browser script
index.php <-- User File management script
Users.db <-- Names and hashed passwords
Uploads:
[FILE] htaccess <-- Prevent script execution (layer 2).
[DIR] #Accepted: Notes.png, Video.mp4, etc...
[DIR] #Denied: Project.png, new_timetable.txt, etc...
[DIR] Admin: Proj1.txt, Proj1.png, etc...
[DIR] User1: Task1.txt, Task2.txt, etc...
[DIR] User2: Video1.txt, date.txt, etc...
give this code a try:
function in_directory_tree($dir,$file_to_search){
$filesList = new RecursiveDirectoryIterator("uploads");
$targetFile = "contact.php" ;
foreach(new RecursiveIteratorIterator($filesList) as $file)
{
$contents = explode("\\",$file);
if (in_array($targetFile, $contents))
return true;
}
return false;
}
This code will load the directory and start searching recursively, if it reaches the end without finding the file it will return false, otherwise it will return true.
I used RecursiveDirectoryIterator as it will help us get inside directories to list them
I have solved this problem by preventing path traversal instead of checking if the file exists in this folder. This code works for me (returns true only when a file in /uploads exists (and blocks going back using C:/, ../, etc), and returns true only when the file does exist. Here is the finished code:
<?php
// Code used for the deny button:
// <button onclick="location.href='?deny=SmilerRyan/Project.png';">Deny</button>
if(isset($_GET['deny'])) {
$userpath = $_GET['deny'];
$basepath = 'Uploads/';
$realBase = realpath($basepath);
$userpath = $basepath . $userpath;
$realUserPath = realpath($userpath);
if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
die("Invalid path - Possible Attack Blocked");
} else {
rename($userpath, "./Uploads/#Denied/" . basename($userpath) );
}
}
?>
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
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');
}
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)));
}
}
}
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.