i'm new to curl.
i have this curl code.
but i have no idea about run this with php
curl -X POST -u "{username}":"{password}"
--header "Content-Type: audio/flac"
--data-binary "#audio-file1.flac"
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true&word_alternatives_threshold=0.9&keywords=%22colorado%22%2C%22tornado%22%2C%22tornadoes%22&keywords_threshold=0.5"
this is my php code.but not sure that i'm correct.
$s = curl_init();
curl_setopt($s, CURLOPT_URL, 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true&word_alternatives_threshold=0.9&keywords=%22colorado%22%2C%22tornado%22%2C%22tornadoes%22&keywords_threshold=0.5');
curl_setopt($s, CURLOPT_POST, 1);
curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query([
'--header' => "Content-Type: audio/flac",
'--data-binary' => '#audio-file1.flac'
]));
curl_exec($s);
curl_close($s);
please help me how to add -u "{username}":"{password}" to php code?
the good way to do this, is with a file handle and CURLOPT_INFILE, this will work with files of any size, and allows the upload to start before the entire file has been read from disk, thus it's faster and use just a small amount of memory, no matter how big the file is. however, the quick'n easy way, which puts the entire file in memory at once, and doesn't start the upload until the entire file has been read into ram, and is thus unsuitable for big files, is simply: curl_setopt($ch,CURLOPT_POSTFIELDS,file_get_contents($filename));, but.. the rough equivalent to your curl command, using the good method, is:
$ch = curl_init ();
$filename = "audio-file1.flac";
$fileh = fopen ( $filename, 'rb' );
curl_setopt_array ( $ch, array (
CURLOPT_USERPWD => "{username}:{password}",
CURLOPT_HTTPHEADER => array (
'Content-Type: audio/flac'
),
CURLOPT_POST => 1,
CURLOPT_INFILE => $fileh,
CURLOPT_INFILESIZE => filesize ( $filename ),
CURLOPT_URL => "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true&word_alternatives_threshold=0.9&keywords=%22colorado%22%2C%22tornado%22%2C%22tornadoes%22&keywords_threshold=0.5",
CURLOPT_USERAGENT => 'libcurl/' . curl_version () ['version'] . '; php/' . PHP_VERSION
) );
// curl_setopt ( $ch, CURLOPT_URL, '127.0.0.1:9999' );
curl_exec ( $ch );
fclose ( $fileh );
curl_close ( $ch );
Related
I am trying to authenticate to third party ticketing system, connect and retrieve agent info. I then want to parse retrieved file so as to only show specific info such as 'id' and' 'active_since', but I get an NULL error in browser. Any help?
FILE RETURNED BY THIRDPARTY
[agent] => Array
(
[active_since] => 2015-11-30T08:09:26-01:00
[available] => 1
[created_at] => 2015-05-14T19:15:18+00:00
[id] => XXXXX
[occasional] =>
[points] => 5520
[scoreboard_level_id] => 5000402007
[signature] =>
[signature_html] =>
Below is the PHP CURL code.
<?php
$username = "xxxxxxx";
$password = "xxxxxxx";
$url = 'http://support.xxxx.com/agents/xxx132067';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'header' => "Authorization: Basic " . base64_encode("$username:$password")
)
);
$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
$array["active_since"];
?>
Remove the 'header' => from the Authorization header. And it should be as below:
"Authorization: Basic " . base64_encode("$username:$password")
And I didn't see you are calling curl at all. Replace your file_get_contents with proper curl call.
$result = curl_exec($cURL);
curl_close($cURL);
I want to fetch content from my Atlassian with username and password.
The URL typically looks like:
http://my-own-site.atlassian.net/wiki/pages/viewpage.action?spaceKey=TO&title=Any-Wiki-Title
Is it possible to use PHP CURL to fetch content from this page?
So far I am only getting 401 auth reqd error.
I have looked through Stackoverflow and all I am getting is how to access basic atlassian.com and bitbucket.org pages.
With this code in php, you can create Confluence Pages:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8090/rest/api/content/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"type\":\"page\",\"title\":\"**inserttitle**\",\"space\":{\"key\":\"**insertspace**\"},\"ancestors\":[{\"type\":\"page\",\"id\":**insertancestor**}],\"body\":{\"storage\":{\"value\":\"<p>This is a new page</p>\",\"representation\":\"storage\"}}}");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "**insertusername**" . ":" . "**insertpassword**");
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
?>
And with this code, you can get content from Confluence:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8090/rest/api/content/**insertid**");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_USERPWD, "**insertusername**" . ":" . "**insertpassword**");
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
?>
echo $result;
Modify the parameter. I marked the words with insert*
Yes, it is certainly possible to access Atlassian products using PHP and cURL. I do it all the time to create/modify Jira issues
You will have to find/write a library (or set of libraries) which will allow you to access REST API calls. In my case, I wrote a base REST library which can then be inherited to create Jira, Confluence, any other REST service libraries
Search the Atlassian documentation site to find the REST API for the product you're using (Confluence in your case I would guess)
Don't forget that the REST API uses GET, POST, PUT and DELETE methods so your library will need to handle all of these
With regards to your error, I *think* your login will need to be allowed access to the API calls
To retrieve any existing content properties for a piece of content, use url as https://your-domain.atlassian.net/wiki/rest/api/content/{content_ID}
$curl = curl_init();
$post = array(
"id" => "{content_ID}",
"type" => "{content_ID}", //Ex. page
"title" => "{content_Title}",
"space" => ["key" => "{spaces_key}"],
"body" => ["storage" => ["value" => "<p>Here comes the other text</p>", "representation" => "storage"]],
"version" => ["number" => 15]
);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://your-domain.atlassian.net/wiki/rest/api/content/{content_ID}?expand=metadata.properties.myprop,space,body.view,version,container",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 300,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => json_encode($post),
CURLOPT_HTTPHEADER => array(
"authorization: Basic {base64 of (username:password)}",
"content-type: application/json",
'Accept: application/json'
),
));
$result = curl_exec($curl);
curl_close($curl);
I am going to convert some file using php and send it as a part of HTTP POST request.
There is part of my code:
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: " . $this->contentType."",
'content' => "file=".$file
)
));
$data = file_get_contents($this->url, false, $context);
Does variable $file have to be byte representation of the file which I want to send?
And is that correct way to send file in php without using form? Have you got any clues?
Also what is the way to convert file to byte representation using PHP?
You may find it much easier to use CURL, for example:
function curlPost($url,$file) {
$ch = curl_init();
if (!is_resource($ch)) return false;
curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , 0 );
curl_setopt( $ch , CURLOPT_FOLLOWLOCATION , 0 );
curl_setopt( $ch , CURLOPT_URL , $url );
curl_setopt( $ch , CURLOPT_POST , 1 );
curl_setopt( $ch , CURLOPT_POSTFIELDS , '#' . $file );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $ch , CURLOPT_VERBOSE , 0 );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Where $url is where you want to post to, and $file is the path to the file you want to send.
Oddly enough I just wrote an article and illustrated this same scenario. (phpmaster.com/5-inspiring-and-useful-php-snippets). But to get you started, here's code that should work:
<?php
$context = stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: multipart/form-data; boundary=--foo\r\n",
"content" => "--foo\r\n"
. "Content-Disposition: form-data; name=\"myFile\"; filename=\"image.jpg\"\r\n"
. "Content-Type: image/jpeg\r\n\r\n"
. file_get_contents("image.jpg") . "\r\n"
. "--foo--"
)
));
$html = file_get_contents("http://example.com/upload.php", false, $context);
In situations like these it helps to make a mock web form and run it through Firefox with firebug enabled or something, and then inspect the request that was sent. From there you can deduce the important things to include.
I'm curling a URL with the following code at the moment, which works fine with either the get attached to the end of the URL or the POST data. But not with the get and the post.
However when I use the advanced rest client (add on for google chrome) it works just fine. Annoyingly though, I can't see the request that it sends to mimic it.
Heres the call i'm making with it.
$fields = array(
'searchPaginationResultsPerPage'=>500 );
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, 'http://www.microgenerationcertification.org/mcs-consumer/installer-search.php?searchPaginationPage=1' );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_POST,count($fields));
curl_setopt($curl,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 80);
$str = curl_exec($curl);
curl_close($curl);
Just using this as a bit of a test more than anything else, but can't seem to get it working. I can get the first 500 results all the time, but not the next 500.
This works
$fields = array (
'searchPaginationResultsPerPage' => 500,
'searchPaginationPage' => 1
);
$headers = array (
"Connection: keep-alive",
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding: gzip,deflate,sdch",
"Accept-Language: en-US,en;q=0.8",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3"
);
$fields_string = http_build_query ( $fields );
$cookie = 'cf6c650fc5361e46b4e6b7d5918692cd=49d369a493e3088837720400c8dba3fa; __utma=148531883.862638000.1335434431.1335434431.1335434431.1; __utmc=148531883; __utmz=148531883.1335434431.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); mcs=698afe33a415257006ed24d33c7d467d; style=default';
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.microgenerationcertification.org/mcs-consumer/installer-search.php?searchPaginationPage=1&searchPaginationResultsPerPage=500' );
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 80 );
curl_setopt ( $ch, CURLOPT_COOKIE, $cookie );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
$str = curl_exec ( $ch );
curl_close ( $ch );
echo $str;
You needed cookie information and make sure curl is using GET not POST
See Demo : http://codepad.viper-7.com/gTThxX (I hope the cokkies is not expired before you view it )
Not sure why that fails, looks fine.. What happens when you skip CURL and go for the PHP stream method:
$postdata = http_build_query(
array(
'searchPaginationResultsPerPage' => 500
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://www.microgenerationcertification.org/mcs-consumer/installer-search.php?searchPaginationPage=1', false, $context);
I had a look at the page you are scraping and noticed the following:
When you change the results per page it posts your search again
They appear to be using the session to store your search parameters
You are not preserving the session ID when using CURL (and doing so is probably a bit more complex than you'd like) so this will not behave the same as on the website.
I did notice however that if you append the searchPaginationResultsPerPage parameter to the URL it works fine. Like this:
http://www.microgenerationcertification.org/mcs-consumer/installer-search.php?searchPaginationPage=0&searchPaginationResultsPerPage=500
That means you could actually use file_get_contents and not worry about the CURL stuff.
Hi I am trying to build php youtube api without a Zend function
this is what I have till now:
function upload() {
$files = $_FILES;
$name = $files['file']['name'];
$type = $files['file']['type'];
$size = $files['file']['size'];
$tmp_nm = $files['file']['tmp_name'];
$data = array('name' => 'Foo', 'file' => '#'.$tmp_nm);
print_r($_POST);
print_r($_FILES);
echo 'Size '.$size;
$headers = array(
"Authorization: AuthSub token=".$this->auth,
"GData-Version: 2",
"X-GData-Key: key=".$this->dev_key,
"Content-length: ".$size,
"API_XML_request"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/action/GetUploadToken');
curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_REFERER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_HEADER,0);
if($this->get_info)
{
$this->curlget_info($ch);
}
$output = curl_exec($ch);
print_r($output);
return $output;
}
The errors I get:
Output 1
Array ( [token] => TOKEN ) Array ( [file] => Array ( [name] => 0016.png [type] => image/png [tmp_name] => D:\wamp\tmp\php178D.tmp [error] => 0 [size] => 4216 ) ) Size 4216
Google
Error
Length Required
POST requests require a Content-length header.
Output 2
Array ( [token] => TOKEN ) Array ( [file] => Array ( [name] => Film.wmv [type] => video/x-ms-wmv [tmp_name] => D:\wamp\tmp\php11D3.tmp [error] => 0 [size] => 96589 ) ) Size 96589
Google
Error
Length Required
POST requests require a Content-length header.
I am using this guide.
I am trying to solve this for 5 days and I asked couple irc channels and forums. A friend linked me here to ask, I hope someone will help me :))
I don't have a developer key so I can't help you out directly, but clearly Google has a problem with your http header so you have to find out what you're sending in the header, not the message body. The best way to do this is to inspect the packet on the wire as it leaves your machine.
So install Wireshark, start it up on your WAMP server, start capturing packets, do your test, and then look at the http connection in the packet. Make sure it's what you expect.
Or maybe there's a way for curl to write the packet to a file instead of the server for debugging purposes. I don't know.
Also it's a long shot (and would rely on them being out of spec), but I noticed that you and that other person you linked to have "Content-length". Try "Content-Length" to match the example.
Not sure if this is the answer, but in the example page, they put quotes around the authsub token:
Authorization: AuthSub token="DXAA...sdb8"
Maybe try that?