Gee
Gee

Reputation: 367

cURL Upload File to PHP

I'm currently trying to use the cURL executable to upload mp4 Files to a php script using the POST method. In the PHP file I'm checking the File format and all that kind of stuff. Here's the PHP file:

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (($_FILES["file"]["type"] == "video/mp4") && ($_FILES["file"]["size"] < 2000000) && in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    } else {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
        }
    }
} else {
    echo "Invalid file";
}
?>

When I upload files using a normal HTML form it works properly. This is the HTML form i used:

<!DOCTYPE html>

<head>
    <title></title>
</head>

<body>

    <form action="upload_file.php" method="post" enctype="multipart/form-data" name="uploadedfile">
        <label for="file"><span>Filename:</span></label>
        <input type="file" name="file" id="file" /> 
        <br />
        <input type="submit" name="submit" value="Submit" />
    </form>
</body>
</html>

But when I now try it using the cURL Client using this command:

"curl -F [email protected] http://localhost:1337/upload_file.php"

It displays me "Invalid File" in the console, which is normally shown when the file doesnt match the attributes im checking in PHP(for example not fitting the file type).

I hope you guys understand my problem and can help me! :)

Greets Steven

Upvotes: 3

Views: 1546

Answers (2)

Richard Thomas
Richard Thomas

Reputation: 360

Further to what drew010 wrote (I'd write a comment but don't have the reputation yet), trusting those values passed in may actually be a security risk and has been used to hack sites in the past so be careful.

Upvotes: 1

drew010
drew010

Reputation: 69927

Your $_FILES["file"]["type"] check is failing because cURL doesn't make any guesses to the type and won't send that automatically in the POST request.

This is easily spoofed so it's not a great check anyway.

But to make your example work, try specifying the content type with the file parameter:

curl -F [email protected];type=video/mp4 http://localhost:1337/upload_file.php

Upvotes: 2

Related Questions