Fogbugz XML_API PHP CURL File upload - php

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.

Related

PHP API returning URL with extra "/"s in the URL

I have a YouTube API that I'm using (credited to the owner, obviously) that returns the MP4 link to it. (ex: r5---sn.googlevideo, or whatever google link). I had to edit the code cause the creator even said "This code is not working." So I got it to work, but when it returns I get a link that looks like https:\/\/link.com instead of https://link.com. I went to the link with the extra slashes, and I get https:////link.com, just to be sure.
This is a little Youtube link fetcher because I can't stand seeing websites popup ads and other annoying links, so I thought I'd put one on my own website.
This is the code of the API.
<?php
function YT_IN_DX($url){
$cookie_file_path = "cookies.txt";
$ch = curl_init();
$headers[] = "Connection: Keep-Alive";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_URL, $url);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
function YT_V_INFO($v){
$url = "https://www.youtube.com/get_video_info?video_id=$v";
$html = urldecode(YT_IN_DX($url));
$video_links = Explode_Content('playabilityStatus', 'adSafetyReason', $html);
$json = str_replace("\u0026", "&", $video_links);
$json = '{"playabilityStatus' . $json . 'adSafetyReason":{"isEmbed":true}}';
$array = json_decode($json, true);
if (isset($array["playabilityStatus"]["status"]) && $array["playabilityStatus"]["status"] == "UNPLAYABLE") {
$data = array("error" => $array["playabilityStatus"]["status"]);
}else{
$formats = $array["streamingData"]["formats"];
for ($a = 0; $a <= (count($formats) - 1); $a++){
$data[] = array(
"url" => $array["streamingData"]["formats"][$a]["url"],
"mimeType" => $array["streamingData"]["formats"][$a]["mimeType"],
"quality" => $array["streamingData"]["formats"][$a]["quality"],
"qualityLabel" => $array["streamingData"]["formats"][$a]["qualityLabel"],
"width" => $array["streamingData"]["formats"][$a]["width"],
"height" => $array["streamingData"]["formats"][$a]["height"],
"audioQuality" => $array["streamingData"]["formats"][$a]["audioQuality"],
"approxDurationMs" => $array["streamingData"]["formats"][0]["approxDurationMs"]
);
}
}
return $data;
}
function Explode_Content($first, $last, $string)
{
$exp = explode($first, $string);
$exp = explode($last, $exp[1]);
return $exp[0];
}
if(isset($_GET['url']) && $_GET['url'] != ""){
parse_str( parse_url( $_GET['url'], PHP_URL_QUERY ), $vars );
$id=$vars['v'];
echo json_encode(YT_V_INFO($id),JSON_PRETTY_PRINT);
}else{
#$myObj->error = true;
$myObj->msg = "there is no youtube link";
$myObj->madeBy = "El-zahaby";
$myObj->instagram = "egy.js";
$myJSON = json_encode($myObj,JSON_PRETTY_PRINT);
echo $myJSON;
echo "credit to el3zahaby!";
}
?>
I expected the outcome to be a fine URL, but I get a output of extra slashes.
Maybe you have to escape the backslashes
echo json_encode(YT_V_INFO($id),JSON_UNESCAPED_SLASHES);
or you can also remove the backslashes manually, replace this part, with following code
if(isset($_GET['url']) && $_GET['url'] != ""){
parse_str( parse_url( $_GET['url'], PHP_URL_QUERY ), $vars );
$id=$vars['v'];
$str = json_encode(YT_V_INFO($id),JSON_PRETTY_PRINT);
$str = str_replace('\\', '', $str);
echo $str;

php json_decode is not working Properly

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;
}
}

Submit xml to GSA with PHP / foreach loop

Trying to submit to GSA (google search applicance). Works fine for 1 xml file. But im trying to loop through all files in a directory and submit to the gsa with a loop but cannot get it working.
<?php
$target_url = 'http://1.1.1.1:19900/xmlfeed';
$header = array('Content-Type: multipart/form-data');
$directory = 'xml';
if (! is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ('.' === $file) continue;
if ('..' === $file) continue;
}
//print $file;
$fields = array(
'feedtype'=>'incremental',
'datasource'=>'testing',
'data'=>file_get_contents(realpath($file))
//'data'=>file_get_contents(realpath('test.xml')) //works fine
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_TIMEOUT,120);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$return = curl_exec($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
curl_close ($ch);
echo $return;
?>
Tried adding a foreach loop but that gives me an error that the file is empty.
You should do a request for each file. Put your curl execution in the foreach loop and it should be fine :
<?php
$target_url = 'http://1.1.1.1:19900/xmlfeed';
$header = array('Content-Type: multipart/form-data');
$directory = 'xml';
if (! is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
//List all files in the directory
foreach(glob($directory."/*.*") as $file) {
//Check the file extension
$ext = pathinfo($file, PATHINFO_EXTENSION);
if($ext != 'xml') continue;
//Add the fields
$fields = array(
'feedtype'=>'incremental',
'datasource'=>'testing',
'data'=>file_get_contents($file)
);
//Post the request
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_TIMEOUT,120);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$return = curl_exec($ch);
if (curl_errno($ch)) {
$msg = curl_error($ch);
}
curl_close ($ch);
//Print the result for each file
echo "Result for " . basename($file) . " is : " . $return;
}
?>
It works fine for me. I hope it will help :)

php simplexml with spreadshirt api

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).

Save external files by php

I have an array with urls, like:
[1] = http://site.com/1.pdf
[2] = http://site.com/234234234.png
[3] = http://site.com/archive.zip
[4] = http://site.com/1f41f.anyformat
[5] = http://site.com/file.txt
How do I save them to some folder on my ftp by PHP?
Names of the files should not change.
Here's a simple example:
$urls = array('url1', 'url2');
foreach($urls as $url) {
$data = file_get_contents($url);
file_put_contents('/path/to/folder/'.basename($url), $data);
}
Maybe this will help you solve the question
function remote_merge($sourceurl,$targetftp){
$ch = curl_init ($sourceurl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);
$tempfile = "/path/to/temp/".basename(parse_url($sourceurl, PHP_URL_PATH));
if(file_exists($tempfile)){
unlink($tempfile);
}
$fp = fopen($tempfile,'x');
fwrite($fp, $rawdata);
fclose($fp);
$ch = curl_init();
$fp = fopen($tempfile, "rb");
curl_setopt($ch, CURLOPT_URL, $targetftp);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tempfile));
$error = curl_exec($ch);
// check $error here to see if it did fine or not!
curl_close($ch);
}
Use this to tryout the remote_merge function
$sourceurls = array(
"http://site.com/1.pdf",
"http://site.com/234234234.png",
"http://site.com/archive.zip",
"http://site.com/1f41f.anyformat",
"http://site.com/file.txt"
);
foreach($sourceurl as $sourceurls){
$filename = basename(parse_url($sourceurl, PHP_URL_PATH);
$targetftp = "ftp://${ftpuser}:${ftppasswd}#${ftpserver}${ftppath}/$filename";
remote_merge($sourceurl,$targetftp)
}
193 questions, 3 answers... wow.
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_close ($ch);
return curl_exec($ch);
}
$files = array();
$dir = "dir/";
foreach($files as $file){
$name = explode("/", $file);
$name = end($name);
$contents = curl($file);
file_put_contents($dir.$name, $contents);
}

Categories