Error shown even if directory already exists - php

I am making a intranet customer manager in PHP. For each customer a directory is created for the shop to add files into. What my script is supposed do is if no directory exists create it, if it does exists dont create it.
What is actually happening is if the directory already exists I am getting the following error :
Warning: mkdir() [function.mkdir]: File exists in C:\server2go\server2go\htdocs\customermgr\administrator\components\com_chronoforms\form_actions\custo m_code\custom_code.php(18) : eval()'d code on line 14
So what is happening it is trying to create it anyway, even though the if statement should stop it ?, im confused on what I am doing wrong :-S .
<?php
$customerID = $_GET['cfid'];
$directory = "/customer-files/$customerID";
if(file_exists($directory) && is_dir($directory)) {
}
else {
$thisdir = getcwd();
mkdir($thisdir ."/customer-files/$customerID" , 0777); }
?>

Replace:
if(file_exists($directory) && is_dir($directory)) {
with:
$thisdir = getcwd();
if(file_exists($thisdir.$directory) && is_dir($thisdir.$directory)) {
or better:
<?php
$customerID = $_GET['cfid'];
$directory = "./customer-files/$customerID";
if(file_exists($directory) && is_dir($directory)) {
}
else {
mkdir($directory , 0777); }
?>

Just took a short look but i would try this:
$directory = $thisdir . "/customer-files/$customerID";
and remove $thisdir from mkdir();
also you should move your $thisdir before the $directory declaration

The function file_exists() does not use relative paths, where is_dir() can. So instead, use the common denominator and pass an absolute path to these functions. Additionally you can move the call to getcwd() into the $directory assignment and reuse $directory later for creating the directory.
<?php
$customerID = $_GET['cfid'];
// Get full path to directory
$directory = getcwd() . "/customer-files/$customerID";
if(file_exists($directory) && is_dir($directory)) {
// Do nothing
}
else {
// Directory doesn't exist, make it
mkdir($directory , 0777); }
}
?>

Related

Having an issue with the fopen() php function

I have a users directory and a child directory for the login/register system. I have a file, testing.php, to try to figure out how to create a directory in the users directory AND create a PHP file within that same directory. Here's my code:
<?php
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = "../" . "ActivationFile";
fopen("$file", "w");
?>
I'm able to get mdkir($directory) to work, but not the fopen("$file", "w").
Try this, this should normally solve your problem.
PHP delivers some functions to manipulate folder & path, it's recommended to use them.
For example to get the current parent folder, you can use dirname function.
$directoryname = dirname(dirname(__FILE__)) . "/SomeDirectory";
if (!is_dir($directoryname)) {
mkdir($directoryname);
}
$file = "ActivationFile";
$handle = fopen($directoryname . '/' . $file, "w");
fputs($handle, 'Your data');
fclose($handle);
This line is equivalent to "../SomeDirectory"
dirname(dirname(__FILE__)) . "/SomeDirectory";
So when you open the file, you open "../SomeDirectory/ActivationFile"
fopen($directoryname . '/' . $file, "w");
You can use the function touch() in order to create a file:
If the file does not exist, it will be created.
You also forgot to re-use $directory when specifying the filepath, so the file was not created in the new directory.
As reported by Fred -ii- in a comment, error reporting should also be enabled. Here is the code with these changes:
<?php
// Enable error output, source: http://php.net/manual/en/function.error-reporting.php#85096
error_reporting(E_ALL);
ini_set("display_errors", 1);
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = $directory . "/ActivationFile";
touch($file);
try this:
$dirname = $_POST["DirectoryName"];
$filename = "/folder/{$dirname}/";
if (file_exists($filename)) {
echo "The directory {$dirname} exists";
} else {
mkdir("folder/{$dirname}", 0777);
echo "The directory {$dirname} was successfully created.";
}

PHP creating a folder with the right path

<?php
if (isset($_POST['filename']) && isset($_POST['editorpassword']) && isset($_POST['roomname'])) {
$dir = $_POST['filename']; // This must match the "name" of your input
$path = "evo/" . $dir;
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
}
?>
I have this script where I'm trying to create a new folder. The script itself is ran inside of a folder called /evo and by using this code, it creates the folder in there. Where it needs to go is ../../creative however even if I try and use
$path = "./rooms/creative/" . $dir;
or something to that effect it creates it with the base folder as evo so it appears at:
../evo/rooms/creative (creating the folders that don't exist there with it as it should)
I'm just unsure what to write in for the path on where I need it created to find the right location.
Simplest solution is to remove the "evo" in $path = "evo/" . $dir;

Warning: opendir(): The system cannot find the file specified. (code: 2)

I'm trying to turn the files in my 'objects' directory into an array, then use them to load the objects. But, for some reason, I continue to get this error
Warning: opendir(C:\xampp\htdocs/objects,C:\xampp\htdocs/objects): The system cannot find the file specified. (code: 2)
here is the code:
public function loadObjects(){
$files = array();
if ($handle = opendir(APP_PATH . 'objects'))
{
while (false !== ($entry = readdir($handle)))
{
if ($entry != "." && $entry != "..")
{
$files[] = $entry;
}
}
}
closedir($handle);
if(is_array($files) && count($files) > 0)
{
foreach($files as $value)
{
require_once(APP_PATH . 'objects/' . $value);
$value = stristr($value, '.', true);
self::$objects[$value] = new $object(self::$instance);
}
}
}
I know this is an old question but for any future viewers I will post an anwser just in case.
This type of error usually comes from a simple oversight. When developing most aplication the developer usualy uses a path like
http://localhost/myAppHome
or
http://96.82.102.233/myAppHome(if on remote server)
In this perticular case the APP_PATH is probably defined somethig like that:
define('APP_PATH',$_SERVER['DOCUMENT_ROOT']);
This will be wrong in every case when the app is being developed outside of a domain name.
$_SERVER['DOCUMENT_ROOT'] will resolve to the root of domain which in this case will be
http://localhost or http://96.82.102.233
The main directory for localhost or the IP address is going to be the diretory root of the server itself => drive:/xampp/htdocs (for example)
Basically to avoid this issue you should always mind not to ask for 'DOCUMENT_ROOT' when developing without a domain pointing to you app.
If you dont require reqular deploys you can just add the missing folder to the definition like so :
define('APP_PATH',$_SERVER['DOCUMENT_ROOT'].'/myAppHome');
In case you deploy on reqular basis and you are afraid you will forget to rever this change before depoying you can always insert an IF when defing APP_PATH like:
if($_SERVER['SERVER_NAME']=='localhost'){
define('APP_PATH', $_SERVER['DOCUMENT_ROOT'].'/myAppHome');
}else{
define('APP_PATH', $_SERVER['DOCUMENT_ROOT']);
}
You are trying to open that directory with a "/".
Try to replace:
C:\xampp\htdocs/objects
to
C:\xampp\htdocs\objects
Please be sure APP_PATH variable is not null and correct values. There is no scandir function usage on your codes.
After that, i suggest you to use DirectoryIterator.
http://www.php.net/manual/en/class.directoryiterator.php
Complete example:
http://fabien.potencier.org/article/43/find-your-files
APP_HOST = DIR folder;
APP_PATH = APP_PATH + DIR folder;
Example = "C:/xampp/htdocs" + "/parent/child/index.php"
if ($_SERVER['SERVER_NAME'] == "localhost") {
define('APP_HOST', pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME));
define('APP_PATH', $_SERVER['DOCUMENT_ROOT'] . APP_HOST);
} else {
define('APP_PATH', $_SERVER['DOCUMENT_ROOT']);
}

List Directories like wamp page in PHP

I am looking for a way to list the names of every folder in a directory and their path in PHP
Thank you
What you are referring to is not a page from WAMPP, it is a default setting to show files and folders on any (if not most) web servers... This is usually switched off by the web server config, or .htaccess files
You are looking for some PHP code to do a similar thing, the following PHP functions are what you will need to look into, read the pages and view the examples to understand how to use them... Do not ignore "Warning" or "Important" messages on these pages from php.net:
opendir - Creates a handle to a directory for reading
readdir - Reads files/folders inside a dir
rmdir - Deletes a folder (must be empty)
mkdir - Creates a folder
Here is an example:
<?php
$folder = "myfolder";
if ($dhandle = opendir($folder)) {
while ($file = readdir($dhandle)) {
// Ignore . and ..
if ($file<>'.' && $file<>'..')
// if it's a folder, echo [F]
if (is_dir("$folder/$file")) echo "[F] $file<br>"; else
echo "$file<br>";
}
closedir($dhandle);
}
?>
Important
Remember that on a linux OS, your Apache/PHP must have access to the folder in question before it can write/delete files and folders... Read up on chmod, chown and chgrp
use the following function to get the path of the files/folders
<?php
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
getDirectory( "." );
?>
There is an simple solution to this problem :(if you are using linux only )
you want list the names of every folder in a directory and their path in PHP .
you can use
find
command in conjuction with PHP's
exec();
function
the following snippet shows this
<?php
$startdir = "Some Directory" ; // the start directory whose sub directories along with path is needed
exec("find " . $startdir . " -type d " , $directories); // executes the command and stores the result in array $directory line by line
while(list($index,$dir) = each($directories) ) {
echo $dir."<br/>"; //lists directories one by one
}
?>
foot notes:
command ,
find dirname -type d
lists all the directories and subdirectories under folder startdir
This is a php code save this as index.php and put it in your web root directory.
<?php
$pngFolder = <<< EOFILE
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAA3NCSVQICAjb4U/gAAABhlBMVEX//v7//v3///7//fr//fj+/v3//fb+/fT+/Pf//PX+/Pb+/PP+/PL+/PH+/PD+++/+++7++u/9+vL9+vH79+r79+n79uj89tj89Nf889D88sj78sz78sr58N3u7u7u7ev777j67bL67Kv46sHt6uP26cns6d356aP56aD56Jv45pT45pP45ZD45I324av344r344T14J734oT34YD13pD24Hv03af13pP233X025303JL23nX23nHz2pX23Gvn2a7122fz2I3122T12mLz14Xv1JPy1YD12Vz02Fvy1H7v04T011Py03j011b01k7v0n/x0nHz1Ejv0Hnuz3Xx0Gvz00buzofz00Pxz2juz3Hy0TrmznzmzoHy0Djqy2vtymnxzS3xzi/kyG3jyG7wyyXkwJjpwHLiw2Liw2HhwmDdvlXevVPduVThsX7btDrbsj/gq3DbsDzbrT7brDvaqzjapjrbpTraojnboTrbmzrbmjrbl0Tbljrakz3ajzzZjTfZijLZiTJdVmhqAAAAgnRSTlP///////////////////////////////////////8A////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9XzUpQAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAACqSURBVBiVY5BDAwxECGRlpgNBtpoKCMjLM8jnsYKASFJycnJ0tD1QRT6HromhHj8YMOcABYqEzc3d4uO9vIKCIkULgQIlYq5haao8YMBUDBQoZWIBAnFtAwsHD4kyoEA5l5SCkqa+qZ27X7hkBVCgUkhRXcvI2sk3MCpRugooUCOooWNs4+wdGpuQIlMDFKiWNbO0dXTx9AwICVGuBQqkFtQ1wEB9LhGeAwDSdzMEmZfC0wAAAABJRU5ErkJggg==
EOFILE;
if (isset($_GET['img']))
{
header("Content-type: image/png");
echo base64_decode($pngFolder);
exit();
}
$projectsListIgnore = array ('.','..');
$handle=opendir(".");
$projectContents = '';
while ($file = readdir($handle))
{
if (is_dir($file) && !in_array($file,$projectsListIgnore))
{
$projectContents .= '<li>'.$file.'</li>';
}
}
closedir($handle);
?>
<ul class="projects">
<?php $projectContents ?>
</ul>

php: create directory on form submit?

I am wondering what I am doing wrong. I'm inside of PATH and I want to create a folder inside of PATH. I want to check if the folder already exists and, if not, create one. Getting the name of the folder from an input field with name of "dirname".
if (isset($_POST['createDir'])) {
//get value of inputfield
$dir = $_POST['dirname'];
//set the target path ??
$targetfilename = PATH . '/' . $dir;
if (!file_exists($dir)) {
mkdir($dir); //create the directory
chmod($targetfilename, 0777); //make it writable
}
}
It might be a good idea to make sure that the directory you are handling is indeed a directory. This code works... edit as you please.
define("PATH", "/home/born05/htdocs/swish_s/Swish");
$test = "set";
$_POST["dirname"] = "test";
if (isset($test)) {
//get value of inputfield
$dir = $_POST['dirname'];
//set the target path ??
$targetfilename = PATH . '/' . $dir;
if (!is_file($dir) && !is_dir($dir)) {
mkdir($dir); //create the directory
chmod($targetfilename, 0777); //make it writable
}
else
{
echo "{$dir} exists and is a valid dir";
}
Good luck!
Edited: comment was a good hint ;)
You have to use
!is_dir($dir)
instead of
!file_exists($dir)
it's not a file, it's a directory!
Good luck!
You can use is_dir().
#codeworxx file_exists can be used to check a directory as well..
http://www.php.net/manual/en/function.file-exists.php

Categories