Reputation: 129
I want to add image in directory. The directory makes dynamically. But there is an error while uploading the image in directory and image can't upload due to this error the error is given below:
Warning: mkdir(): File exists in C:\wamp\www\test\index.php on line 21
My code is here:
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="filename" id="filename" />
<input type="submit" name="pic" />
</form>
</body>
</html>
<?php
if(isset($_POST['pic'])){
$comimages = $_FILES['filename']['tmp_name'];
$targetpath = mkdir("pageimage/pageid");
$compath = $targetpath."/".$_FILES['filename']['name'];
$comFileType=$_FILES['filename']['type'];
$comFileSize=$_FILES['filename']['size'];
$comFileSize=$comFileSize/1024;
if($comFileSize<1000)
{
$arrFileType=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType,$arrFileType))
{
move_uploaded_file($comimages,$compath);
}
else
{
echo("invalid file format");
}
}
else
{
echo("File Size Error");
}
}
?>
Upvotes: 1
Views: 860
Reputation: 2249
First question : Where is line 21?
Anyway, you have to test if directory exists before creating it. Obviously, it seems to exist already in your case (folders are technically considered files here, see for example is_dir()
). Use file_exists()
.
Also beware that if you create a structure (a folder and a folder inside), you have to use the $recursive
parameter, see PHP doc : http://php.net/manual/fr/function.mkdir.php
Upvotes: 0
Reputation: 36784
Replace
$targetpath = mkdir("pageimage/pageid");
With..
$targetpath = if(is_dir("pageimage/pageid")) ? "pageimage/pageid" : mkdir("pageimage/pageid");
You should check to see whether the folder exists before creating it.
Upvotes: 0
Reputation: 30741
You cant create a directory twice, befor creating the directory check for its existence.
you can use is_dir()
and is_writeable()
to be sure you can write to this directory.
see: http://uk.php.net/manual/en/function.is-writable.php
Upvotes: 0
Reputation: 4844
Replace the
$targetpath = mkdir("pageimage/pageid");
With:
$targetpath = "pageimage/pageid";
if(!is_dir($targetpath)){
mkdir($targetpath);
}
This way you are creating the directory only if it doesn't exist. It's normal the error you get as the directory already existed.
Upvotes: 0
Reputation: 3956
The clue is in the error. The directory you are trying to create with $targetpath = mkdir("pageimage/pageid");
already exists... so you can't make it again!
I would suggest doing a quick file exists check before trying to make it. There is a function for that: file_exists()
Also, mkdir()
returns a boolean (success or fail); not a file directory, so you won't be able to use your $targetpath
variable as you expect.
Try this instead...
$targetpath = "pageimage/pageid";
if (!file_exists($targetpath)) {
mkdir($targetpath);
}
...
Upvotes: 4