diff --git a/CUrl.php b/CUrl.php index c573d11..2eb9110 100644 --- a/CUrl.php +++ b/CUrl.php @@ -2,6 +2,8 @@ namespace h4kuna; +use Nette\Utils\Strings; + /** * @author Milan Matějček */ @@ -26,12 +28,12 @@ public function __construct($url = FALSE, array $options = NULL) { $this->resource = $this->init(); if ($options === NULL) { - $options = array(\CURLOPT_HEADER => FALSE, \CURLOPT_RETURNTRANSFER => TRUE, - \CURLOPT_SSL_VERIFYPEER => FALSE, \CURLOPT_SSL_VERIFYHOST => FALSE); + $options = array(CURLOPT_HEADER => FALSE, CURLOPT_RETURNTRANSFER => TRUE, + CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_SSL_VERIFYHOST => FALSE); } if ($url !== FALSE) { - $options += array(\CURLOPT_URL => $url); + $options += array(CURLOPT_URL => $url); } $this->setOptions($options); @@ -47,17 +49,17 @@ public function __construct($url = FALSE, array $options = NULL) { public function __set($name, $value) { $val = strtoupper($name); if (defined($val)) { - return $this->setOption(constant($val), $value); + return $this->setopt(constant($val), $value); } $const = self::OPT . $val; if (defined($const)) { - return $this->setOption(constant($const), $value); + return $this->setopt(constant($const), $value); } $const = self::INFO . $val; if (defined($const)) { - return $this->setOption(constant($const), $value); + return $this->setopt(constant($const), $value); } return parent::__set($name, $value); @@ -129,6 +131,49 @@ static function download($url) { return file_get_contents($url); } + /** + * @example + * $content = array( + * 'foo' => 'bar', + * 'file' => array( + * 'content' => 'file content is simple text', // or path + * 'name' => 'filename.txt', + * 'type' => 'text/plain' + * )); + * + * @param string $url + * @param array $content + * @return CUrl + */ + static function postUploadFile($url, array $content) { + $nl = "\r\n"; + $boundary = '--------CurlBoundary' . Strings::random(18); + $curl = new static($url, array( + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_SSL_VERIFYHOST => 1, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_HEADER => 0, + CURLOPT_POST => 1, + CURLOPT_VERBOSE => 0, + CURLOPT_HTTPHEADER => array('Content-Type: multipart/form-data;charset=utf-8;boundary="' . $boundary . '"')) + ); + $body = ''; + foreach ($content as $name => $value) { + $body .= '--' . $boundary . $nl . 'Content-Disposition: form-data;name="' . $name . '"'; + if (is_array($value)) { + // is file + $body .= ';filename="' . $value['name'] . '"' . $nl; + $body .= 'Content-Type: ' . $value['type']; + $value = file_exists($value['content']) ? file_get_contents($value['content']) : $value['content']; + } + $body .= $nl . $nl . $value . $nl; + } + $body .= "--$boundary--"; + + $curl->setopt(CURLOPT_POSTFIELDS, $body); + return $curl; + } + /** * Close connection * @return void