skip to Main Content

I have a PHP code that performs file upload with API to my cpanel account.

The problem is this: If the file I want to upload already exists, it does not upload this file.

What I want is this: If the file I want to upload already exists, I want it to overwrite it.

My code:

<?php
// Log everything during development.
// If you run this on the CLI, set 'display_errors = On' in php.ini.
error_reporting(E_ALL);

// Declare your username and password for authentication.
$username = 'xxxxx';
$password = 'xxxxx';

// Define the API call.
$cpanel_host = 'xxxxxx';
$request_uri = "https://$cpanel_host:2083/execute/Fileman/upload_files";

// Define the filename and destination.
$upload_file = realpath("test.php");
$destination_dir = "public_html";

// Set up the payload to send to the server.
if( function_exists( 'curl_file_create' ) ) {
    $cf = curl_file_create( $upload_file );
} else {
    $cf = "@/".$upload_file;
}
$payload = array(
    'dir'    => $destination_dir,
    'file-1' => $cf
);

// Set up the curl request object.
$ch = curl_init( $request_uri );
curl_setopt( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $ch, CURLOPT_USERPWD, $username . ':' . $password );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );

// Set up a POST request with the payload.
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

// Make the call, and then terminate the curl caller object.
$curl_response = curl_exec( $ch );
curl_close( $ch );

// Decode and validate output.
$response = json_decode( $curl_response );
if( empty( $response ) ) {
    echo "The curl call did not return valid JSON:n";
    die( $response );
} elseif ( !$response->status ) {
    echo "The curl call returned valid JSON, but reported errors:n";
    die( $response->errors[0] . "n" );
}

// Print and exit.
die( print_r( $response ) );
?>

It can also be a process of deleting the old file and then installing the new file, it doesn’t matter

2

Answers


  1. I recommend to try deleting the file if it exists and then to reupload.

    Login or Signup to reply.
  2. You could add overwrite option to your payload like this:

    $payload = array(
    ‘dir’ => $destination_dir,
    ‘overwrite’ => ‘1’,
    ‘file-1’ => $cf
    );

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search