skip to Main Content

The normal curl way, works well.

curl 
  -F "[email protected]" 
  -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゜

2

Answers


  1. 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';
    }
    
    Login or Signup to reply.
  2. 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));
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search