 SychoSlyScoot the WorldPremium join:2004-01-22 Mount Prospect, IL kudos:1 1 edit | PHP check to see if a folder existsI am creating directories and I want to check if the directory exists before it is created. Here is my code:
<?php
$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.";
}
?>
Everytime I run the code I get the following error:
Parse error: syntax error, unexpected T_IF, expecting ',' or ';' in /home/kompute1/public_html/sychosly.com/pix/step2.php on line 18
Can anyone please help. I am ne to PHP and am learning as I go.
-- ~Sly
---
"You don't have the guts to be who you want to be!" |
|
 usa2kBlessedPremium,MVM join:2003-01-26 Redford, MI kudos:3 | I don't think $dirname needs to be in quotes on several lines. |
|
 | reply to SychoSly As mentioned, variables shouldn't be in quotes. There's also an easier way to use variables in a string, use curlys:
<?php
$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.";
}
?>
Also, for simple strings it's better to use single quotes. Double quotes are only needed when you have things like escape codes in the string. |
|
 SychoSlyScoot the WorldPremium join:2004-01-22 Mount Prospect, IL kudos:1 1 edit | So now the script runs, thank you very much.
I am now having a different problem. When I run the script now and I create a directory that doesn't exist. I get the "The directory mydirectory was successfully created", so it seems like the "if" part of the loop works.
When I go back and I recreate the same directory to see if my loop works I get the PHP error stating that the file exists and then the line stating the directory was successfully created. So it looks like it goes into the else part and it bypasses the "if" part.
I then tried swapping the code in the loop so that the "if" part does creates the directory and then the else part says it is created. I get no directory created. So it seems like the if part is not running only whatever is in the else.
Hope that makes sense. Any ideas? |
|
 usa2kBlessedPremium,MVM join:2003-01-26 Redford, MI kudos:3 1 edit | Re: PHP check to see if a folder exists When you make the dir its in you current directory. Your earlier test was from the root / if using sdgthy's code |
|
 SychoSlyScoot the WorldPremium join:2004-01-22 Mount Prospect, IL kudos:1 1 edit | Thanks for the help. It seems to be working now. |
|