dropbox-php-sdk icon indicating copy to clipboard operation
dropbox-php-sdk copied to clipboard

Check if the folder already exists

Open tranvanba1992 opened this issue 6 years ago • 3 comments

How to check if the folder already exists. Thanks

tranvanba1992 avatar Mar 28 '19 04:03 tranvanba1992

Just do a try catch and your script will add the folder if necessary

try { $dropbox->createFolder($path); } catch (Exception $e) {

}

jonpaulh avatar Jul 12 '19 13:07 jonpaulh

I'm working in the symfony framework and can't do a simple try/catch, so I wrote a function to handle this:

`function doesItemExist( $path, $depth = 0 ){ // this isn't actually in my code, as I'm using a an object based approach, but you could define your dropbox object here if needed $dropbox = new Dropbox($app);

$depth++;
if( !is_array( $path ) ){
	$path = explode( '/', $path );
}

$pathDepth = count( $path ) - 1; // the max depth of the exploded path
$currentPath = join( '/', array_slice( $path, 0, $depth ) ); // the joined path at the current depth

if( $depth <= $pathDepth ){
	// get the dropbox items
	$listFolder = $dropbox->listFolder( $currentPath, ['recursive' => false] );
	$items = $listFolder->getItems()->all();

	// loop through the items looking for the current path
	foreach( $items as $item ){
		// match case insensitive
		if(
			"$currentPath/$path[$depth]" === $item->getDataProperty( 'path_display' ) ||
			"$currentPath/$path[$depth]" === $item->getDataProperty( 'path_lower' )
	 	){
			// found our current depth item
			if( $depth === $pathDepth ){
				// if we are at the max depth then we are done
				return true;
				break;
			} else {
				// otherwise dive deeper
				return doesItemExist( $path, $depth );
				break;
			}
		}
	}

	// our item wasn't found
	return false;
}

}`

wetmarble avatar Apr 02 '20 18:04 wetmarble

After doing A/B testing, dropbox's search function is faster than my function.

wetmarble avatar May 13 '20 22:05 wetmarble