使用 cURL 如何 post 一个文件

Using cURL how to post a file

我正在使用 AnonFiles 网站使用他们的 API

将文件直接上传到我的帐户

https://anonfiles.com/docs/api

我创建了一个帐户,他们给了我一个 API 密钥,使用这个密钥,我可以通过将 ?token=5846e48082XXXXXX 附加到上传请求来直接上传到我的帐户。

请求示例

curl -F "file=@test.txt" https://api.anonfile.com/upload

现在我想要一个带有 PHP 代码的简单表格,它允许我选择一个文件并将其上传到我的 anonfiles 帐户。

这是我尝试使用 cURL 函数

PHP 中编写此请求
<?PHP

if (isset($_POST['submit'])) {

    $url = 'https://anonfile.com/api/upload?token=5846e48082XXXXXX';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'file' => curl_file_create(
            $_FILES['file']['tmp_name'],
            $_FILES['file']['type'],
            $_FILES['file']['name']
        ),
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

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

    $result = json_decode($json);

    if (is_object($result) && $result->status) {
        echo "OK!";
    } else {
        echo "Error";
    }
}

?>

HTML 表格

<form action="' . $_SERVER['PHP_SELF'] . '" method="post" enctype="multipart/form-data">
File: <input type="file" name="file" id="file">
<br/>
<input type="submit" name="submit" id="submit" value="Send">
</form>

但这似乎不起作用并打印出错误消息而不是 ok 并且没有文件上传。

你可以这样做 this:

<?PHP

if (isset($_POST['submit'])) {

    $url = 'https://anonfile.com/api/upload?token=5846e48082XXXXXX';

    $filename = $_FILES['file']['name'];
    $filedata = $_FILES['file']['tmp_name'];
    $filesize = $_FILES['file']['size'];
    if ($filedata != '')
    {
        $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
        $postfields = array("filedata" => "@$filedata", "filename" => $filename);
        $ch = curl_init();
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_HEADER => true,
            CURLOPT_POST => 1,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $postfields,
            CURLOPT_INFILESIZE => $filesize,
            CURLOPT_RETURNTRANSFER => true
        ); // cURL options
        curl_setopt_array($ch, $options);
        $json = curl_exec($ch);
        $result = json_decode($json);
        if(!curl_errno($ch))
        {
            $info = curl_getinfo($ch);
            if ($info['http_code'] == 200) {
                if (is_object($result) && $result->status) {
                    $msg = "OK!";
                }
            }
        }
        else
        {
            $msg = curl_error($ch);
        }
        curl_close($ch);
    }
    else
    {
        $msg = "Please select the file";
    }
    echo $msg;
}

?>