Reputation: 11
I've run into a problem where I need to upload an image into a folder and store its path into database.
If the folder is not present then create the new folder and then store it there and save full path into database.
$file_name=$_FILES["uploadedimage"]["name"];
$temp_name=$_FILES["uploadedimage"]["tmp_name"];
$imgtype=$_FILES["uploadedimage"]["type"];
$ext= GetImageExtension($imgtype);
image name to be used
$imagename=("Userimage")."-".time().$ext;
image path
$target_path = "images/".$imagename
Condition
if(move_uploaded_file($temp_name, $target_path))
{
$query_upload="INSERT into images_tbl (images_path , submission_date) VALUES ('".$target_path."','".date("Y-m-d")."')";
$imagedb= mysqli_query($con,$query_upload);
while($imagepath = mysqli_fetch_array($imagedb))
{
echo "success";
}
}
Upvotes: 0
Views: 108
Reputation: 1325
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
0777 is the directory permission ,that is a creating the directory and setting the permission to 0777 so that file can be uploaded to this directory
Upvotes: 0
Reputation: 507
You could do something like this:
<?php
$target_dir = preg_replace('#^(.*)'.basename($target_path).'$#', '$1', $target_path);
if (!is_dir($target_dir))
mkdir($target_dir, 0755);
if(move_uploaded_file($temp_name, $target_path))
{
$query_upload="INSERT into images_tbl (images_path , submission_date) VALUES ('".$target_path."','".date("Y-m-d")."')";
$imagedb= mysqli_query($con,$query_upload);
while($imagepath = mysqli_fetch_array($imagedb))
{
echo "success";
}
}
?>
The preg_replace part strips the directory path out of the complete path.
Upvotes: 0
Reputation: 436
It's easy:
$target_path = 'images/'.$imagename;
if(!is_dir($target_path)) mkdir($target_path, 0755);
Don't use " " when you can use ' ', because each time you use " .." , php try to find variable inside and lost time for nothing. ;)
Upvotes: 1