Iain Simpson
Iain Simpson

Reputation: 8131

Error shown even if directory already exists

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); }

    ?>

Upvotes: 0

Views: 142

Answers (3)

Jeremy Harris
Jeremy Harris

Reputation: 24579

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); }
    }

?>

Upvotes: 1

stewe
stewe

Reputation: 42644

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); }

    ?>

Upvotes: 1

Tny
Tny

Reputation: 165

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

Upvotes: 1

Related Questions