note 87277 rejected from function.curl-setopt by thiago

From: Date: Thu, 27 Nov 2008 14:05:04 +0000
Subject: note 87277 rejected from function.curl-setopt by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-147037@lists.php.net to get a copy of this message
Note Submitter: marceloburegio at gmail dot com ---- I've a problem when tried to use upload file with different content-type (adding ;type=content-type after filename). I write below a workaround to fix this, and now works for me. It's substitue curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arrData)); If you have the same problem, use this solution. PS: If you have simulate upload with no file, use "filename" => "@" only. <?php function postWithFiles($ch, $arrData) { $arrHeaders = array(); $strContents = ""; // Generate unique ID $strUniqueId = substr(md5(uniqid(rand(), true)), 0, 12); $strBoundary = "----------------------------". $strUniqueId; // Overwrite Content-Type header for multipart/form-data - First Boundary $arrHeaders[] = "Content-Type: multipart/form-data; boundary=". $strBoundary; curl_setopt($ch, CURLOPT_HTTPHEADER, $arrHeaders); foreach ($arrData as $strName => $strData) { // Add Boundary $strContents .= "--". $strBoundary ."\r\n"; // Check if is file and if contents content type tag if (preg_match("/@([^;]*)(;type=(.*))?/", $strData, $arrFile)) { $strFileName = $arrFile[1]; $strContentType = (!empty($arrFile[3])) ? $arrFile[3] : "application/octet-stream"; $strContents .= 'Content-Disposition: form-data; name="'. $strName .'"; filename="'. basename($strFileName) .'"'."\r\n"; $strContents .= 'Content-Type: '. $strContentType ."\r\n"; $strContents .= "\r\n"; if (file_exists($strFileName)) $strContents .= file_get_contents($strFileName); $strContents .= "\r\n"; } else { $strContents .= 'Content-Disposition: form-data; name="'. $strName .'"'."\r\n"; $strContents .= "\r\n"; $strContents .= $strData ."\r\n"; } } // Last Boundary $strContents .= "--". $strBoundary ."--\r\n"; curl_setopt($ch, CURLOPT_POSTFIELDS, $strContents); } ?>

« previous php.notes (#147037) next »