PHP Accessing ownCloud Files Using WebDAV, upload, download and list files


$userUsername = 'username';
$userPassword = 'pass';
$folder = 'folder/';
$apiUrl = 'https://www.url.com/remote.php/webdav/';

//LIST FILES
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $apiUrl.$folder);
	curl_setopt($ch, CURLOPT_USERPWD, $userUsername.':'.$userPassword); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PROPFIND');
	curl_setopt($ch, CURLOPT_HEADER, 'true');
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Depth: 30; Content-Type: application/xml; charset=UTF-8'));
	$curlResult = curl_exec($ch);
	$xml = simplexml_load_string($curlResult);
	$xml->registerXPathNamespace('d', 'urn:DAV');
	$res = array();
	foreach ($xml->xpath('/d:multistatus/d:response/d:href') as $v) {$res[] = urldecode($v);}
	print_r($res);
//LIST FILES


//UPLOAD FILE
	$file = '1.txt';
	$fp = fopen($file, 'r');
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $apiUrl.$folder.$file);
	curl_setopt($ch, CURLOPT_USERPWD, $userUsername.':'.$userPassword); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_PUT, true); 
	curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file));
	curl_setopt($ch, CURLOPT_INFILE, $fp);
	$ret = curl_exec($ch);
//UPLOAD FILE


//DOWNLOAD PDF FILE
	$file = 'test.pdf';
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $apiUrl.$folder.$file);
	curl_setopt($ch, CURLOPT_USERPWD, $userUsername.':'.$userPassword); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	$curlResult = curl_exec($ch);
	header('Cache-Control: public'); 
	header('Content-type: application/pdf');
	header('Content-Disposition: attachment; filename='new.pdf'');
	header('Content-Length:'.strlen($curlResult));
	echo $curlResult;
	curl_close($ch);
//DOWNLOAD PDFFILE



//VIEW JPG IMAGE
	$file = '1.jpg';
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $apiUrl.$folder.$file);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_USERPWD, $userUsername.':'.$userPassword); 
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
	$image = curl_exec($ch);
	curl_close($ch);
	header('Content-type: image/jpeg');
	$im = imagecreatefromstring($image);
	$tw = imagesx($im);
	$th = imagesy($im);
	$thumbWidth = 100;
	$thumbHeight = $th * ($thumbWidth / $tw);
	$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
	imagecopyresampled($thumbImg, $im, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $tw, $th);
	imagejpeg($thumbImg, NULL, 100);
	imagedestroy($thumbImg);
//VIEW JPG IMAGE