How to overwrite existing folder or file in php ftp upload? - php

how to overwrite folder/file if exist via php ftp using ftp_put .
the default is not overwriting the files.
function ftp_putAll($conn_id, $folder, $remotedir) { // Called from moveFolder function at line 161 //
$d = dir($folder);
while($file = $d->read()) { // do this for each file in the directory
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($folder."/".$file)) { // do the following if it is a directory
if (!#ftp_chdir($conn_id, $remotedir."/".$file)) {
ftp_mkdir($conn_id, $remotedir."/".$file); // create directories that do not yet exist
}
$stream_options = array('ftp' => array('overwrite' => true));
$this->ftp_putAll($conn_id, $folder."/".$file, $remotedir."/".$file); // recursive part
} else {
if(ftp_put($conn_id, $remotedir."/".$file, $folder."/".$file, FTP_ASCII)) {
$upload = ftp_put($conn_id, $remotedir."/".$file, $folder."/".$file, FTP_ASCII);
}
else {
}
}

It would depend on the implementation of the FTP server. If the file overwrite is not allowed, first delete the file before uploading.

function ftp_putAll($conn_id, $src_dir, $dst_dir){
$d = dir($src_dir);
while($file = $d->read()) { // do this for each file in the directory
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
if (!#ftp_chdir($conn_id, $dst_dir."/".$file)) {
ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
}
ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
} else {
#ftp_put( $conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY);
}
}
}
$d->close();
}
can you please try this above code.
Following are function parameter
connection id ,
source path ,
destination path

Related

Extracting zip file on host by PHP destroys directory structure

I have a directory structure like this :
members/
login.php
register.php
I zip them by PHP ZipArchive in my windows machine, but when I upload it to linux host and extract there by PHP it gives me these as two files with no directory :
members\login.php
members\register.php
I want to have the complete directory structure on the host after unzipping the file.
Note that this unpacking code runs without any problem in my local machine. Is it something about windows and linux or what? How can I resolve it?
PHP does not actually provide a function that extracts a ZIP including its directory structure. I found the following code in a user comment in the manual:
function unzip($zipfile)
{
$zip = zip_open($zipfile);
while ($zip_entry = zip_read($zip)) {
zip_entry_open($zip, $zip_entry);
if (substr(zip_entry_name($zip_entry), -1) == '/') {
$zdir = substr(zip_entry_name($zip_entry), 0, -1);
if (file_exists($zdir)) {
trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
return false;
}
mkdir($zdir);
}
else {
$name = zip_entry_name($zip_entry);
if (file_exists($name)) {
trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
return false;
}
$fopen = fopen($name, "w");
fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
}
zip_entry_close($zip_entry);
}
zip_close($zip);
return true;
}
Source here.
try DIRECTORY_SEPARATOR
instead of using:
$path = $someDirectory.'/'.$someFile;
use:
$path = $someDirectory. DIRECTORY_SEPARATOR .$someFile;
Change your code to this:
$zip = new ZipArchive;
if ($zip->open("module. DIRECTORY_SEPARATOR .$file[name]") === TRUE) {
$zip->extractTo('module. DIRECTORY_SEPARATOR');
}
And it will work for both operating systems.
Good luck,
The problem solved! Here's what I did :
I change the code of creating zip file into this function from php.net user comments :
function addFolderToZip($dir, $zipArchive){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
$zipArchive->addEmptyDir($dir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories
if(($file !== ".") && ($file !== "..")){
addFolderToZip($dir . $file . "/", $zipArchive);
}
}else{
// Add the files
$zipArchive->addFile($dir . $file);
}
}
}
}
}
$zip = new ZipArchive;
$zip->open("$modName.zip", ZipArchive::CREATE);
addFolderToZip("$modName/", $zip);
$zip->close();
And in the host I wrote just this code to extract the zipped file :
copy($file["tmp_name"], "module/$file[name]");
$zip = new ZipArchive;
if ($zip->open("module/$file[name]") === TRUE) {
$zip->extractTo('module/');
}
$zip->close();
It created the folder and sub-folders. The only bug left is that it extracts every file in all subfolders in the main folder too, so there is two versions of each file in subfolders.

how to delete a file from folder in php

I have a folder 'items' in which there are 3 files item1.txt, item2.txt and item3.txt.
I want to delete item2.txt file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>
Initially the folder should have 777 permissions
$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
if ($file==$data) {
unlink($dir.'/'.$file);
}
}
or try
$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);
No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.
$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);
Please read details of unlink() function
http://php.net/manual/en/function.unlink.php
There is one bug in your code, you haven't given the correct path
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($dir."/".$file);//give correct path,
}
}
closedir($dirHandle);
?>
unlink
if($file==$data) {
unlink( $dir .'/'. $file);
}
It's very simple:
$file='a.txt';
if(unlink($file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
//if file is in other folder then do as follows
unlink("foldername/".$file);
try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.
rename($old, $new) or die("Unable to rename $old to $new.");

ZipArchive - extract folder

I am allowing users to upload portfolios in ZIP archives on my site.
The problem is that most archives have the following folder structure:
zipfile.zip
- zipfile
- file1.ext
- file2.ext
- file3.ext
is there any way to simply put the files (not the directory) onto my site (so the folder structure of their portfolio is like so)
user_name
- portfolio
- file1.ext
- file2.ext
- file3.ext
it currently uploads them like so:
user_name
- portfolio
- zipfile
- file1.ext
- file2.ext
- file3.ext
which creates all kinds of problems!
I have tried doing this:
$zip = new ZipArchive();
$zip->open($_FILES['zip']['tmp_name']);
$folder = explode('.', $_FILES['zip']['name']);
end($folder);
unset($folder[key($folder)]);
$folder = (implode('.', $folder));
$zip->extractTo($root, array($folder));
$zip->close();
to no avail.
You could do something like this:
Extract Zip file to a temp location.
Scan through it and move(copy) all the files to portfolio folder.
Delete the temp folder and its all contents (created in Step 1).
Code:
//Step 01
$zip = new ZipArchive();
$zip->open($_FILES['zip']['tmp_name']);
$zip->extractTo('temp/user');
$zip->close();
//Define directories
$userdir = "user/portfolio"; // Destination
$dir = "temp/user"; //Source
//Step 02
// Get array of all files in the temp folder, recursivly
$files = dirtoarray($dir);
// Cycle through all source files to copy them in Destination
foreach ($files as $file) {
copy($dir.$file, $userdir.$file);
}
//Step 03
//Empty the dir
recursive_directory_delete($dir);
// Functions Code follows..
//to get all the recursive paths in a array
function dirtoarray($dir, $recursive) {
$array_items = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($dir. "/" . $file)) {
if($recursive) {
$array_items = array_merge($array_items, dirtoarray($dir. "/" . $file, $recursive));
}
} else {
$file = $dir . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);
}
}
}
closedir($handle);
}
return $array_items;
}
// Empty the dir
function recursive_directory_delete($dir)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// if the new path is a directory
if(is_dir($path))
{
// we call this function with the new path
recursive_directory_delete($path);
// if the new path is a file
}else{
// we remove the file
unlink($path);
}
}
}
// close the directory
closedir($handle);
// return success
return TRUE;
}
}
How if change your zip file to this?
zipfile.zip
- file1.ext
- file2.ext
- file3.ext

Copy entire directory and content from one location to another using PHP

I am trying to copy an entire folder from one location to another using PHP, but it doesn't seem to work:
$username = "peter" //this is just an example.
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder
// copy image folder
$source = "templates/template1/images/";//copy image folder -source
$dest = $userdir;
function copyr($source, $dest){
// Simple copy for a file
if (is_file($source)) {
$c = copy($source, $dest);
chmod($dest, 0777);
return $c;
}
// Make destination directory
if (!is_dir($dest)) {
$oldumask = umask(0);
mkdir($dest, 0777);
umask($oldumask);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}
}
// Clean up
$dir->close();
return true;
}
I have also tried other solutions I saw online without success. Would appreciate any help possible
I also just tried this script without any luck.
I just tried another script and still no luck :(.
$template_homepage = "templates/template1/index.php";//path to default template homepage
$homepage = file_get_contents($template_homepage);//get default homepage structure
$username = testuser;// folder name for store
if (trim($username) == '') {
die("An error occured.");
} else {
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder for new website
// copy image folder
$src = 'templates/template1/images';//copy image folder -source
$dst = $userdir;
function rcopy($src, $dst) {
if (file_exists($dst)) rrmdir($dst);
if (is_dir($src)) {
mkdir($dst);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
}
else if (file_exists($src)) copy($src, $dst);
}
$fh = fopen($userdir."index.php", 'w') or die("An error occured. ");// create home page in users folder
// $stringData = $title; //."\n";//
fwrite($fh, $homepage);// write homepage structure into new homepage file.
fclose($fh);// close new homepage file.
$launchpage = "../Users/".$username."/"; // launch new homepage file.
header("Location: $launchpage");
}
Why don't you use exec and use the OS command to copy the folder over?
exec('cp -r sourcedir destdir');

zip generating function generating blank files

I am using this function to generate zip files:
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
//echo $file;
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
echo $destination;
return file_exists($destination);
}
else
{
return false;
}
}
I am using this to zip a vanilla, unaltered Wordpress install.(http://wordpress.org/) However for some reason the wp-content folder is having a 'ghost' empty file generated with it's name. The folder (and everything else) itself compresses correctly, but most unzip applications (including php's own extractTo()) break when they reach this unwanted file due to the name conflict.
I've looked into the folder/file structure and as far as I can see the only difference of note between this and the other folders in the site is that it is the biggest at 5.86 mb.
Can anyone suggest a fix / workaround?
This is the sample example to zip a folder.
<?php
function Create_zipArch($archive_name, $archive_folder)
{
$zip = new ZipArchive;
if ($zip->open($archive_name, ZipArchive::CREATE) === TRUE)
{
$dir = preg_replace('/[\/]{2,}/', '/', $archive_folder . "/");
$dirs = array($dir);
while (count($dirs))
{
$dir = current($dirs);
$zip->addEmptyDir($dir);
$dh = opendir($dir);
while ($file = readdir($dh))
{
if ($file != '.' && $file != '..')
{
if (is_file($file))
$zip->addFile($dir . $file, $dir . $file);
elseif (is_dir($file))
$dirs[] = $dir . $file . "/";
}
}
closedir($dh);
array_shift($dirs);
}
$zip->close();
$result='success';
}
else
{
$result='failed';
}
return $result;
}
$zipArchName = "ZipFileName.zip"; // zip file name
$FolderToZip = "zipthisfolder"; // folder to zip
echo Create_zipArch($zipArchName, $FolderToZip);
?>

Categories