Hello i'm rely stuck here,
Ok i already have a working function to update my database for ONE specified file, in my directory,
now i need a php code to do the same thing for each file on directory and then delete it.
$fileName = "IEDCBR361502201214659.RET";
$cnab240 = RetornoFactory::getRetorno($fileName, "linhaProcessada");
$retorno = new RetornoBanco($cnab240);
$retorno->processar();
the function linhaProcessada is
function linhaProcessada2($self, $numLn, $vlinha) {
if($vlinha["registro"] == $self::DETALHE )
{
if($vlinha["registro"] == $self::DETALHE && $vlinha["segmento"] == "T" ) {
//define a variavel do nosso numero como outra usavel
$query ="SELECT * FROM jos_cobra_boletos WHERE nosso_numero = ".$vlinha['nosso_numero']."";
echo "Boleto de numero: ".$vlinha['nosso_numero']." Atualizado com sucesso!<hr>";
$testResult = mysql_query($query) or die('Error, query failed');
if(mysql_fetch_array($testResult) == NULL){
}else{
$query = "UPDATE jos_cobra_boletos
SET status_pagamento='Pago'
WHERE nosso_numero=".$vlinha['nosso_numero']."";
$result = mysql_query($query) or die('Erro T');
}
}
}
}
Really need help on this one
PHP's opendir() ought to do the trick. More info here: http://php.net/manual/en/function.opendir.php
<?php
// Set Directory
$dir = '/abs/path/with/trailing/slash/';
if ($handle = opendir( $dir )) { // Scan directory
while (false !== ($file = readdir($handle))) { // Loop each file
$fileName = $dir . $file;
// Run code on file
$cnab240 = RetornoFactory::getRetorno($fileName, "linhaProcessada");
$retorno = new RetornoBanco($cnab240);
$retorno->processar();
// Delete file
unlink( $fileName );
}
closedir( $handle );
}
<? //PHP 5.4+
foreach(
new \GlobIterator(
__DIR__ . '/*.RET', //Or other directory where these files are
\FilesystemIterator::SKIP_DOTS |
\FilesystemIterator::CURRENT_AS_PATHNAME
)
as $pathname
){
(new RetornoBanca(
RetornoFactory::getRetorno($pathname, 'linhaProcessada')
))
->processar();
\unlink($pathname);
}
?>
Related
I am trying to use allow my custom API endpoint to upload files to a custom directory based on information sent in the request body. It is coming through fine but I am not getting it to pass into the directory properly. I have tried getting the studentid from the request body and then calling that as a global in my function but it is not working.
add_filter("wcra_upload_callback", "wcra_upload_callback_handler");
function wcra_upload_callback_handler($request) {
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH.'wp-admin/includes/file.php');
}
$studentid = $request['studentid'];
function studentresultsdir($dir) {
global $studentid;
$mydir = 'https://example.com/wp-content/uploads/studentresults/';
$dir['path'] = $mydir;
$dir['url'] = $mydir;
$dir['subdir'] = $studentid;
var_dump($dir);
return $dir;
}
add_filter("upload_dir", "studentresultsdir");
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
echo __('File is valid, and was successfully uploaded.', 'textdomain')."\n";
var_dump($movefile);
} else {
echo $movefile['error'];
}
remove_filter("upload_dir", "studentresultsdir");
}
My var_dump of $dir is giving me an empty subdirectory. I think this is the cause of my "unable to create directory" error too but need to work this step out first.
Just wanted to add that I will be adding authentication checks once I get this working.
I managed to solve this particular error by moving the global variable outside of all functions.
add_filter("wcra_upload_callback", "wcra_upload_callback_handler");
$studentid = '';
function wcra_upload_callback_handler($request) {
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH.'wp-admin/includes/file.php');
}
global $studentid;
$studentid = $request['studentid'];
function studentresultsdir($dir) {
global $studentid;
$mydir = 'https://example.com/wp-content/uploads/studentresults/';
$dir['path'] = $mydir;
$dir['url'] = $mydir;
$dir['subdir'] = '/'.$studentid;
var_dump($dir);
return $dir;
}
add_filter("upload_dir", "studentresultsdir");
$uploadedfile = $_FILES['file'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile['error'])) {
echo __('File is valid, and was successfully uploaded.', 'textdomain')."\n";
var_dump($movefile);
} else {
echo $movefile['error'];
}
remove_filter("upload_dir", "studentresultsdir");
}
I have a folder with some randomly named files that contain data that I need.
In order to use the data, I have to move the files to another folder and name the file 'file1.xml'
Every time a file is moved and renamed, it replaces a previous 'file1.xml' in the destination folder.
The source folder contains all the other randomly named files which are kept as an archive.
The php will be run via a cron job every 48 hours
The following works, but it's for ftp. I need to edit it for local files.
$conn = ftp_connect('ftp.source.com'); ftp_login($conn, 'username', 'password'); // get file list $files = ftp_nlist($conn, '/data'); $mostRecent = array( 'time' => 0, 'file' => null ); foreach ($files as $file) { // get the last modified time $time = ftp_mdtm($conn, $file); if ($time > $mostRecent['time']) { // this file is the most recent so far $mostRecent['time'] = $time; $mostRecent['file'] = $file; } } ftp_get($conn, "/destinationfolder/file1.xml", $mostRecent['file'], FTP_BINARY); ftp_close($conn);
I didn't test it but I think this should work (comparing your ftp script):
<?php
$conn = ftp_connect('ftp.source.com');
ftp_login($conn, 'username', 'password');
// get file list
$files = ftp_nlist($conn, '/data');
$mostRecent = array( 'time' => 0, 'file' => null );
foreach ($files as $file) {
// get the last modified time
$time = ftp_mdtm($conn, $file);
if ($time > $mostRecent['time']) {
// this file is the most recent so far
$mostRecent['time'] = $time;
$mostRecent['file'] = $file;
}
}
ftp_get($conn, "/destinationfolder/file1.xml", $mostRecent['file'], FTP_BINARY); ftp_close($conn);
?>
New:
<?php
$sourceDir = "./data";
$destDir = "./destinationfolder";
if (!is_dir($sourceDir) || !is_dir($destDir)) {
exit("Directory doesn't exists.");
}
if (!is_writable($destDir)) {
exit("Destination directory isn't writable.");
}
$mostRecentFilePath = "";
$mostRecentFileMTime = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceDir), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mostRecentFileMTime) {
$mostRecentFileMTime = $fileinfo->getMTime();
$mostRecentFilePath = $fileinfo->getPathname();
}
}
}
if ($mostRecentFilePath != "") {
if (!rename($mostRecentFilePath, $destDir . "/file1.xml")) {
exit("Unable to move file.");
}
}
?>
I read similar query on google, there I read about checking whether file is writable and then setting permissions using chmod() function, but I tried that too, it didnt work. I want to store the image path in database, and move the image to the uploads folder. The path of the image would be as :
C:/xampp/htdocs/konnect1/uploads/Hydrangeas1.jpg
On using chmod(), I get Warning as "Message: chmod(): No such file or directory".
please help as what should I change now.
Controller page->admin_c.php
Posting the function, where image upload code is written.
public function create_event1()
{
if($this->input->post('counter') || !$this->input->post('counter'))
{
$count = $this->input->post('counter');
$c = $count;
//echo $c;
if($this->input->is_ajax_request())
{
$vardata = $this->input->post('vardata');
echo $vardata;
}
$g = $_POST['results'];
$configUpload['upload_path'] = '/konnect1/uploads/'; #the folder placed in the root of project
$configUpload['allowed_types'] = 'gif|jpg|png|bmp|jpeg'; #allowed types description
$configUpload['max_size'] = '0'; #max size
$configUpload['max_width'] = '0'; #max width
$configUpload['max_height'] = '0'; #max height
$configUpload['encrypt_name'] = false; #encrypt name of the uploaded file
$this->load->library('upload', $configUpload);
$this->upload->initialize($configUpload); #init the upload class
if( chmod($configUpload['upload_path'], 0755) )
{
// more code
chmod($configUpload['upload_path'], 0777);
}
else
echo "Couldn't do it.";
if ( ! is_writable($this->upload->do_upload('picture')))
{
$uploadedDetails = $this->upload->display_errors('upload_not_writable');
echo $uploadedDetails;
}
else if(!$this->upload->do_upload('picture'))
{
$uploadedDetails = $this->upload->display_errors();
}
else
{
$uploadedDetails = $this->upload->data();
//print_r($uploadedDetails);die;
$etype = $this->input->post('etype');
$ecategory = $this->input->post('ecategory');
$ename = $this->input->post('ename');
$edat_time = $this->input->post('edat_time');
$evenue = $this->input->post('evenue');
$sch_name0 = $this->input->post("sch_name0");
$speaker_name0 = $this->input->post("speaker_name0");
$sch_stime0 = $this->input->post("sch_stime0");
$sch_etime0 = $this->input->post("sch_etime0");
$sch_venue0 = $this->input->post("sch_venue0");
$sch_name = $this->input->post("sch_name");
$speaker_name = $this->input->post("speaker_name");
$sch_stime = $this->input->post("sch_stime");
$sch_etime = $this->input->post("sch_etime");
$sch_venue = $this->input->post("sch_venue");
$agenda_desc = $this->input->post("agenda_desc");
if ((!empty($etype)) || (!empty($uploadedDetails)) || (!empty($ecategory)) || (!empty($ename)) || (!empty($edat_time)) || (!empty($evenue)) || (!empty($sch_name0)) || (!empty($speaker_name0)) || (!empty($sch_stime0)) || (!empty($sch_etime0)) || (!empty($sch_venue0)) || (!empty($sch_name)) || (!empty($speaker_name)) || (!empty($sch_stime)) || (!empty($sch_etime)) || (!empty($sch_venue)) || (!empty($agenda_desc)))
{
$res1 = $this->admin_m->insert($uploadedDetails);
if($res1 == true)
{
$res2 = $this->admin_m->insert1($c);
$lastid = $this->db->insert_id();
$data['h'] = $this->admin_m->select($lastid);
//return the data in view
$this->load->view('admin/event', $data);
}
else
echo "error";
}
}
}
}
Model Page->admin_m.php
<?php
class Admin_m extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert($image_data = array())
{
//$data1 = explode('/',$imge_data);
//$data2 = in_array("konnect1", $data1);
$data = array(
'ename' => $this->input->post('ename'),
'eimg' => $this->input->post('eimg'),
'edat_time' => $this->input->post('edat_time'),
'evenue' => $this->input->post('evenue'),
'sch_name' => $this->input->post('sch_name0'),
'speaker_name' => $this->input->post('speaker_name0'),
'sch_stime' => $this->input->post('sch_stime0'),
'sch_etime' => $this->input->post('sch_etime0'),
'sch_venue' => $this->input->post('sch_venue0'),
'etype' => $this->input->post('etype'),
'ecategory' => $this->input->post('ecategory'),
'agenda_desc' => $this->input->post('agenda_desc'),
'eimg' => $image_data['full_path']
);
$result = $this->db->insert('event',$data);
if($result == true)
return true;
else
echo "Error in first row";
}
public function insert1($c)
{
for($i=0; $i<=$c; $i++)
{
$sql = array(
'sch_name' => $this->input->post('sch_name')[$i],
'speaker_name' => $this->input->post('speaker_name')[$i],
'sch_stime' => $this->input->post('sch_stime')[$i],
'sch_etime' => $this->input->post('sch_etime')[$i],
'sch_venue' => $this->input->post('sch_venue')[$i]
);
//$sql = "INSERT INTO event(sch_name,speaker_name,sch_stime,sch_etime,sch_venue) VALUES(($this->input->post('sch_name')[$i]),($this->input->post('speaker_name')[$i]),($this->input->post('sch_stime')[$i]),($this->input->post('sch_etime')[$i]),($this->input->post('sch_venue')[$i]))";
$res = $this->db->insert('event',$sql);
}
if ($res == true)
return true;
else
echo "Error from first row";
}
public function select($lastid)
{
//data is retrive from this query
$query = $this->db->get('event');
return $query;
}
}
?>
for reference, attached model code also.
According to the error message, it seems PHP is unable to find the directory.
Please use PHP function is_dir() to first validate if PHP can recognize the path as a folder.
Once it returns true, you can proceed to use it.
Also in your upload path, you have started with / which would mean that your project is placed in root of OS and I don't think that location would be correct.
From the terminal cd to your project directory and run command pwd and get the current working directory and then use the proper upload path after taking into consideration the location of the project.
I currently have this script where users (using a form where they can upload up to seven images) can upload multiple images to a folder and the image name to my database, without any success. Please help.
if (isset($_POST['submit'])) { $ref_49 = $_POST['ref_49'];
$name = $_POST['name'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$rent_sell = $_POST['rent_sell'];
$heading = $_POST['heading'];
$price = $_POST['price'];
$limitedtextarea = $_POST['limitedtextarea'];
$type = $_POST['type'];
$where = $_POST['where'];
$address = $_POST['address'];
$bedroom = $_POST['bedroom'];
$bathroom = $_POST['bathroom'];
$garages = $_POST['garages'];
$carports = $_POST['carports'];
$granny_flat = $_POST['granny_flat'];
$ref_99 = $_POST['ref_99'];
$fulldesc = $_POST['full_desc'];
if ($ref_99=="") {
$full_ad = "yes";
} else {
$full_ad = "no";
}
$todays_date = date("Y-m-d");
mkdir("gallery/" . $_POST["name"], 0777);
for ($i = 0; $i < 7; $i++)
{
$file_name = $_FILES['uploadFile' . $i]['name'];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace("'", "", $file_name);
// $copy = copy($_FILES['uploadFile'. $i]['tmp_name'], "gallery/" . $_POST["name"] . "/" . $file_name);
if ((($_FILES['uploadFile' . $i]["type"] == "image/gif")
|| ($_FILES['uploadFile' . $i]["type"] == "image/jpeg")
|| ($_FILES['uploadFile' . $i]["type"] == "image/pjpeg"))
&& ($_FILES['uploadFile' . $i]["size"] < 200000000))
{
if ($_FILES['uploadFile' . $i]["error"] > 0)
{
$message = "Return Code: " . $_FILES['uploadFile' . $i]["error"] . "<br />";
}
else
{
$query = "INSERT INTO property (
name, contact, email, type_of_listing, rent_sell, address, prop_desc, area, price, main_image, image_1, image_2, image_3, image_4, image_5, image_6, heading, bathroom, bedroom, garages, carports, granny_flat, full_description, full_ad, 49_ref, 99_ref, listed
) VALUES (
'{$name}', '{$contact}', '{$email}', '{$type}', '{$rent_sell}', '{$address}', '{$limitedtextarea}', '{$where}', '{$price}', '{$photo_1}', '{$photo_2}', '{$photo_3}', '{$photo_4}', '{$photo_5}', '{$photo_6}', '{$photo_7}', '{$heading}', '{$bathroom}', '{$bedroom}', '{$garages}', '{$carports}', '{$granny_flat}', '{$fulldesc}', '{$full_ad}', 'ref_49_{$ref_49}', 'ref_99_{$ref_99}', ''
)";
$result = mysql_query($query, $connection);
if (file_exists("gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]))
{
$message = "<h3>" . $_FILES['uploadFile' . $i]["name"] . " already exists.</h3>";
}
else
{
move_uploaded_file($_FILES['uploadFile' . $i]["tmp_name"], "gallery/" . $_POST["name"] . "/" . $_FILES['uploadFile' . $i]["name"]);
$message = "File: " . $_FILES['uploadFile' . $i]["name"] . " uploaded.";
}
}
}
else
{
$message = "<h3>Invalid file or no file selected.</h3><br />• Only JPEG OR GIF allowed.<br />• Size limited may not exceed 200KB.<br />Return";
}
}
}
}
There could be a lot of things going wrong here. Have you tried to break this up into pieces? Are you sure the DB is connecting? Are you sure php has access to write to the directories it's attempting to write to? Are you sure those directories exist...etc. etc.
Comment out the vast majority of the code, and start testing all the components piece by piece, or wrap stuff in try/catch and see what errors are produced.
[edit]
If the problem only occurs when you upload < 7 files then the problem is in that you've hard coded a 7 into your loop!
Loop through how many files are actually being uploaded, not a fixed number.
Assuming they're all being named sequentially (and starting at 0) you can test for the existence of your hashed FILE value in the loop and just keep ingesting until it comes up null (probably good to add a limiter to make sure it can't go on for ever)
something like this...
[edit 2] modified the condition to include a test for file size
for($i=0; $_FILES['uploadFile' . $i] && $_FILES['uploadFile' . $i]['size'] > 0 && $i<100 ; $i++){
try{
//do your upload stuff here
}catch(e){}
}
[EDIT]
To modify your page to include a dynamic number of fields do this:
check out this fiddle: http://jsfiddle.net/RjcHY/2/
Click the plus and minus buttons on the right side to see how it works. I made it so that it's naming the file buttons as per your php's expectations.
While dealing with common tasks like file uploading, write some library for handling those tasks and call necessary function wherever needed . If you create an uploader class file , you can simply invoke one of the methods you created to handle file uploads .
Here i will give you a Uploader class
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>
For handling multiple uploads , ex 3 images uploading
repeat the block as follows
<?php
for($i=1;$i<=3;$i++){
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->setSequence($i);
if($uploader->uploadFile('txtFile'.$i)){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
}
?>
in above example , file browse components are named as txtFile1,txtFile2,txtFile3
Hope you will understand my explanation .
How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP?
To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well.
Here is a starting point- a function that will scan through an FTP directory and print the name of any directory in the tree which matches the pattern. I have tested it briefly.
function scan_ftp_dir($conn, $dir, $pattern) {
$files = ftp_nlist($conn, $dir);
if (!$files) {
return;
}
foreach ($files as $file) {
//the quickest way i can think of to check if is a directory
if (ftp_size($conn, $file) == -1) {
//get just the directory name
$dirName = substr($file, strrpos($file, '/') + 1);
if (preg_match($pattern, $dirName)) {
echo $file . ' matched pattern';
} else {
//directory didn't match pattern, recurse
scan_ftp_dir($conn, $file, $pattern);
}
}
}
}
Then do something like this
$host = 'localhost';
$user = 'user';
$pass = 'pass';
if (false === ($conn = ftp_connect($host))) {
die ('cannot connect');
}
if (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');
scan_ftp_dir($conn, '.', '/^beginswith/');
Unfortunately you can only delete an empty directory with ftp_rmdir(), but if you look here there is a function called ftp_rmAll() which you could use to remove whole directory structures which you find.
Also I have only tested on Unix the trick of using the fail status returned from ftp_size() as a method of checking if an item returned by ftp_nlist() is a directory.
Presumably there's more to this question than it first appears.
FTP supports DIR to list directory contents, RMDIR to remove directories and DEL to delete files, so it supports the operations you need.
Or are you asking how to iterate over an FTP directory tree?
Do you have a preferred/required implementation language for this?
Well, this is the script I ended up using. It's a rather specific instance where one would have to use this, but if you are in the same predicament I was in, simply put in your ftp server address, username, password, the name of the folders you want deleted, and the path of the folder to start in and this will iterate through the directory, deleting all folders that match the name. There is a bug with reconnecting if the connection to the server is broken so you might need to run the script again if it disconnects.
if( $argc == 2 ) {
$directoryToSearch = $argv[1];
$host = '';
$username = '';
$password = '';
$connection = connect( $host, $username, $password );
deleteDirectoriesWithName( $connection, 'directoryToDelete', $directoryToSearch );
ftp_close( $connection );
exit( 0 );
}
else {
cliPrint( "This script currently only supports 1 argument.\n");
cliPrint( "Usage: php deleteDirectories.php directoryNameToSearch\n");
exit( 1 );
}
/**
* Recursively traverse directories and files starting with the path
* passed in and then delete all directories that match the name
* passed in
* #param $connection the connection resource to the database.
* #param $name the name of the directories that should be * deleted.
* #param $path the path to start searching from
*/
function deleteDirectoriesWithName( &$connection, $name, $path ) {
global $host, $username, $password;
cliPrint( "At path: $path\n" );
//Get a list of files in the directory
$list = ftp_nlist( $connection, $path );
if ( empty( $list ) ) {
$rawList = ftp_rawlist( $connection, $path );
if( empty( $rawList ) ) {
cliPrint( "Reconnecting\n");
ftp_close( $connection );
$connection = connect( $host, $username, $password );
cliPrint( "Reconnected\n" );
deleteDirectoriesWithName( $connection, $name, $path );
return true;
}
$pathToPass = addSlashToEnd( $path );
$list = RawlistToNlist( $rawList, $pathToPass );
}
//If we have selected a directory, then 'visit' the files (or directories) in the dir
if ( $list[0] != $path ) {
$path = addSlashToEnd( $path );
//iterate through all of the items listed in the directory
foreach ( $list as $item ) {
//if the directory matches the name to be deleted, delete it recursively
if ( $item == $name ) {
DeleteDirRecursive( $connection, $path . $item );
}
//otherwise continue traversing
else if ( $item != '..' && $item != '.' ) {
deleteDirectoriesWithName( $connection, $name, $path . $item );
}
}
}
return true;
}
/**
*Put output to STDOUT
*/
function cliPrint( $string ) {
fwrite( STDOUT, $string );
}
/**
*Connect to the ftp server
*/
function connect( $host, $username, $password ) {
$connection = ftp_connect( $host );
if ( !$connection ) {
die('Could not connect to server: ' . $host );
}
$loginSuccessful = ftp_login( $connection, $username, $password );
if ( !$loginSuccessful ) {
die( 'Could not login as: ' . $username . '#' . $host );
}
cliPrint( "Connection successful\n" );
return $connection;
}
/**
* Delete the provided directory and all its contents from the FTP-server.
*
* #param string $path Path to the directory on the FTP-server relative to
* the current working directory
*/
function DeleteDirRecursive(&$resource, $path) {
global $host, $username, $password;
cliPrint( $path . "\n" );
$result_message = "";
//Get a list of files and directories in the current directory
$list = ftp_nlist($resource, $path);
if ( empty($list) ) {
$listToPass = ftp_rawlist( $resource, $path );
if ( empty( $listToPass ) ) {
cliPrint( "Reconnecting\n" );
ftp_close( $resource );
$resource = connect( $host, $username, $password );
$result_message = "Reconnected\n";
cliPrint( "Reconnected\n" );
$result_message .= DeleteDirRecursive( $resource, $path );
return $result_message;
}
$list = RawlistToNlist( $listToPass, addSlashToEnd( $path ) );
}
//if the current path is a directory, recursively delete the file within and then
//delete the empty directory
if ($list[0] != $path) {
$path = addSlashToEnd( $path );
foreach ($list as $item) {
if ($item != ".." && $item != ".") {
$result_message .= DeleteDirRecursive($resource, $path . $item);
}
}
cliPrint( 'Delete: ' . $path . "\n" );
if (ftp_rmdir ($resource, $path)) {
cliPrint( "Successfully deleted $path\n" );
} else {
cliPrint( "There was a problem deleting $path\n" );
}
}
//otherwise delete the file
else {
cliPrint( 'Delete file: ' . $path . "\n" );
if (ftp_delete ($resource, $path)) {
cliPrint( "Successfully deleted $path\n" );
} else {
cliPrint( "There was a problem deleting $path\n" );
}
}
return $result_message;
}
/**
* Convert a result from ftp_rawlist() to a result of ftp_nlist()
*
* #param array $rawlist Result from ftp_rawlist();
* #param string $path Path to the directory on the FTP-server relative
* to the current working directory
* #return array An array with the paths of the files in the directory
*/
function RawlistToNlist($rawlist, $path) {
$array = array();
foreach ($rawlist as $item) {
$filename = trim(substr($item, 55, strlen($item) - 55));
if ($filename != "." || $filename != "..") {
$array[] = $filename;
}
}
return $array;
}
/**
*Adds a '/' to the end of the path if it is not already present.
*/
function addSlashToEnd( $path ) {
$endOfPath = substr( $path, strlen( $path ) - 1, 1 );
if( $endOfPath == '/' ) {
$pathEnding = '';
}
else {
$pathEnding = '/';
}
return $path . $pathEnding;
}