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);
}
Related
I want to copy set of uploaded files from one folder to another folder.From the below code, all the files in one folder is copied.It takes much time. I want to copy only the currently uploaded file to another folder.I have some idea to specify the uploaded files and copy using for loop.But I don't know to implement.I am very new to developing.Please help me.Below is the code.
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
To copy only the uploaded files, there is only a slight change in the coding which I have made. That is instead of using "." from one folder, I passed the array value. So that only the files which are uploaded will be copied to the new folder instead of copying everything which takes long time.Below is the only change made to do:
$files = glob("test_uploads/$name_arrray[$i]");
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/>';
I have a zip file containing one folder, that contains more folders and files, like this:
myfile.zip
-firstlevel
--folder1
--folder2
--folder3
--file1
--file2
Now, I want to extract this file using PHPs ZipArchive, but without the "firstlevel" folder. At the moment, the results look like this:
destination/firstlevel/folder1
destination/firstlevel/folder2
...
The result I'd like to have would look like this:
destination/folder1
destination/folder2
...
I've tried extractTo, which produces the first mentioned result, and copy(), as suggested here, but this doesn't seem to work at all.
My current code is here:
if($zip->open('myfile.zip') === true) {
$firstlevel = $zip->getNameIndex(0);
for($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->getNameIndex($i);
$pos = strpos($entry, $firstlevel);
if ($pos !== false) {
$file = substr($entry, strlen($firstlevel));
if(strlen($file) > 0){
$files[] = $file;
}
}
}
//attempt 1 (extractTo):
//$zip->extractTo('./test', $files);
//attempt 2 (copy):
foreach($files as $filename){
copy('zip://'.$firstlevel.'/'.$filename, 'test/'.$filename);
}
}
How can I achieve the result I'm aiming for?
Take a look at my Quick Unzipper script. I wrote this for personal use a while back when uploading large zip files to a server. It was a backup, and 1,000s of files take forever with FTP so using a zip file was faster. I use Git and everything, but there wasn't another option for me. I place this php file in the directory I want the files to go, and put the zip file in the same directory. For my script, they all have to operate in the same directory. It was an easy way to secure it for my needs, as everything I needed was in the same dir.
Quick Unzipper: https://github.com/incomepitbull/QuickUnzipper/blob/master/unzip.php
I linked the file because I am not showcasing the repo, just the code that makes the unzip tick. With modern versions of PHP, there should't be anything that isn't included on your setup. So you shouldn't need to do any server config changes to use this.
Here is the PHP Doc for the ZipArchive class it uses: http://php.net/manual/en/class.ziparchive.php
There isn't any included way to do what you want, which is a shame. So I would unzip the file to a temp directory, then use another function to copy the contents to where you want. So when using ZipArchive, you will need to return the first item to get the folder name if it is unknown. If the folder is known, ie: the same pesky folder name every time, then you could hard code the name.
I have made it return the first item from the index. So if you ALWAYS have a zip with 1 folder inside it, and everything in that folder, this would work. However, if you have a zip file without everything consolidated inside 1 folder, it would fail. The code I have added will take care of your question. You will need to add further logic to handle alternate cases.
Also, You will still be left with the old directory from when we extract it to the temp directory for "processing". So I included code to delete it too.
NOTE: The code uses a lot of if's to show the processing steps, and print a message for testing purposes. You would need to modify it to your needs.
<?php
public function copyDirectoryContents($source, $destination, $create=false)
{
if ( ! is_dir($source) ) {
return false;
}
if ( ! is_dir($destination) && $create === true ) {
#mkdir($destination);
}
if ( is_dir($destination) ) {
$files = array_diff(scandir($source), array('.','..'));
foreach ($files as $file)
{
if ( is_dir($file) ) {
copyDirectoryContents("$source/$file", "$destination/$file");
} else {
#copy("$source/$file", "$destination/$file");
}
}
return true;
}
return false;
}
public function removeDirectory($directory, $options=array())
{
if(!isset($options['traverseSymlinks']))
$options['traverseSymlinks']=false;
$files = array_diff(scandir($directory), array('.','..'));
foreach ($files as $file)
{
if (is_dir("$directory/$file"))
{
if(!$options['traverseSymlinks'] && is_link(rtrim($file,DIRECTORY_SEPARATOR))) {
unlink("$directory/$file");
} else {
removeDirectory("$directory/$file",$options);
}
} else {
unlink("$directory/$file");
}
}
return rmdir($directory);
}
$file = dirname(__FILE__) . '/file.zip'; // full path to zip file needing extracted
$temp = dirname(__FILE__) . '/zip-temp'; // full path to temp dir to process extractions
$path = dirname(__FILE__) . '/extracted'; // full path to final destination to put the files (not the folder)
$firstDir = null; // holds the name of the first directory
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
$firstDir = $zip->getNameIndex(0);
$zip->extractTo($temp);
$zip->close();
$status = "<strong>Success:</strong> '$file' extracted to '$temp'.";
} else {
$status = "<strong>Error:</strong> Could not extract '$file'.";
}
echo $status . '<br />';
if ( empty($firstDir) ) {
echo 'Error: first directory was empty!';
} else {
$firstDir = realpath($temp . '/' . $firstDir);
echo "First Directory: $firstDir <br />";
if ( is_dir($firstDir) ) {
if ( copyDirectoryContents($firstDir, $path) ) {
echo 'Directory contents copied!<br />';
if ( removeDirectory($directory) ) {
echo 'Temp directory deleted!<br />';
echo 'Done!<br />';
} else {
echo 'Error deleting temp directory!<br />';
}
} else {
echo 'Error copying directory contents!<br />';
}
} else {
echo 'Error: Could not find first directory';
}
}
I just wanna ask, what is the code needed in my code in order this warning will not show
Warning: mkdir() [function.mkdir]: File exists in
C:\xampp\htdocs\php-robert\dir\dir.php
also did my program is correct? what i want in my program is, if the folder is not exist, make a folder, if its existing just do nothing.. nothing to show, just nothing
dir.php
<?php
$var = "MyFolder";
$structure = "../../file/rep/$var";
if (!mkdir($structure, 0700)) {
}
else
{
echo"folder created";
}
?>
Try the following:
$folder = "folder_name";
// if folder does not exist or the name is used, just not for a folder
if (!file_exists($folder) || !is_dir($folder)) {
if (mkdir($folder, 0755)) {
echo 'Folder created';
} else {
echo 'Unable to create folder';
}
}
if (!is_dir($structure)) {
mkdir($structure);
}
else
{
echo "folder already exists";
}
if (is_dir($structure) == false and mkdir($structure, 0700) == false)
{
echo "error creating folder";
}
else
{
echo "folder exists or was created";
}
You could also test if a file exists, but it isn't a folder
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);
}
}