How to create a directory in Live Server using PHP? - php

<?php
$dirPath = "Admin/new_images";
$result = mkdir($dirPath, 0777);
if ($result == 1) {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
?>
This code is working fine with my Local Host.
But its not working on live server.
Can anyone help me on this?

try this:
<?php
$dirPath = "Admin/new_images";
$result = mkdir($dirPath, 0777, true);
chmod($dirPath, 0777);
if ($result == 1) {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
?>
for window u have to change $dirPath like below:
$dirPath = "Admin\\new_images";

mkdir — Makes directory
Description
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )
Attempts to create the directory specified by pathname.
Parameters :
pathname The directory path.
mode The mode is 0777 by default, which means the widest possible
access. For more information on modes, read the details on the chmod()
page.
Note:
mode is ignored on Windows.
Note that you probably want to specify the mode as an octal number,
which means it should have a leading zero. The mode is also modified
by the current umask, which you can change using umask().
recursive Allows the creation of nested directories specified in the
pathname. Defaults to FALSE.
context Note: Context support was added with PHP 5.0.0. For a
description of contexts, refer to Stream Functions
Return Values
Returns TRUE on success or FALSE on failure.
<?php
/**
* Makes directory, returns TRUE if exists or made
*
* #param string $pathname The directory path.
* #return boolean returns TRUE if exists or made or FALSE on failure.
*/
function mkdir_recursive($pathname, $mode)
{
is_dir(dirname($pathname)) || mkdir_recursive(dirname($pathname), $mode);
return is_dir($pathname) || #mkdir($pathname, $mode);
}
?>

Try the below code
<?php
test();
function test(){
$root_path = $_SERVER['DOCUMENT_ROOT'];
$directory_name = 'testDir';
if (!file_exists($root_path.'/'.$directory_name)) {
if(mkdir($root_path.'/'.$directory_name, 0777, true)){
print "Directory created successfully.";
}else{
print "Error in creating Directory.";
}
}else{
print "Directory already exists.";
}
}
?>

Related

How to create a directory based on a data in database and save the file in it [duplicate]

I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.
Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.
So I need to add code to my theme that checks for the folder and creates it otherwise.
Try this, using mkdir:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Note that 0777 is already the default mode for directories and may still be modified by the current umask.
Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:
mkdir('path/to/directory', 0755, true);
Here is something a bit more universal since this comes up on Google. While the details are more specific, the title of this question is more universal.
/**
* recursively create a long directory path
*/
function createPath($path) {
if (is_dir($path))
return true;
$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
$return = createPath($prev_path);
return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}
This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it's created all the directories. It returns true if successful.
It could be improved by providing a stopping level so it just fails if it goes beyond the user folder or something and by including permissions.
Use a helper function like this:
function makeDir($path)
{
$ret = mkdir($path); // use #mkdir if you want to suppress warnings/errors
return $ret === true || is_dir($path);
}
It will return true if the directory was successfully created or already exists, and false if the directory couldn't be created.
A better alternative is this (shouldn't give any warnings):
function makeDir($path)
{
return is_dir($path) || mkdir($path);
}
A faster way to create a folder:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Recursively create the directory path:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
Inspired by Python's os.makedirs()
The best way is to use the wp_mkdir_p function. This function will recursively create a folder with the correct permissions.
Also, you can skip folder exists condition because the function returns:
true when the directory was created or existed before
false if you can't create the directory.
Example:
$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
// Directory exists or was created.
}
More: https://developer.wordpress.org/reference/functions/wp_mkdir_p/
Within WordPress, there's also the very handy function wp_mkdir_p which will recursively create a directory structure.
Source for reference:
function wp_mkdir_p( $target ) {
$wrapper = null;
// Strip the protocol
if( wp_is_stream( $target ) ) {
list( $wrapper, $target ) = explode( '://', $target, 2 );
}
// From php.net/mkdir user contributed notes
$target = str_replace( '//', '/', $target );
// Put the wrapper back on the target
if( $wrapper !== null ) {
$target = $wrapper . '://' . $target;
}
// Safe mode fails with a trailing slash under certain PHP versions.
$target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
if ( empty($target) )
$target = '/';
if ( file_exists( $target ) )
return #is_dir( $target );
// We need to find the permissions of the parent folder that exists and inherit that.
$target_parent = dirname( $target );
while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
$target_parent = dirname( $target_parent );
}
// Get the permission bits.
if ( $stat = #stat( $target_parent ) ) {
$dir_perms = $stat['mode'] & 0007777;
} else {
$dir_perms = 0777;
}
if ( #mkdir( $target, $dir_perms, true ) ) {
// If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
$folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
#chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
}
}
return true;
}
return false;
}
I needed the same thing for a login site. I needed to create a directory with two variables.
The $directory is the main folder where I wanted to create another sub-folder with the users license number.
include_once("../include/session.php");
$lnum = $session->lnum; // Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in
if (!file_exists($directory . "/" . $lnum)) {
mkdir($directory . "/" . $lnum, 0777, true);
}
This is the most up-to-date solution without error suppression:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory');
}
For your specific question about WordPress, use the following code:
if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');
Function Reference: WordPress wp_mkdir_p. ABSPATH is the constant that returns WordPress working directory path.
There is another WordPress function named wp_upload_dir(). It returns the upload directory path and creates a folder if doesn't already exists.
$upload_path = wp_upload_dir();
The following code is for PHP in general.
if (!is_dir('path/to/directory')) mkdir('path/to/directory', 0777, true);
Function reference: PHP is_dir()
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
Here you go.
if (!is_dir('path/to/directory')) {
if (!mkdir('path/to/directory', 0777, true) && !is_dir('path/to/directory')) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', 'path/to/directory'));
}
}
You can try also:
$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);
If you want to avoid the file_exists vs. is_dir problem, I would suggest you to look here.
I tried this and it only creates the directory if the directory does not exist. It does not care if there is a file with that name.
/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
mkdir($path_to_directory, 0777, true);
}
To create a folder if it doesn't already exist
Considering the question's environment.
WordPress.
Webhosting server.
Assuming it's Linux, not Windows running PHP.
And quoting from: mkdir
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive =
FALSE [, resource $context ]]] )
The manual says that the only required parameter is the $pathname!
So, we can simply code:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// Todo
}
?>
Explanation:
We don't have to pass any parameter or check if the folder exists or even pass the mode parameter unless needed; for the following reasons:
The command will create the folder with 0755 permission (the shared hosting folder's default permission) or 0777, the command's default.
mode is ignored on Windows hosting running PHP.
Already the mkdir command has a built-in checker for if the folder exists; so we need to check the return only True|False ; and it’s not an error; it’s a warning only, and Warning is disabled on the hosting servers by default.
As per speed, this is faster if warning disabled.
This is just another way to look into the question and not claiming a better or most optimal solution.
It was tested on PHP 7, production server, and Linux
if (!is_dir('path_directory')) {
#mkdir('path_directory');
}
We can create folder using mkdir. Also we can set permission for it.
Value Permission
0 cannot read, write or execute
1 can only execute
2 can only write
3 can write and execute
4 can only read
5 can read and execute
6 can read and write
7 can read, write and execute
<?PHP
// Making a directory with the provision
// of all permissions to the owner and
// the owner's user group
mkdir("/documents/post/", 0770, true)
?>
As a complement to current solutions, a utility function.
function createDir($path, $mode = 0777, $recursive = true) {
if(file_exists($path)) return true;
return mkdir($path, $mode, $recursive);
}
createDir('path/to/directory');
It returns true if already exists or successfully created. Else it returns false.
We should always modularise our code and I've written the same check it below...
We first check the directory. If the directory is absent, we create the directory.
$boolDirPresents = $this->CheckDir($DirectoryName);
if (!$boolDirPresents) {
$boolCreateDirectory = $this->CreateDirectory($DirectoryName);
if ($boolCreateDirectory) {
echo "Created successfully";
}
}
function CheckDir($DirName) {
if (file_exists($DirName)) {
echo "Dir Exists<br>";
return true;
} else {
echo "Dir Not Absent<br>";
return false;
}
}
function CreateDirectory($DirName) {
if (mkdir($DirName, 0777)) {
return true;
} else {
return false;
}
}
You first need to check if directory exists file_exists('path_to_directory')
Then use mkdir(path_to_directory) to create a directory
mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
More about mkdir() here
Full code here:
$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
mkdir($structure);
}

PHP: How to check if image file exists?

I need to see if a specific image exists on my cdn.
I've tried the following and it doesn't work:
if (file_exists(http://www.example.com/images/$filename)) {
echo "The file exists";
} else {
echo "The file does not exist";
}
Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...
You need the filename in quotation marks at least (as string):
if (file_exists('http://www.mydomain.com/images/'.$filename)) {
… }
Also, make sure $filename is properly validated. And then, it will only work when allow_url_fopen is activated in your PHP config
if (file_exists('http://www.mydomain.com/images/'.$filename)) {}
This didn't work for me. The way I did it was using getimagesize.
$src = 'http://www.mydomain.com/images/'.$filename;
if (#getimagesize($src)) {
Note that the '#' will mean that if the image does not exist (in which case the function would usually throw an error: getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed) it will return false.
Try like this:
$file = '/path/to/foo.txt'; // 'images/'.$file (physical path)
if (file_exists($file)) {
echo "The file $file exists";
} else {
echo "The file $file does not exist";
}
Well, file_exists does not say if a file exists, it says if a path exists. ⚡⚡⚡⚡⚡⚡⚡
So, to check if it is a file then you should use is_file together with file_exists to know if there is really a file behind the path, otherwise file_exists will return true for any existing path.
Here is the function i use :
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}
Here is the simplest way to check if a file exist:
if(is_file($filename)){
return true; //the file exist
}else{
return false; //the file does not exist
}
A thing you have to understand first: you have no files.
A file is a subject of a filesystem, but you are making your request using HTTP protocol which supports no files but URLs.
So, you have to request an unexisting file using your browser and see the response code. if it's not 404, you are unable to use any wrappers to see if a file exists and you have to request your cdn using some other protocol, FTP for example
If the file is on your local domain, you don't need to put the full URL. Only the path to the file. If the file is in a different directory, then you need to preface the path with "."
$file = './images/image.jpg';
if (file_exists($file)) {}
Often times the "." is left off which will cause the file to be shown as not existing, when it in fact does.
public static function is_file_url_exists($url) {
if (#file_get_contents($url, 0, NULL, 0, 1)) {
return 1;
}
return 0;
}
There is a major difference between is_file and file_exists.
is_file returns true for (regular) files:
Returns TRUE if the filename exists and is a regular file, FALSE otherwise.
file_exists returns true for both files and directories:
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
Note: Check also this stackoverflow question for more information on this topic.
You have to use absolute path to see if the file exists.
$abs_path = '/var/www/example.com/public_html/images/';
$file_url = 'http://www.example.com/images/' . $filename;
if (file_exists($abs_path . $filename)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
If you are writing for CMS or PHP framework then as far as I know all of them have defined constant for document root path.
e.g WordPress uses ABSPATH which can be used globally for working with files on the server using your code as well as site url.
Wordpress example:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
if (file_exists($image_path)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
I'm going an extra mile here :). Because this code would no need much maintenance and pretty solid, I would write it with as shorthand if statement:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
echo (file_exists($image_path))?'The file exists. URL:' . $file_url:'The file does not exist';
Shorthand IF statement explained:
$stringVariable = ($trueOrFalseComaprison > 0)?'String if true':'String if false';
you can use cURL. You can get cURL to only give you the headers, and not the body, which might make it faster. A bad domain could always take a while because you will be waiting for the request to time-out; you could probably change the timeout length using cURL.
Here is example:
function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
$exists = remoteFileExists('http://stackoverflow.com/favicon.ico');
if ($exists) {
echo 'file exists';
} else {
echo 'file does not exist';
}
You can use the file_get_contents function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.
If you are using curl, you can try the following script:
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
Reference URL: https://hungred.com/how-to/php-check-remote-email-url-image-link-exist/
try this :
if (file_exists(FCPATH . 'uploads/pages/' . $image)) {
unlink(FCPATH . 'uploads/pages/' . $image);
}
If path to your image is relative to the application root it is better to use something like this:
function imgExists($path) {
$serverPath = $_SERVER['DOCUMENT_ROOT'] . $path;
return is_file($serverPath)
&& file_exists($serverPath);
}
Usage example for this function:
$path = '/tmp/teacher_photos/1546595125-IMG_14112018_160116_0.png';
$exists = imgExists($path);
if ($exists) {
var_dump('Image exists. Do something...');
}
I think it is good idea to create something like library to check image existence applicable for different situations. Above lots of great answers you can use to solve this task.
Here is one function that I use to check any kind of URL. It will check response code is URL exists or not.
/*
* Check is URL exists
*
* #param $url Some URL
* #param $strict You can add it true to check only HTTP 200 Response code
* or you can add some custom response code like 302, 304 etc.
*
* #return string or NULL
*/
function is_url_exists($url, $strict = false)
{
if (is_int($strict) && $strict >= 100 && $strict < 600 || is_array($strict)) {
if(is_array($strict)) {
$response = $strict;
} else {
$response = [$strict];
}
} else if ($strict === true || $strict === 1) {
$response = [200];
} else {
$response = [200,202,301,302,303];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
if (!curl_errno($ch) && $return !== false) {
return ( in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), $response) !== false );
}
return false;
}
This is exactly what you need.
Read first 5 bytes form HTTP using fopen() and fread() then use this:
DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10));
to detect image.
file_exists reads not only files, but also paths. so when $filename is empty, the command would run as if it's written like this:
file_exists("http://www.example.com/images/")
if the directory /images/ exists, the function will still return true.
I usually write it like this:
// !empty($filename) is to prevent an error when the variable is not defined
if (!empty($filename) && file_exists("http://www.example.com/images/$filename"))
{
// do something
}
else
{
// do other things
}
file_exists($filepath) will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed.
is_file($filepath) will only return true for fully filepaths
you need server path with file_exists
for example
if (file_exists('/httpdocs/images/'.$filename)) {echo 'File exist'; }
if(#getimagesize($image_path)){
...}
Is working for me.
Try it:
$imgFile = 'http://www.yourdomain.com/images/'.$fileName;
if (is_file($imgFile) && file_exists($imgFile)) {
echo 'File exists';
} else {
echo 'File not exist';
}
Another Way:
$imgFile = 'http://www.yourdomain.com/images/'.$fileName;
if (is_file($imgFile)) {.....
}

How do I check if a directory exists? "is_dir", "file_exists" or both?

I want to create a directory if it does not exist already.
Is using the is_dir function enough for that purpose?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
Or should I combine is_dir with file_exists?
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.
$filename = "/folder/" . $dirname . "/";
if (file_exists($filename)) {
echo "The directory $dirname exists.";
} else {
mkdir("folder/" . $dirname, 0755);
echo "The directory $dirname was successfully created.";
exit;
}
I think realpath() may be the best way to validate if a path exist
http://www.php.net/realpath
Here is an example function:
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (long version)
* #param string $folder the path being checked.
* #return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
if($path !== false AND is_dir($path))
{
// Return canonicalized absolute pathname
return $path;
}
// Path/folder does not exist
return false;
}
Short version of the same function
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (sort version)
* #param string $folder the path being checked.
* #return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
Output examples
<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input); // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output); // bool(false)
/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input); // string(5) "/home"
var_dump($output); // string(5) "/home"
/** CASE 3 **/
$input = '/home/..';
var_dump($input); // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output); // string(1) "/"
Usage
<?php
$folder = '/foo/bar';
if(FALSE !== ($path = folder_exist($folder)))
{
die('Folder ' . $path . ' already exist');
}
mkdir($folder);
// Continue do stuff
Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error "failed to open stream: No such file or directory" will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists() and is_dir() at the same time, for ex.:
if (file_exists('file')) {
if (!is_dir('file')) { //if file is already present, but it's not a dir
//do something with file - delete, rename, etc.
unlink('file'); //for example
mkdir('file', NEEDED_ACCESS_LEVEL);
}
} else { //no file exists with this name
mkdir('file', NEEDED_ACCESS_LEVEL);
}
I had the same doubt, but see the PHP docu:
https://www.php.net/manual/en/function.file-exists.php
https://www.php.net/manual/en/function.is-dir.php
You will see that is_dir() has both properties.
Return Values is_dir
Returns TRUE if the filename exists and is a directory, FALSE otherwise.
$year = date("Y");
$month = date("m");
$filename = "../".$year;
$filename2 = "../".$year."/".$month;
if(file_exists($filename)){
if(file_exists($filename2)==false){
mkdir($filename2,0777);
}
}else{
mkdir($filename,0777);
}
$save_folder = "some/path/" . date('dmy');
if (!file_exists($save_folder)) {
mkdir($save_folder, 0777);
}
This is an old, but still topical question. Just test with the is_dir() or file_exists() function for the presence of the . or .. file in the directory under test. Each directory must contain these files:
is_dir("path_to_directory/.");
Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false). It is slower but kills two birds in one shot.
Another option is to simply ignore the E_WARNING, not by using #mkdir(...); (because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
This is how I do
if(is_dir("./folder/test"))
{
echo "Exist";
}else{
echo "Not exist";
}
A way to check if a path is directory can be following:
function isDirectory($path) {
$all = #scandir($path);
return $all !== false;
}
NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows
i think this is fast solution for dir check.
$path = realpath($Newfolder);
if (!empty($path)){
echo "1";
}else{
echo "0";
}

Create a folder if it doesn't already exist

I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.
Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.
So I need to add code to my theme that checks for the folder and creates it otherwise.
Try this, using mkdir:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Note that 0777 is already the default mode for directories and may still be modified by the current umask.
Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:
mkdir('path/to/directory', 0755, true);
Here is something a bit more universal since this comes up on Google. While the details are more specific, the title of this question is more universal.
/**
* recursively create a long directory path
*/
function createPath($path) {
if (is_dir($path))
return true;
$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
$return = createPath($prev_path);
return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}
This will take a path, possibly with a long chain of uncreated directories, and keep going up one directory until it gets to an existing directory. Then it will attempt to create the next directory in that directory, and continue till it's created all the directories. It returns true if successful.
It could be improved by providing a stopping level so it just fails if it goes beyond the user folder or something and by including permissions.
Use a helper function like this:
function makeDir($path)
{
$ret = mkdir($path); // use #mkdir if you want to suppress warnings/errors
return $ret === true || is_dir($path);
}
It will return true if the directory was successfully created or already exists, and false if the directory couldn't be created.
A better alternative is this (shouldn't give any warnings):
function makeDir($path)
{
return is_dir($path) || mkdir($path);
}
A faster way to create a folder:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Recursively create the directory path:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
Inspired by Python's os.makedirs()
The best way is to use the wp_mkdir_p function. This function will recursively create a folder with the correct permissions.
Also, you can skip folder exists condition because the function returns:
true when the directory was created or existed before
false if you can't create the directory.
Example:
$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
// Directory exists or was created.
}
More: https://developer.wordpress.org/reference/functions/wp_mkdir_p/
Within WordPress, there's also the very handy function wp_mkdir_p which will recursively create a directory structure.
Source for reference:
function wp_mkdir_p( $target ) {
$wrapper = null;
// Strip the protocol
if( wp_is_stream( $target ) ) {
list( $wrapper, $target ) = explode( '://', $target, 2 );
}
// From php.net/mkdir user contributed notes
$target = str_replace( '//', '/', $target );
// Put the wrapper back on the target
if( $wrapper !== null ) {
$target = $wrapper . '://' . $target;
}
// Safe mode fails with a trailing slash under certain PHP versions.
$target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
if ( empty($target) )
$target = '/';
if ( file_exists( $target ) )
return #is_dir( $target );
// We need to find the permissions of the parent folder that exists and inherit that.
$target_parent = dirname( $target );
while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
$target_parent = dirname( $target_parent );
}
// Get the permission bits.
if ( $stat = #stat( $target_parent ) ) {
$dir_perms = $stat['mode'] & 0007777;
} else {
$dir_perms = 0777;
}
if ( #mkdir( $target, $dir_perms, true ) ) {
// If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
$folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
#chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
}
}
return true;
}
return false;
}
I needed the same thing for a login site. I needed to create a directory with two variables.
The $directory is the main folder where I wanted to create another sub-folder with the users license number.
include_once("../include/session.php");
$lnum = $session->lnum; // Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in
if (!file_exists($directory . "/" . $lnum)) {
mkdir($directory . "/" . $lnum, 0777, true);
}
This is the most up-to-date solution without error suppression:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory');
}
For your specific question about WordPress, use the following code:
if (!is_dir(ABSPATH . 'wp-content/uploads')) wp_mkdir_p(ABSPATH . 'wp-content/uploads');
Function Reference: WordPress wp_mkdir_p. ABSPATH is the constant that returns WordPress working directory path.
There is another WordPress function named wp_upload_dir(). It returns the upload directory path and creates a folder if doesn't already exists.
$upload_path = wp_upload_dir();
The following code is for PHP in general.
if (!is_dir('path/to/directory')) mkdir('path/to/directory', 0777, true);
Function reference: PHP is_dir()
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
Here you go.
if (!is_dir('path/to/directory')) {
if (!mkdir('path/to/directory', 0777, true) && !is_dir('path/to/directory')) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', 'path/to/directory'));
}
}
You can try also:
$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);
If you want to avoid the file_exists vs. is_dir problem, I would suggest you to look here.
I tried this and it only creates the directory if the directory does not exist. It does not care if there is a file with that name.
/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
mkdir($path_to_directory, 0777, true);
}
To create a folder if it doesn't already exist
Considering the question's environment.
WordPress.
Webhosting server.
Assuming it's Linux, not Windows running PHP.
And quoting from: mkdir
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive =
FALSE [, resource $context ]]] )
The manual says that the only required parameter is the $pathname!
So, we can simply code:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// Todo
}
?>
Explanation:
We don't have to pass any parameter or check if the folder exists or even pass the mode parameter unless needed; for the following reasons:
The command will create the folder with 0755 permission (the shared hosting folder's default permission) or 0777, the command's default.
mode is ignored on Windows hosting running PHP.
Already the mkdir command has a built-in checker for if the folder exists; so we need to check the return only True|False ; and it’s not an error; it’s a warning only, and Warning is disabled on the hosting servers by default.
As per speed, this is faster if warning disabled.
This is just another way to look into the question and not claiming a better or most optimal solution.
It was tested on PHP 7, production server, and Linux
if (!is_dir('path_directory')) {
#mkdir('path_directory');
}
We can create folder using mkdir. Also we can set permission for it.
Value Permission
0 cannot read, write or execute
1 can only execute
2 can only write
3 can write and execute
4 can only read
5 can read and execute
6 can read and write
7 can read, write and execute
<?PHP
// Making a directory with the provision
// of all permissions to the owner and
// the owner's user group
mkdir("/documents/post/", 0770, true)
?>
As a complement to current solutions, a utility function.
function createDir($path, $mode = 0777, $recursive = true) {
if(file_exists($path)) return true;
return mkdir($path, $mode, $recursive);
}
createDir('path/to/directory');
It returns true if already exists or successfully created. Else it returns false.
We should always modularise our code and I've written the same check it below...
We first check the directory. If the directory is absent, we create the directory.
$boolDirPresents = $this->CheckDir($DirectoryName);
if (!$boolDirPresents) {
$boolCreateDirectory = $this->CreateDirectory($DirectoryName);
if ($boolCreateDirectory) {
echo "Created successfully";
}
}
function CheckDir($DirName) {
if (file_exists($DirName)) {
echo "Dir Exists<br>";
return true;
} else {
echo "Dir Not Absent<br>";
return false;
}
}
function CreateDirectory($DirName) {
if (mkdir($DirName, 0777)) {
return true;
} else {
return false;
}
}
You first need to check if directory exists file_exists('path_to_directory')
Then use mkdir(path_to_directory) to create a directory
mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
More about mkdir() here
Full code here:
$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
mkdir($structure);
}

How to test if a directory already exist in PHP?

How can i test if a directory already exist and if not create one in PHP?
Try this:
$filename = "/tmp";
if (!file_exists($filename))
echo $filename, " does not exist";
elseif (!is_dir($filename))
echo $filename, " is not a directory";
else
echo "Directory ", $filename, " already exists";
file_exists checks if the path/file exists and is_dir checks whether the given filename is a directory.
Edit:
to create the directory afterwards, call
mkdir($filename);
To expand on the answer above based on the questioner's comments:
$filename = "/tmp";
if (!is_dir($filename)) {
mkdir($filename);
}
You need to use mkdir() to actually make the directory.
Try this:
$dir = "/path/to/dir";
if(is_dir($dir) == false)
mkdir($dir);
If you want the complete path the be created (if not present), set recusive parameter to true.
See documentation of mkdir for more information.
Use This:
if(file_exists("Directory path") && is_dir("Directory path"))
{
//Your Code;
}

Categories