I'm trying to use Spreadshirt API to create a product on their platform, but i'm stuck with this weird error:
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/anarchoi/public_html/test.php:102 Stack trace: #0 /home/anarchoi/public_html/test.php(102): SimpleXMLElement->__construct('') #1 {main} thrown in /home/anarchoi/public_html/test.php on line 102
Most of the code is just copied from their wiki so i really don't understand why it doesn't work.
I'm looking for help to understand where the error is coming from and why it is happening.
$productTypeId = "210";
$printTypeId = "17";
$printColorIds = "13,20";
$productTypeAppearanceId = "1";
$productTypePrintAreaId = "4";
$designId = "10438193";
// 1. Get shop data
$shopUrl = "http://api.spreadshirt.com/api/v1/shops/266497";
$ch = curl_init($shopUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$shop = new SimpleXMLElement($result);
$namespaces = $shop->getNamespaces(true);
// 2. Get product type data
$attributes = $shop->productTypes->attributes($namespaces['xlink']);
$productTypeUrl = $attributes->href . "/" . $productTypeId;
$ch = curl_init($productTypeUrl);
// echo "<br>$productTypeUrl<br>";
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$productType = new SimpleXMLElement($result);
// 3. Get design data
$attributes = $shop->designs->attributes($namespaces['xlink']);
$designUrl = $attributes->href . "/" . $designId;
$ch = curl_init($designUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$design = new SimpleXMLElement($result);
// 4. Prepare product
// get positioning data for selected product type
$printArea = null;
foreach ($productType->printAreas->printArea as $current) {
if ($current['id'] == $productTypePrintAreaId) {
$printArea = $current;
}
}
$product = new SimpleXMLElement(getFileData("product.xml"));
$product->productType['id'] = $productTypeId;
$product->appearance['id'] = $productTypeAppearanceId;
$configuration = $product->configurations->configuration;
$configuration->printArea['id'] = $productTypePrintAreaId;
$configuration->printType['id'] = $printTypeId;
$configuration->offset->x =
((doubleval($printArea->boundary->size->width) - doubleval($design->size->width)) / 2);
$configuration->offset->y =
((doubleval($printArea->boundary->size->height) - doubleval($design->size->height)) / 4);
$image = $product->configurations->configuration->content->svg->image;
$image['width'] = $design->size->width;
$image['height'] = $design->size->height;
$image['designId'] = $designId;
$image['printColorIds'] = $printColorIds;
// 5. Create product
$attributes = $shop->products->attributes($namespaces['xlink']);
$productsUrl = $attributes->href;
$header = array();
$header[] = createSprdAuthHeader("POST", $productsUrl);
$header[] = "Content-Type: application/xml";
$ch = curl_init("$productsUrl"."?fullData=true");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $product->asXML());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$productUrl = parseHttpHeaders($result, "Location");
$ch = curl_init($productUrl);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
// Close the handle
curl_close($ch);
$product = new SimpleXMLElement($result);
$resource = $product->resources->resource[0];
$attributes = $resource->attributes($namespaces['xlink']);
echo '<html><body>';
echo 'Product available at: ' . $productUrl . '</br>';
echo 'Product image is available at: ' . $attributes->href . '</br>';
echo '<img src="' . $attributes->href . '?width=1000"/>';
echo '</body></html>';
function createSprdAuthHeader($method, $url) {
$apiKey = "***";
$secret = "***";
$time = time()*1000;
$data = "$method $url $time";
$sig = sha1("$data $secret");
return "Authorization: SprdAuth apiKey=\"$apiKey\", data=\"$data\", sig=\"$sig\"";
}
function parseHttpHeaders( $header, $headername ) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/('.$headername.'): (.+)/m', $field, $match) ) {
return $match[2];
}
}
return $retVal;
}
function getFileData($file) {
$fp = fopen($file, "r");
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
}
product.xml = https://www.ni-dieu-ni-maitre.com/product.xml
I stumbled upon similar issue when implementing Spreadshirt, looks like their API server is sending (at least some) content gzipped regardless of any Accept-Encoding headers. You can tell that it's your case by var_dumping the string before it's passed to SimpleXMLElement (as suggested by others) – if it's gibberish, it's very possible you have the same issue as I did.
Setting the curl option of CURLOPT_ENCODING to an empty string ('') fixed that for me – it "magically" turned on ungzipping the response (see man page for curl_setopt() for more information).
Related
I had tried to send info in a post and a header throw localbitcoins and get one error:
HMAC authentication key and signature was given, but they are invalid
From what i learn with localbitcoins api is this just a code u get when u mess with the header can someone help me to solve why I get this error because don't know whats wrong in my code:
function localbitcoins_query2($path, array $req = Array()) {
$key='mycode';
$secret='mycode';
$mt = explode(' ', microtime());
$nonce = $mt[1].substr($mt[0], 2, 6);
if ($req) {
$get=httpbuildquery($req);
$path=$path.'?'.$get;
}
$postdata=$nonce.$key.$path;
$sign = strtoupper(hash_hmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curl_init();
$data = array("lat" => "Hagrid", "price_equation" => "36");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_URL,"https://localbitcoins.com".$path);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
$res = curl_exec($ch);
if ($res === false) throw new Exception('Curl error: '.curl_error($ch));
$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}
Try this solution:
function localbitcoins_query2($path, array $req = Array()) {
$key='mycode';
$secret='mycode';
$mt = explode(' ', microtime());
$nonce = $mt[1].substr($mt[0], 2, 6);
$get = "";
if ($req) {
$get=httpbuildquery($req);
}
$postdata=$nonce.$key.$path.$get; // NOTE: $postdata without '?' char before the parameters!;
$sign = strtoupper(hash_hmac('sha256', $postdata, $secret));
$headers = array(
'Apiauth-Signature:'.$sign,
'Apiauth-Key:'.$key,
'Apiauth-Nonce:'.$nonce
);
$ch = null;
$ch = curl_init();
$data = array("lat" => "Hagrid", "price_equation" => "36");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_URL,"https://localbitcoins.com".$path.( $get=="" ? "" : "?".$get)); // NOTE: here it's necesary '?' char before the parameters!);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
$res = curl_exec($ch);
if ($res === false) throw new Exception('Curl error: '.curl_error($ch));
$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data: '.$res);
curl_close($ch);
return $dec;
}
This is our class that is called
<?php
class Nest
{
public $debug;
private $username;
private $password;
private $cookieFile;
public function __construct($username, $password, $debug = false)
{
// Set the properties
$this->debug = $debug;
$this->username = $username;
$this->password = $password;
$this->useragent = 'Nest/1.1.0.10 CFNetwork/548.0.4';
$this->cookieFile = tempnam('/tmp', 'nest-cookie');
// Login
$response = $this->curlPost('https://home.nest.com/user/login', 'username=' . urlencode($username) . '&password=' . urlencode($password));
if (($json = json_decode($response)) === false)
throw new Exception('Unable to connect to Nest');
// Stash information needed to make subsequence requests
$this->access_token = $json->access_token;
$this->user_id = $json->userid;
$this->transport_url = $json->urls->transport_url;
}
public function house_state_set($state)
{
switch ($state)
{
case 'away':
$away = true;
break;
case 'home':
$away = false;
break;
default:
throw new Exception('Invalid state given: "' . $state . '"');
}
$status = $this->status_get();
$structure_id = $status->user->{$this->user_id}->structures[0];
$payload = json_encode(array('away_timestamp' => time(), 'away' => $away, 'away_setter' => 0));
return $this->curlPost($this->transport_url . '/v2/put/' . $structure_id, $payload);
}
public function house_state_get()
{
$status = $this->status_get();
$structure = $status->user->{$this->user_id}->structures[0];
list (,$structure_id) = explode('.', $structure);
return ($status->structure->{$structure_id}->away ? 'away' : 'home');
}
public function temperature_set(&$temp)
{
$status = $this->status_get();
$structure = $status->user->{$this->user_id}->structures[0];
list (,$structure_id) = explode('.', $structure);
$device = $status->structure->{$structure_id}->devices[0];
list (,$device_serial) = explode('.', $device);
$temperature_scale = $status->device->{$device_serial}->temperature_scale;
if ($temperature_scale == "F")
{
$target_temp_celsius = (($temp - 32) / 1.8);
}
else
{
$target_temp_celsius = $temp;
}
$payload = json_encode(array('target_change_pending' => true, 'target_temperature' => $target_temp_celsius));
return $this->curlPost($this->transport_url . '/v2/put/shared.' . $device_serial, $payload);
}
public function status_get()
{
$response = $this->curlGet($this->transport_url . '/v2/mobile/user.' . $this->user_id);
if (($json = json_decode($response)) === false)
throw new Exception('Unable to gather the status from Nest');
return $json;
}
private function curlGet($url, $referer = null, $headers = null)
{
$headers[] = 'Authorization: Basic ' . $this->access_token;
$headers[] = 'X-nl-user-id:' . $this->user_id;
$headers[] = 'X-nl-protocol-version: 1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
if(!is_null($referer)) curl_setopt($ch, CURLOPT_REFERER, $referer);
if(!is_null($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($ch, CURLOPT_VERBOSE, true);
$html = curl_exec($ch);
if(curl_errno($ch) != 0)
{
throw new Exception("Error during GET of '$url': " . curl_error($ch));
}
$this->lastURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$this->lastStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $html;
}
private function curlPost($url, $post_vars = '', $referer = null)
{
if (isset($this->access_token)) $headers[] = 'Authorization: Basic ' . $this->access_token;
if (isset($this->user_id)) $headers[] = 'X-nl-user-id:' . $this->user_id;
$headers[] = 'X-nl-protocol-version: 1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars);
if(!is_null($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($ch, CURLOPT_VERBOSE, true);
$html = curl_exec($ch);
$this->lastURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$this->lastStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $html;
}
}
and is called with:
<?php
$new = $_GET['t'];
include_once('nest.php');
$nest = new Nest('usr', 'pwd');
$nest->temperature_set($new);
?>
If I replace $new with a number and then call the function it works but not in it current form. I have tried using the class to call outside variables, tried to just call but cant figure where and why its not working.
I suspect it is not working because your device is configured to use Celsius.
PHP is a dynamically typed language, as is JavaScript, but sometimes people forget that both will change types based on context (and sometimes the type conversion will have unexpected results).
All $_REQUEST variables are strings. Try changing:
$target_temp_celsius = $temp;
To
$target_temp_celsius = $temp + 0;
(JSON is strongly typed)
I'm having trouble scraping an ASPX.NET website. Even after searching through stackoverflow I haven't been able to find a fix.
First off, this is a public accessible website that I'm trying to scrape so that I can email myself a copy occasionally in order to not bother having to go there with a browser.
My code goes so far as to capture the __VIEWSTATE and __EVENTVALIDATION but when I submit the form I get the "Validation of viewstate MAC failed" error.
Any ideas?
<?php
require_once ("simple_html_dom.php");
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Create curl connection
$url = 'http://www.ariautodirect.com/ui/index.aspx';
$cookieFile = 'cookie.txt';
$ch = curl_init();
// We must request the login page and get the ViewState and EventValidation hidden values
// and pass those along in the post request.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setOpt($ch, CURLOPT_REFERER, 'http://www.ariautodirect.com/ui/index.aspx');
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Origin: http://www.ariautodirect.com', 'Host: www.ariautodirect.com'));
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
$curl_scraped_page = curl_exec($ch);
// Grab ViewState and EventValidation data
$html = str_get_html($curl_scraped_page);
$viewState = $html->find("#__VIEWSTATE", 0);
$eventValidation = $html->find("#__EVENTVALIDATION", 0);
$previousPage = $html->find("#__PREVIOUSPAGE", 0);
//create array of data to be posted
// This matches exactly what I am seeing being posted when looking at Fiddler
$post_data['__EVENTTARGET'] = '';
$post_data['__EVENTARGUMENT'] = '';
$post_data['__VIEWSTATE'] = $viewState->value;
$post_data['__EVENTVALIDATION'] = $eventValidation->value;
$post_data['__PREVIOUSPAGE'] = 'Kn9nmdEGkbDIIX-v7Z_vg0t3njAt1lzkUm-uXH6djRcAGjPo6-w6RWKF3BBQz1ijEoJZGJVqOvHTqB5ghEU40C8xhnw1';//hard-coded because $previousPage->value throughs error
$post_data['ctl00$HeaderCtl1$LoginControl1$txtUserName'] = '';
$post_data['ctl00$HeaderCtl1$LoginControl1$txtPassword'] = '';
$post_data['ctl00$HeaderCtl1$LoginControl1$txtClientCode'] = '';
$post_data['ctl00$SearchCriteria1$drpDownMiles'] = '50';
$post_data['ctl00$SearchCriteria1$txtZipCode'] = '30301';
$post_data['ctl00$SearchCriteria1$ddlMake'] = 'All Makes ';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender1_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender2_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender3_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender4_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender5_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender6_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender7_ClientState'] = 'true';
$post_data['ctl00$SearchCriteria1$CollapsiblePanelExtender8_ClientState'] = 'true';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$drpDownMiles'] = '50';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$txtZipCode'] = '30301';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$btnSearch'] = 'Search';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$drpDownPageList'] = '100';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$txtVinSearch'] = '';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$SrtxtClientId'] = '';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$SrtxtVehicleNo'] = '';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$hdnSortYear'] = '';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$hdnSortModel'] = '';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$hdnSortMileage'] = '';
$post_data['ctl00$ContentPlaceHolder1$DataGridResults1$hdnSortPrice'] = '';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = rawurlencode($key) . '=' . rawurlencode($value);
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
$post_string = http_build_query($post_data);
//Set options for post
$urlAcctSummary = "http://www.ariautodirect.com/ui/DisplayResults.aspx";
curl_setopt($ch, CURLOPT_URL, $urlAcctSummary);
curl_setOpt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Origin: http://www.ariautodirect.com', 'Host: www.ariautodirect.com', 'Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setOpt($ch, CURLOPT_REFERER, 'http://www.ariautodirect.com/ui/index.aspx');
// Perform our post request
$curl_scraped_page = curl_exec($ch);
echo $curl_scraped_page;
curl_close($ch);
?>
When i am Decoding using commented "$jsonString" String it is working very well.
But after using curl it is not working, showing Null.
Please Help Me in this.
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
$url = 'http://ExampleStatus.php?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// $jsonString = '[{"branchname":"BHUBNESHWAR","consignee":"ICICI BANK LTD","currentstatus":"Delivered by : BHUBNESHWAR On - 25/07/2015 01:00","dlyflag":"Y","PODuploaded":"Not Uploaded"}]';
if ($jsonString != '') {
$json = str_replace(array('[', ']'), '', $jsonString);
echo $json;
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
}
}
After curl I used following concept to get only JSON data from HTML Page.
1) fetchData.php
$url = 'http://DocketStatusApp.aspx?dkno=' . $dcktNo;
$myvars = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonString = curl_exec($ch);
// now get only value
$dom = new DOMDocument();
$dom->loadHTML($jsonString);
$thediv = $dom->getElementById('Label1');
echo $thediv->textContent;
2) JSONprocess.php
if (isset($_POST['dkno'])) {
$dcktNo = $_POST['dkno'];
ob_start(); // begin collecting output
include_once 'fetchData.php';
$result = ob_get_clean(); // Completed collecting output
// Now it will show & take only JSON Data from Div Tag
$json = str_replace(array('[', ']'), '', $result);
$obj = json_decode($json);
if (is_null($obj)) {
die("<br/>Invalid JSON, don't need to keep on working on it");
} else {
$podStatus = $obj->PODuploaded;
}
}
I have built a php script which receives values in $_POST and $_FILES
I'm catching those values, and then trying to use CURL to make posts to FogBugz.
I can get text fields to work, but not files.
$request_url = "http://fogbugz.icarusstudios.com/fogbugz/api.php";
$newTicket = array();
$newTicket['cmd'] = 'new';
$newTicket['token'] = $token;
$newTicket['sPersonAssignedTo'] = 'autobugz';
$text = "\n";
foreach( $form as $pair ) {
$text .= $pair[2] . ": " . $pair[0] . "\n";
}
$text = htmlentities( $text );
$newTicket['sEvent'] = $text;
$f = 0;
foreach ($_FILES as $fk => $v) {
if ($_FILES[$fk]['tmp_name'] != '') {
$extension = pathinfo( $_FILES[$fk]['name'], PATHINFO_EXTENSION);
//only take the files we have specified above
if (in_array( array( $fk, $extension ) , $uploads)) {
$newTicket['File'.$f] = $_FILES[$fk]['tmp_name'];
//echo ( $_FILES[$fk]['name'] );
//echo ( $_FILES[$fk]['tmp_name'] );
//print $fk;
//print '<br/>';
//print_r( $v );
}
}
}
$ch = curl_init( $request_url );
$timeout = 5;
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_POSTFIELDS, $newTicket );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
To upload files with CURL you should prepend a # to the path, see this example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"#/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
Taken from http://dtbaker.com.au/random-bits/uploading-a-file-using-curl-in-php.html.
The other answer -- for FogBugz reasons only --
$f cannot be set to 0 initially. It must be 1, so the files go through as File1, File2, etc.
The # symbol is also key.