0

The normal curl way, works well.

curl \
  -F "smfile=@test.png" \
  -H "Content-Type: multipart/form-data" \
  https://sm.ms/api/v2/upload

But in my PHP version curl, it returns bool(false) and string(0) "":

<?php

$url = "https://sm.ms/api/v2/upload";
$headers = array();
array_push($headers, "Content-Type: multipart/form-data");
array_push($headers, "User-Agent: ".$_SERVER['HTTP_USER_AGENT']);

// $fields = array('smfile' => curl_file_create('test.png', 'image/png', 'test.png'));
$fields = array('smfile' => new CURLFile('test.png', 'image/png', 'tset.png'));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

var_dump(curl_exec($ch));
var_dump(curl_error($ch));

What's wrong with my code? ヽ(*。>Д<)o゜

Mashiro
  • 1,032
  • 1
  • 12
  • 24
  • Does this answer your question? [how to upload file using curl with php](https://stackoverflow.com/questions/15200632/how-to-upload-file-using-curl-with-php) – CodyKL Nov 14 '19 at 06:04
  • @CodyKL I tried the `$fields = array('smfile' => "@test.png");` method in that link but got a `Invalid file source` message from the API side. I checked the curl request header by `curl_getinfo`, in which the content_type is "text/html; charset=UTF-8". I'm not sure why? – Mashiro Nov 14 '19 at 06:48

2 Answers2

0

Try this one:

<?php

$url = "https://sm.ms/api/v2/upload";

// I guess the file is in the same directory as this script
$file = __DIR__.'/test.png'; 

$headers = [
    'Content-Type: multipart/form-data',
    'User-Agent: '.$_SERVER['HTTP_USER_AGENT'],
];

$fields = [
    'smfile' => new CURLFile($file, 'image/png')
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

var_dump(curl_exec($ch));
var_dump(curl_error($ch));

?>
CodyKL
  • 1,024
  • 6
  • 14
-2

you can use this simple code to upload files

$explode = explode('.', $_FILES['file']['name']);
$ext = $explode[count($explode) - 1];

if(is_uploaded_file($_FILES['file']['tmp_name']))
{
$result = move_uploaded_file($_FILES['file']['tmp_name'],
'uploads/'.basename($_FILES['file']['name']));
echo $result === true ? 'File uploaded successfuly' : 'There are some errors';
}
else
{
echo 'No File uploaded';
}
  • Your code matches on a file upload via a form, but the TE want to upload a picture from one server to another server over a API via CURL. – CodyKL Nov 14 '19 at 06:22