PHP Velho Oeste 2024

CURLFile::__construct

curl_file_create

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::__construct -- curl_file_createCrear un objeto CURLFile

Descripción

Estilo orientado a objetos

public CURLFile::__construct(string $filename, string $mimetype = ?, string $postname = ?)

Estilo por procedimientos

curl_file_create(string $filename, string $mimetype = ?, string $postname = ?): CURLFile

Crea un objeto CURLFile , utilizado para transferir (upload) un fichero con CURLOPT_POSTFIELDS.

Parámetros

filename

Ruta de acceso al fichero a ser transferido.

mimetype

Tipo MIME del fichero.

postname

Nombre del fichero para los datos de subida.

Valores devueltos

Devuelve un objeto CURLFile .

Ejemplos

Ejemplo #1 Ejemplo con CURLFile::__construct()

Estilo orientado a objetos

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Crea un gestor cURL
$ch = curl_init('http://example.com/upload.php');

// Crea un objeto CURLFile
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Asigna los datos POST
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Ejecuta el gestor
curl_exec($ch);
?>

Estilo por procedimientos

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Crea un gestor cURL
$ch = curl_init('http://example.com/upload.php');

// Crea un objeto CURLFile
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// Asigna los datos POST
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Ejecuta el gestor
curl_exec($ch);
?>

El resultado del ejemplo sería:

array(1) {
  ["test_file"]=>
  array(5) {
    ["name"]=>
    string(9) "test_name"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpPC9Kbx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(46334)
  }
}

Ver también

  • curl_setopt() - Configura una opción para una transferencia cURL

add a note add a note

User Contributed Notes 2 notes

up
8
CertaiN
9 years ago
There are "@" issue on multipart POST requests.

Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.

The following snippet will help you :D

<?php

/**
* For safe multipart POST request for PHP5.3 ~ PHP 5.4.
*
* @param resource $ch cURL resource
* @param array $assoc "name => value"
* @param array $files "name => path"
* @return bool
*/
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {
   
   
// invalid characters for "name" and "filename"
   
static $disallow = array("\0", "\"", "\r", "\n");
   
   
// build normal parameters
   
foreach ($assoc as $k => $v) {
       
$k = str_replace($disallow, "_", $k);
       
$body[] = implode("\r\n", array(
           
"Content-Disposition: form-data; name=\"{$k}\"",
           
"",
           
filter_var($v),
        ));
    }
   
   
// build file parameters
   
foreach ($files as $k => $v) {
        switch (
true) {
            case
false === $v = realpath(filter_var($v)):
            case !
is_file($v):
            case !
is_readable($v):
                continue;
// or return false, throw new InvalidArgumentException
       
}
       
$data = file_get_contents($v);
       
$v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
       
$k = str_replace($disallow, "_", $k);
       
$v = str_replace($disallow, "_", $v);
       
$body[] = implode("\r\n", array(
           
"Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
           
"Content-Type: application/octet-stream",
           
"",
           
$data,
        ));
    }
   
   
// generate safe boundary
   
do {
       
$boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (
preg_grep("/{$boundary}/", $body));
   
   
// add boundary for each parameters
   
array_walk($body, function (&$part) use ($boundary) {
       
$part = "--{$boundary}\r\n{$part}";
    });
   
   
// add final boundary
   
$body[] = "--{$boundary}--";
   
$body[] = "";
   
   
// set options
   
return @curl_setopt_array($ch, array(
       
CURLOPT_POST       => true,
       
CURLOPT_POSTFIELDS => implode("\r\n", $body),
       
CURLOPT_HTTPHEADER => array(
           
"Expect: 100-continue",
           
"Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
       
),
    ));
}

?>
up
-3
mipa
10 years ago
For PHP < 5.5:

<?php

if (!function_exists('curl_file_create')) {
    function
curl_file_create($filename, $mimetype = '', $postname = '') {
        return
"@$filename;filename="
           
. ($postname ?: basename($filename))
            . (
$mimetype ? ";type=$mimetype" : '');
    }
}

?>
To Top