php: upload files to WebDav storage

Trabla: php: upload files to web dav

Solving:

<?php

/**
* @param string $webdav_username WebDav user name credentials with write permission
* @param string $webdav_password WebDav user password
* @param string $file_path path to file (local)

* @param string $remote_url WebDav folder path, where to upload file e.g. https://storage.mysite.com/images/
* @param string $file_name  file name on WebDav after upload
* @return string 
*/

function webdav_upload(     
                             $webdav_username,
                             $webdav_password,   
                             $file_path,
                             $remote_url,
                             $file_name
){

    // Prepare the file we are going to upload
    if(!file_exists($file_path)){
        throw new Exception("File Not Exists {$file_path}", 1);
    }

    $file_size = filesize($file_path);
    $fh = fopen($file_path, 'r');

    // Initialize cURL and set the options required for the upload. We use the remote
    // path we specified together with the filename. This will be the result of the
    // upload.

    $ch = curl_init( $remote_url . $file_name);

    // Set the authentication mode and login credentials
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_USERPWD, implode(':', array( $webdav_username, $webdav_password ) ));

    // Define that we are going to upload a file, by setting CURLOPT_PUT we are
    // forced to set CURLOPT_INFILE and CURLOPT_INFILESIZE as well.

    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_INFILE, $fh);
    curl_setopt($ch, CURLOPT_INFILESIZE, $file_size);

    // Execute the request, upload the file
       $result = curl_exec($ch);

    // Close the file handle
    fclose($fh);

    return $result;

}


// Execute upload


$result = webdav_upload(
   
        'user123'
    ,   'password12345'
    ,    '/var/www/myfile.png'
    ,    'https://storage.mysite.com/images/'
    ,   'myfile.png'
);

var_dump($result);

?>

No comments:

Post a Comment