You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在PHP服务器中接收CURL请求上传的图片

How to Retrieve an Image Uploaded via Your CURL Command in PHP

Hey there! Let's break down why your current setup isn't capturing the uploaded image, and walk through two solid solutions to fix it.

Why $_POST Isn't Working Here

When you use --data-binary @demo.png in your CURL command, you're sending the image's raw binary data directly in the request body—not as a standard form-encoded POST request. PHP's $_POST superglobal only parses data formatted like a web form submission (application/x-www-form-urlencoded or multipart/form-data), so it can't pick up this raw binary content. That's why you're just seeing an empty or incomplete Array in your output.


This is the most common and reliable way to upload files, as it aligns with how browsers handle file uploads.

Step 1: Update Your CURL Command

Replace --data-binary with -F (which specifies a multipart form field):

curl --user name:abc -F "uploaded_image=@demo.png" -i localhost:80/post/index.php --output new.txt

The -F flag tells CURL to send the file as part of a multipart/form-data request, which PHP can parse with the $_FILES superglobal.

Step 2: Modify Your PHP Script (index.php)

Use $_FILES to access the uploaded file details and save it to your server:

<?php
// Check if a file was uploaded
if (isset($_FILES['uploaded_image'])) {
    // Print the file metadata for debugging
    print_r($_FILES['uploaded_image']);

    // Define the path to save the uploaded file
    $targetPath = './uploaded_demo.png';

    // Move the temporary file to your desired location
    if (move_uploaded_file($_FILES['uploaded_image']['tmp_name'], $targetPath)) {
        echo "Image saved successfully to: " . $targetPath;
    } else {
        echo "Failed to save the image.";
    }
} else {
    echo "No file was uploaded.";
}
?>

Solution 2: Read Raw Request Body (If You Can't Change the CURL Command)

If you need to keep using --data-binary for some reason, you can read the raw binary data directly from the request body in PHP.

Modify Your PHP Script (index.php)

Use php://input to fetch the raw data and save it as an image file:

<?php
// Read the raw binary data from the request body
$rawImageData = file_get_contents('php://input');

// Check if data was received
if (!empty($rawImageData)) {
    // Define where to save the image
    $savePath = './received_demo.png';

    // Write the data to a file
    if (file_put_contents($savePath, $rawImageData)) {
        echo "Image received and saved to: " . $savePath;
    } else {
        echo "Failed to write the image to disk.";
    }
} else {
    echo "No image data received.";
}
?>

This method bypasses PHP's form parsing entirely and grabs the exact binary data sent by CURL.


内容的提问来源于stack exchange,提问作者David Cring

火山引擎 最新活动