Trying to validate a folder being dynamically created using PHP - php

I am trying validate: whether or not the folder I am attempting to create exists. Sure, I get a message... an error message :/ telling me it does! (if it doesn't exist, no error message, and everything goes as planned).
It outputs this error message
Directory exists
Warning: mkdir() [function.mkdir]: File exists in /home/***/public_html/***/formulaires/processForm-test.php on line 75
UPLOADS folder has NOT been created
The current code I use is this one:
$dirPath = $_POST['company'];
if(is_dir($dirPath))
echo 'Directory exists';
else
echo 'directory not exist';
function ftp_directory_exists($ftp, $dirPath)
{
// Get the current working directory
$origin = ftp_pwd($ftp);
// Attempt to change directory, suppress errors
if (#ftp_chdir($ftp, $dirPath))
{
// If the directory exists, set back to origin
ftp_chdir($ftp, $origin);
return true;
}
// Directory does not exist
return false;
}
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo '<br/>'.$dirPath . " has been created".'<br/>';
} else {
echo '<br/>'.$dirPath . " has NOT been created".'<br/>';
}
I added the middle part recently (I don't know if that would even have an impact). The one that starts off with "function ftp_directory_exists($ftp, $dirPath)"

Use file_exists() to check if a file / directory exists:
if(!file_exists('/path/to/your/directory')){
//yay, the directory doesn't exist, continue
}

The function ftp_directory_exists you added won't have any impact on your code as it is never called...
You might tried something like this (not tested...) :
$dirPath = $_POST['company'];
$dirExists = is_dir($dirPath);
if(!dirExists)
$dirExists = mkdir($dirPath, 0755);
echo '<br/>'.$dirPath . (($dirExists)? "" : "DO NOT") . " exists".'<br/>';

Related

php-how to delete files from directory if files already exist?

I tried deleting file if its already existing .
But i ended up with no result.
Can any one help me with this!!!
$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';
if (!file_exists($path_user)) {
if (mkdir( $path_user,0777,false )) {
//
}
}
unlink($path_user);
if(move_uploaded_file($file['tmp_name'],$path_user.$path)){
echo "Your File Successfully Uploaded" . "<br>";
}
Organize your code, try this:
$path = 'filename.ext'; // added reference to filename
$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';
// Create the user folder if missing
if (!file_exists($path_user)) {
mkdir( $path_user,0777,false );
}
// If the user file in existing directory already exist, delete it
else if (file_exists($path_user.$path)) {
unlink($path_user.$path);
}
// Create the new file
if(move_uploaded_file($file['tmp_name'],$path_user.$path)) {
echo"Your File Successfully Uploaded"."<br>";
}
Keep in mind that PHP will not recursively delete the directory contents, you should use a function like this one
Maybe you missing else condition ?? And file_name variable :
$file_name = 'sample.jpg';
$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';
if (!file_exists($path_user.$file_name))
{
if (mkdir( $path_user,0777,false )) {
}
} else {
unlink($path_user.$file_name);
}

php ftp check if folder exists always return error creating folder

can someone please tell me what I'm doing wrong in this code?
if($id != '') {
if(is_dir("../public_html".$tem_pasta['path']."/pics/".$id)) {
echo "pasta já existia";
$destination_file = "../public_html".$tem_pasta['path']."/pics/".$id."/".$myFileName;
} else {
//pasta nao existia
if (ftp_mkdir($conn_id, "../public_html".$tem_pasta['path']."/pics/".$id)) {
$destination_file = "../public_html".$tem_pasta['path']."/pics/".$id."/".$myFileName;
//echo "pasta criada<br>";
} else {
echo "erro, não criou a pasta<br>";
}
}
} else {
$destination_file = "../public_html".$tem_pasta['path']."/pics/".$myFileName;
}
it checks if I've a folder ($id) within my pics directory, and if not the script creates a new one.
works good, but if I try to upload another file to the previous created folder it does return an error, saying it didn't create the folder...
thanks
I don't think you can use is_dir on a FTP resource, what you should do is check if the size of the dir/file is -1 with ftp_size.
Because I think what now happens is: you are trying to make the same folder again, and this is why a error occurs.
Edit:
Or check with ftp_chdir!
<?php
function ftp_directory_exists($ftp, $dir)
{
// Get the current working directory
$origin = ftp_pwd($ftp);
// Attempt to change directory, suppress errors
if (#ftp_chdir($ftp, $dir))
{
// If the directory exists, set back to origin
ftp_chdir($ftp, $origin);
return true;
}
// Directory does not exist
return false;
}
?>
Should work!
is_dir works only on the local file-system. If you want to check if a ftp-directory already exists try this:
function ftp_is_dir($ftp, $dir)
{
$pushd = ftp_pwd($ftp);
if ($pushd !== false && #ftp_chdir($ftp, $dir))
{
ftp_chdir($ftp, $pushd);
return true;
}
return false;
}
if($id != '') {
if(ftp_is_dir($conn_id, "../public_html".$tem_pasta['path']."/pics/".$id)) {
// and so on...
Use ftp_nlist and in_array
$ftp_files = #ftp_nlist($this->connection, $directory);
if ($ftp_files === false) {
throw new Exception('Unable to list files. Check directory exists: ' . $directory);
}
if (!in_array($directory, $ftp_files)) {
$ftp_mkdir = #ftp_mkdir($this->connection, $directory);
if ($ftp_mkdir === false) {
throw new Exception('Unable to create directory: ' . $directory);
}
}
With PHP 8.0 (on AWS) the solution with #ftp_chdir() does not hide the error and causes the program to stop. The solution with ftp_nlist() doesn't give good results because it returns either false if the path doesn't exist or an element if the path is a file or a list if it's a directory but doesn't give the "." and ".." elements that would identify a directory.
The ftp_mlsd() function seemed more convenient: it returns a list, possibly empty, only if the path is a directory, false otherwise. But it doesn't work correctly on all servers!
Finally it is the ftp_rawlist() function which seems to be the most generalized because it launches a LIST command on the server and returns the result. If the path is a directory we have an array, possibly empty and we have the value false if it is not a directory.
$list = ftp_rawlist( $ftp_conn, $remote_path );
$is_dir = is_array( $list );

PHP Fix Needed on How to Bypass mkdir if Folder Already Exists

I have a PHP file which creates a unique directory for each user when a file is uploaded. I would like the script to check and see if the directory already exists and if so then skip the mkdir action. Here is my code sample:
<?php
$thisdir = getcwd();
$new_dir = "123";
$full_dir = $thisdir . "/upload/" . $new_dir;
if(mkdir($full_dir, 0777))
{
echo "Directory has been created successfully... <br>";
}
else
{
echo "Failed to create directory...";
}
?>
To continue this example, please assume that the folder "123" already exists. How do I modify it for this case? I am thinking it must be some sort of if...else statement. Thanks for going through this issue.
Use is_dir() to find out whether the folder already exists.
function maybe_mkdir($path, $mode) {
if(is_dir($path)) {
return TRUE;
} else {
return mkdir($path, $mode);
}
}

No error when creating zip, but it doesn't get created

I wrote this code to create a ZIP file and to save it. But somehow it just doesn't show any error, but it doesn't create a ZIP file either. Here's the code:
$zip = new ZipArchive;
$time = microtime(true);
$res = $zip->open("maps/zips/test_" . $time . ".zip", ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
What am I doing wrong, and how can I fix it?
Probably apache or php has not got permissions to create zip archives in that directory. From one of the comments on ZipArchice::open:
If the directory you are writing or
saving into does not have the correct
permissions set, you won't get any
error messages and it will look like
everything worked fine... except it
won't have changed!
Instead make sure you collect the
return value of ZipArchive::close().
If it is false... it didn't work.
Add an else clause to your if statement and dump $res to see the results:
if($res === TRUE) {
...
} else {
var_dump($res);
}
There are 2 cases when zip doesn't generate the error.
Make sure every file you are adding to the zip is valid. Even if
one file is not available when zip->close is called then the archive
will fail and your zip file won't be created.
If your folder doesn't
have write permissions zip will not report the error. It will finish
but nothing will be created.
I had an exactly same issue, even when with full writing/reading permissions.
Solved by creating the ".zip" file manually before passing it to ZipArchive:
$zip = new ZipArchive;
$time = microtime(true);
$path = "maps/zips/test_" . $time . ".zip"
touch($path); //<--- this line creates the file
$res = $zip->open($path, ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
Check out that each of your file exists before calling $zip->addFile otherwise the zip won't be generated and no error message will be displayed.
if(file_exists($fichier->url))
{
if($zip->addFile($fichier->url,$fichier->nom))
{
$erreur_ouverture = false;
}
else
{
$erreur_ouverture = true;
echo 'Open error : '.$fichier->url;
}
}
else
{
echo 'File '.$fichier->url.' not found';
}
break it into steps.
if ($res === TRUE) {
check if file_exist
check if addFile give any error
}
if($zip->close())
{
$zip_created = true;
echo "FILE ADDED!"
}
Check the phpinfo for zip is enabled or not :)
One of the reasons for zip file is not created is due to missing check if you are adding file and not a directory.
if (!$file->isDir())
I found the solution here.

can someone help me fix my code?

I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol
Ol, sorry stackoverflow is a new thing for me. Not sure how to think of it. As a forum or a place to post a question... hmmm, I'm sorry for being rude with my method of asking.
I was wondering i you could give me some guidance on how to properly insert directory structures with how i written this code. I wasn't sure how to tell the PHP where to upload my files and whatnot, I got some help from a friend who helped me sort out some of my bugs, but I'm still lost with dealing with the mkdir and link, unlink functions. Is this how I am suppose to refer to my diretories?
I know php 5.3 uses the _ DIR _ and php 5.0 use dirname(_ _ FILE_ _), I have tried both and I get the same errors. My files are set to 0777 for testing purposes. What could be the problem with it now wanting to write and move my uploaded file?
} elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {
$errors['img_fileexists'] = true;
}
if (! empty($errors)) {
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
// Create thumbnail
if (empty($errors)) {
// Make directory if it doesn't exist
if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
$folders = explode("\\", $dir);
// Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
$dirTmp = '';
foreach ($folders as $fldr) {
if ($dirTmp != '') { $dirTmp .= "\\"; }
$dirTmp .= $fldr;
mkdir("\\".$dirTmp); //ignoring errors deliberately!
}
// Check again whether it exists
if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
}
}
if (empty($errors)) {
// Move uploaded file to final destination
if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
$errors['move_source'] = true;
unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
} else {
// Create thumbnail in new dir
if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
$errors['thumb'] = true;
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
}
}
}
}
// Record in database
if (empty($errors)) {
// Find existing record and delete existing images
$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
$numResults = mysql_num_rows($result);
if ($numResults == 1) {
$row = mysql_fetch_assoc($result);
// Delete old files
unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
}
// Update/create record with new images
if ($numResults == 1) {
$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
} else {
$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
}
$result = mysql_query($sql);
if (!$result) {
unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
}
}
// Print success message and how the thumbnail image created
if (empty($errors)) {
echo "<p>Thumbnail created Successfully!</p>\n";
echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
echo "<br />\n";
}
}
I get the following errors:
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
One way is to check from within your code whether a certain command/function is available for use. You can use the function_exists function for that eg:
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set("GMT");
}
else
{
echo 'date_default_timezone_set is not supported....';
}
Ahh! I'm sorry, didn't mean to vent my frustration on you guys. But I have been at this for hours now it seems.
Like i mentioned this code works but since my server is picky I can't user the 5.3 syntax I coded. This is my attempt to make it work on the 5.0 php my server has.
In particular I think there is something wrong with the mkdir() and the unlink() functions.
if you go to www.helixagent.com log in with test/test then in the url go to /upload2.php then you will see the errors its throwing at me.
well, it works perfect if i use 5.3 and DIR but since I'm on 5.0 i tried a different method
the errors i get are
Warning: move_uploaded_file(./uploads/saiyanz2k/images/banner/azumanga-wall.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/phpVoIEQj' to './uploads/saiyanz2k/images/banner/azumanga-wall.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php on line 112
It looks like you don't have access to the folder (or file)
/uploads/$username/images/banner/$filename
which could be because of a basedir restriction on the host (e.g. you may not leve the parent directory /services/webdata/) or just a missing permission in the os.
Try to (temporary) set permission of /uploads/ to 777 or execute the script from console to see if you have a basedir restriction.
Take a closer look at the paths in the error messages:
./uploads/saiyanz2k/images/banner/azumanga-wall.jpg
/services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload2.php
The destination is a relative path, most likely relative to upload2.php's directory. The one relative path I see is the line:
// Take directory and break it down into folders
$dir = "uploads\\{$username}\\images\\banner\\thumbs";
Which should probably be:
// Take directory and break it down into folders
$dir = "\\uploads\\{$username}\\images\\banner\\thumbs";
Actually, it should be
$dir = "/uploads/{$username}/images/banner/thumbs";
since PHP supports using a forward slash as directory separator on all platforms, while the backslash is only supported on MS platforms.

Categories