You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cpanel API实现PHP文件上传时覆盖已存在文件?

解决Cpanel API上传文件时覆盖已存在文件的问题

解决这个问题有两种可行的方式,下面分别给出实现方案:

方法一:直接使用上传接口的覆盖参数

Cpanel的Fileman/upload_files接口本身支持覆盖已存在文件的参数,只需在请求payload里添加overwrite字段并设置为1即可。

修改你代码中的payload部分,添加该参数:

$payload = array(
    'dir'       => $destination_dir,
    'file-1'    => $cf,
    'overwrite' => 1 // 新增这个参数,开启覆盖
);

修改后再执行上传,当目标文件存在时就会自动覆盖,无需额外操作。

方法二:先删除旧文件再上传

如果你的Cpanel版本不支持overwrite参数,可以先调用Fileman/delete_files接口删除目标文件,再执行上传步骤。

完整代码示例如下:

<?php
// 开启错误报告
error_reporting(E_ALL);

// 认证信息
$username = 'xxxxx';
$password = 'xxxxx';
$cpanel_host = 'xxxxxx';

// 定义文件信息
$upload_file = realpath("test.php");
$destination_dir = "public_html";
// 获取要删除的目标文件路径
$target_file = $destination_dir . "/" . basename($upload_file);

// 第一步:删除已存在的文件
$delete_uri = "https://$cpanel_host:2083/execute/Fileman/delete_files";
$delete_payload = array(
    'files' => $target_file
);

$ch = curl_init($delete_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);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $delete_payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$delete_response = curl_exec($ch);
curl_close($ch);

// 第二步:执行上传操作
$upload_uri = "https://$cpanel_host:2083/execute/Fileman/upload_files";

if(function_exists('curl_file_create')) {
    $cf = curl_file_create($upload_file);
} else {
    $cf = "@/" . $upload_file;
}

$upload_payload = array(
    'dir'    => $destination_dir,
    'file-1' => $cf
);

$ch = curl_init($upload_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);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $upload_payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$upload_response = curl_exec($ch);
curl_close($ch);

// 处理上传响应
$response = json_decode($upload_response);
if(empty($response)) {
    echo "请求未返回有效JSON:";
    die($upload_response);
} elseif (!$response->status) {
    echo "请求返回错误:";
    die($response->errors[0] . "\n");
}

print_r($response);
?>

注意:删除接口即使目标文件不存在也不会返回错误,所以不需要额外判断文件是否存在,直接执行删除即可。

内容的提问来源于stack exchange,提问作者Loki wind.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 11:48:36