foreach loop copy files directories - php

I'd like to copy files from a remote server with a similar structure to files in my server with the same structure.
include "../arrays.php";
foreach ($citycode as $city) {
$source = "http://www.remoteserver.com/data/{$city}/";
$dest = "/alltxts/{$city}/";
// EVERYTHING FROM HERE ONWARDS RUNS PERFECTLY, THE PROBLEM IS PROBABLY ABOVE.
function copyr($source, $dest)
{
// Simple copy for a file
if (is_file($source)) {
chmod($dest, 777);
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
}
chmod($dest, 777);
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir->close();
return true;
}
}
The code to copy the files works just fine when I use a specific $citycode as $city. However, when I use the array to catch all city names with one line, it doesn't work. Any ideas? I'd appreciate any help, thanks!

You are searching for:
$source = "http://www.remoteserver.com/data/{$city}/";
$dest = "/alltxts/{$city}/";
file_put_contents($dest, file_get_contents($source));
Make sure that you have proper permissions to save files in /alltxts/'. Also the leading / looks weird to me. Do you mean something like alltexts/ (relative path) instead?

Related

Clone/Copy a directory to destination

First of all i have searched and tried many functions but all of them works by copying all the contents(not the self source whole folder) of my source directory to destination.
But i want to copy WHOLE DIRECTORY.
WHAT I HAVE TRIED?
This function copies the contents of folder copy of $source to folder New Copy of destination $dest.
$source = 'C:\MAMP\htdocs\projectAuru\our/files/copy';
$dest = 'C:\MAMP\htdocs\projectAuru\our/files/New Copy';
function xcopy($source, $dest, $permissions = 0777)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
// Clean up
$dir->close();
return true;
}
WHAT I AM LOOKING FOR?
It should copy my entire directory copy(along with all of its files and subfolders) to destination folder So finally the destination directory should look like afterwards:
C:\MAMP\htdocs\projectAuru\our/files/New Copy/copy
The solution to this is to get the name of the folder that we are copying and mkdir with that name in the Destination and then copy all files to that mkdir destination.
// Get value after last slash and trim trailing slash if exists
$copyFromFolderName = substr(rtrim($copyFrom, '/'), strrpos(rtrim($copyFrom, '/'), '/') + 1);
if (!is_dir($base.$copyTo.'/'.$copyFromFolderName)) {
mkdir($base.$copyTo.'/'.$copyFromFolderName, 0777, true);
xcopy($base.$copyFrom, $base.$copyTo.'/'.$copyFromFolderName);
}else{
xcopy($base.$copyFrom, $base.$copyTo.'/'.$copyFromFolderName);
}

How to delete file in PHP

I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.

Get only folder names in a directory, skipping dots and ignoring certain folders

I need to get only the folder names in a directory. So far I found the DirectoryIterator to be useful. However I am not getting the desired names of the folders.
$dir = new DirectoryIterator(dirname($directory));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
if ($fileinfo->isDir()) {
//echo $fileinfo->getFilename() . '<br>';
}
}
}
Please see: I also want to skip the dots (.) and (..)
while having the ability to ignore folders I choose.
DirectoryIterator let you obtain filenames relatives to the directory not absolute, neither relative to the current directory of your process. Concatenate $directory and $fileinfo->getFileName() to obtain a correct usable path.
Here is a solution:
$path = 'PATH';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
//skips dots
if ('.' === $file) continue;
if ('..' === $file) continue;
//ignore folders
if ('FOLDER_TO_IGNORE' === $file) continue;
//check if filename is a folder
if (is_dir($file)){
//DO SOMETHING WITH FOLDER ($file)
}
}
closedir($handle);
}

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.

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');

Categories