Php post http request using json - php

Hi I'm trying to send this json object using the POST method but i'm not sure how to include the headers below, i was checking a lot of examples, but no one uses the headers below listed.
This is the code of my php processing page, this page will process the inputs received from a form.html and will create the json object to be transferred to the http server (external platform)
<?php
$host ="10.10.237.8";
$puerto = 21098;
$BUFF = 2048;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$conexion = socket_connect($socket, $host, $puerto);
if($conexion)
{
$msisdn=$_POST["msisdn"];
$mensaje=$_POST["mensaje"];
$php_array = array(
"numero" => $msisdn,
"mensaje" => "$mensaje",
);
$json_array=json_encode($php_array);
echo "Conexion Exitosa, puerto: " . $puerto."\n\n";
echo $json_array;
socket_write($socket, $json_array);
// Receive the results (if any) from the server
$server_response = socket_read($socket, $BUFF);
$decoded_response = json_decode($server_response, true); // decode the data received
echo $decoded_response['passphrase']; // and spit the results
}
else
{
echo "\nLa conexion TCP no se pudo realizar, puerto: ".$puerto;
}
socket_close($socket);
?>
these are the headers information, where i whould include them ? how to do it ? using cURL ? do you have a good example ?
POST /SMBULK/BATCH HTTP/1.0
Authorization: Basic dGVzdDp0ZXN0
Host: 10.10.237.8:21098
Content-Length: 395
User-Agent: Wget/1.12 (solaris2.10)
Content-Type: application/x-www-form-urlencoded
Connection: Keep-Alive
Accept: */*
I hope you can help me. The php code above is not working because some of the information (POST, Content-Length, Content-Type, User-Agent...etc ) is not being included (except "host" which did was included).
I managed to did this but it's not working:
<?php
$str_obj_json='{
"method":"SUBMIT","params":{
"batchType":"submit",
"batchId":"alvarons",
"origAddr":"550",
"origTon":2,
"userData":"Movistar les desea Feliz Navidad",
"submits":
[
{
"messId":"mess127_001",
"destAddr":"51975375377"}
]
}
}';
$ch = curl_init('http://10.10.237.8:21098/SMBULK/BATCH');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_obj_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: 395',
'Authorization: Basic dGVzdDp0ZXN0',
'User-Agent: Wget/1.12 (solaris2.10)',
'Connection: Keep-Alive',
'Accept: */*')
);
$result = curl_exec($ch);
?>
What is wrong ?

To send json object using cUrl you have to add "Content-Type: application/json" to header
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
'Content-type: application/json'
'Content-Length: 395',
'Authorization: Basic dGVzdDp0ZXN0',
'User-Agent: Wget/1.12 (solaris2.10)',
'Connection: Keep-Alive',
'Accept: */*');

Related

Graphql API Call /w Query using PHP

Struggling to figure out how to make graphql api calls with PHP. I'm trying to use the tezos domain API to convert a .tez domain to an address. My query is working well in their "playground", just can't get this translated to php.
Attempt 1:
$apiUrl = 'https://api.tezos.domains/graphql';
$query = '{
domains(where: { name: { in: "' . $wallet . '" } }) {
items {
address
}
}
}';
$data = #file_get_contents($apiUrl, false, stream_context_create([
'http' => [
'method' => 'POST',
'content' => json_encode(['query' => $query]),
]
]));
$results = json_decode($data, true);
echo $results;
$wallet = $results['data'];
Attempt 2:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tezos.domains/graphql" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"query":"{domains(where: {name: { in:"elli0t.tez"}}) {items {address}}}"}');
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Accept-Encoding: gzip, deflate, br',
'Content-Type: application/json',
'Accept: application/json',
'Connection: keep-alive',
'DNT: 1',
'Origin: https://api.tezos.domains' )
);
$result = curl_exec($ch);
print_r($result);
$info = curl_getinfo($ch);
print_r($info);
Attempt 2 at least returns me something.. it says I'm missing a query. Any thoughts?
Here is the curl command generated from the api's playground that appears to work. I'm just having trouble converting this to PHP:
curl 'https://api.tezos.domains/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://api.tezos.domains' --data-binary '{"query":"{\n domains(where: { name: { in: \"elli0t.tez\" } }) {\n items {\n address\n }\n }\n}"}' --compressed
From the GraphQL Docs I found this: a basic query with arguments:
{
human(id: "1000") {
name
height
}
}
Whereas your domains query looks like this:
{
domains(where: { name: { in: "' . $wallet . '" } }) {
items {
address
}
}
}
What strikes me as wrong syntax, because you can't find anywhere in the GraphQL Documentation an example for a structure like:
{
domains(where: { ... })
}
I don't know GraphQL, but I would pinpoint it on the colons inside the argument. The only thing I could find where this is allowed is using variables for creating mutations:
mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!)
{
createReview(episode: $ep, review: $review) {
stars
commentary
}
}
So I guess what might be happening that the domain query breakes, or you are chaining your queries together.
I hope this might help you.

PHP Curl request to public API "Unsupported Media Type"

I try to PHP Curl request. I've got a simple PHP script that sends an HTTP POST request via PHP.
Condition
*Endpoint
https://api.rms.rakuten.co.jp/es/2.0/order/getOrder/
*Request
-Method
"POST"
*Request Header
-Authorization
ESA Base64 (serviceSecret : licenseKey)
*Content-Type
application json; charset=utf-8
*Request Parameter
-Parameter Name/Type
orderNumberList/List <String>
My code(php)
<?php
$serviceSecret = "XXXXXXXXXXXXXXXXXXXXXXXX";
$licenseKey = "XXXXXXXXXXXXXXXXXXXXXX";
$ordernum = "534531-20180618-55345321";
$authkey = base64_encode($serviceSecret . ":" . $licenseKey);
$header = array(
"Content-Type: application/json; charset=utf-8",
"Authorization: ESA {$authkey}"
);
$post = array(
"orderNumberList: {$ordernum}"
);
$url = "https://api.test.com/getOrder/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$xml = curl_exec($ch);
curl_close($ch);
var_dump($xml);
?>
But response is only this.
string(73) "{"Results": {"errorCode": "ES04-03","message": "Unsupported Media Type"}}"
Below is an example Curl code.
curl -X POST \
https://api.test.com/getOrder/ \
-H 'Authorization : ESA xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\
-H 'Content-Type : application / json; charset = utf-8'\
-d '{
"orderNumberList": "543435-20180116-00111801", "524335-20180116-00113801"
}'
Any insights or ideas?
Thanks in advance.

PHP | SOAP 1.2 | How to set WS Addressing

Here is the WSDL ...
I am using the SOAP Client in PHP with documentation HERE ...
Soap Call
$wsdl = 'https://api.krollcorp.com/EBusinessTest/Kroll.Dealer.EBusiness.svc/Docs?singleWsdl';
try {
$client = new SoapClient($wsdl, array('soap_version' => SOAP_1_2, 'trace' => 1));
// $result = $client->SubmitPurchaseOrder();
$result = $client->__soapCall("SubmitPurchaseOrder", array());
} catch (SoapFault $e) {
printf("\nERROR: %s\n", $e->getMessage());
}
$requestHeaders = $client->__getLastRequestHeaders();
$request = $client->__getLastRequest();
$responseHeaders = $client->__getLastResponseHeaders();
printf("\nRequest Headers -----\n");
print_r($requestHeaders);
printf("\nRequest -----\n");
print_r($request);
printf("\nResponse Headers -----\n");
print_r($responseHeaders);
printf("\nEND\n");
Output
ERROR: The SOAP action specified on the message, '', does not match the HTTP SOAP Action, 'http://tempuri.org/IEBusinessService/SubmitPurchaseOrder'.
Request Headers -----
POST /EBusinessTest/Kroll.Dealer.EBusiness.svc HTTP/1.1
Host: api.krollcorp.com
Connection: Keep-Alive
User-Agent: PHP-SOAP/5.6.19
Content-Type: application/soap+xml; charset=utf-8; action="http://tempuri.org/IEBusinessService/SubmitPurchaseOrder"
Content-Length: 200
Request -----
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://tempuri.org/"><env:Body><ns1:SubmitPurchaseOrder/></env:Body></env:Envelope>
Response Headers -----
HTTP/1.1 500 Internal Server Error
Content-Length: 637
Content-Type: application/soap+xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 06 Sep 2017 12:42:57 GMT
END
Attempts
I am a beginner at using SOAP APIs.
I believe this is failing because SOAP 1.2 uses WsHttpBinding instead of BasicHttpBinding.
I am not sure how to set WS Addressing with the SOAP Client in PHP ...
Below code is working for me.You can enable Ws-A Addressing and call soap method-
$client = new SoapClient("http://www.xyz.Services?Wsdl", array('soap_version' => SOAP_1_2,'trace' => 1,'exceptions'=> false
));
$wsa_namespace = 'http://www.w3.org/2005/08/addressing';
$ACTION_ISSUE = 'http://www.xyx/getPassword';// Url With method name
$NS_ADDR = 'http://www.w3.org/2005/08/addressing';
$action = new SoapHeader($NS_ADDR, 'Action', $ACTION_ISSUE, true);
$to = new SoapHeader($NS_ADDR, 'To', 'http://www.xyx.svc/Basic', false);
$headerbody = array('Action' => $action,'To' => $to);
$client->__setSoapHeaders($headerbody);
//$fcs = $client->__getFunctions();
//pre($client->__getLastRequest());
//pre($fcs);
$parameters=array('UserId'=>'12345678','MemberId'=>'123456','Password' => '123456','PassKey' => 'abcdef1234');
;
$result = $client->__soapCall('getPassword', array($parameters));//getPassword method name
print_r(htmlspecialchars($client->__getLastRequest()));// view your request in xml code
print_r($client->__getLastRequest());die; //Get Last Request
print_r($result);die; //print response
Dude, I totally feel your pain. I was able to get this to work but I don't think this is the right way, but it is pointing in the right direction. A caveat though, you have to know what namespace soap_client is going to assign to the addressing. Best way is just to capture the request XML and look for what namespace is attache to the addressing, and then pass it in. Below is my code with a default of 'ns2' for namespace, but you can't count on it for your example. Good Luck!
private function generateWSAddressingHeader($action,$to,$replyto,$message_id=false,$ns='ns2')
{
$message_id = ($message_id) ? $message_id : $this->_uniqueId(true);
$soap_header = <<<SOAP
<{$ns}:Action env:mustUnderstand="0">{$action}</{$ns}:Action>
<{$ns}:MessageID>urn:uuid:{$message_id}</{$ns}:MessageID>
<{$ns}:ReplyTo>
<{$ns}:Address>{$replyto}</{$ns}:Address>
</{$ns}:ReplyTo>
<{$ns}:To env:mustUnderstand="0">$to</{$ns}:To>
SOAP;
return new \SoapHeader('http://www.w3.org/2005/08/addressing','Addressing',new \SoapVar($soap_header, XSD_ANYXML),true);
}
My solution is
Send request using SoapUi
Copy request http log from SoapUi screen ( Bottom of SoapUi program)
Past that code into the PHP project as fallows
$soap_request = '{copy that part from SoapUi http log}';
$WSDL = "**wsdl adres**";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $WSDL);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array(
'Content-Type: application/soap+xml; charset=utf-8',
'SOAPAction: "run"',
'Accept: text/xml',
'Cache-Control: no-cache',
'Pragma: no-cache',
'Content-length: '. strlen($soap_request),
'User-Agent: PHP-SOAP/7.0.10',
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, $soap_request);
$response = curl_exec($ch);
if (empty($response)) {
throw new SoapFault('CURL error: '.curl_error($ch), curl_errno($ch));
}
curl_close($ch);

PHP cURL POST returns a 415 - Unsupported Media Type

I've got a simple PHP script that sends an HTTP POST request via cURL, and expects a json string in response (would have loved to use an existing library like pecl_http/HTTPRequest for this, but can't). The call consistently fails with a 415 error - Unsupported Media Type. I think I'm not configuring cURL correctly, but after much searching, I can't find out what I'm doing wrong. Here's some code:
class URLRequest
{
public $url;
public $headers;
public $params;
public $body;
public $expectedFormat;
public $method;
public function URLRequest($aUrl, array $aHeaders, array $aParams, $aFormat = "json", $isPost = false, $aBody = "+")
{
$this->url = $aUrl;
$this->headers = $aHeaders;
$this->params = $aParams;
$this->expectedFormat = $aFormat;
$this->method = ($isPost ? "POST" : "GET");
$this->body = $aBody;
}
public function exec()
{
$queryStr = "?";
foreach($this->params as $key=>$val)
$queryStr .= $key . "=" . $val . "&";
//trim the last '&'
$queryStr = rtrim($queryStr, "&");
$url = $this->url . $queryStr;
$request = curl_init();
curl_setopt($request, CURLOPT_URL, $url);
curl_setopt($request, CURLOPT_HEADER, 1);
curl_setopt($request, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($request, CURLOPT_SSL_VERIFYPEER, false);
if($this->method == "POST")
{
curl_setopt($request, CURLOPT_POST, 1);
curl_setopt($request, CURLOPT_POSTFIELDS, $this->body);
//this prevents an additions code 100 from getting returned
//found it in some forum - seems kind of hacky
curl_setopt($request, CURLOPT_HTTPHEADER, array("Expect:"));
}
$response = curl_exec($request);
curl_close($request);
preg_match("%(?<=HTTP/[0-9]\.[0-9] )[0-9]+%", $response, $code);
$resp = "";
if($this->expectedFormat == "json")
{
//parse response
}
elseif($this->expectedFormat == "xml")
{
//parse response
}
return $resp;
}
}
$url = "http://mydomain.com/myrestcall";
$query = array( "arg_1" => "test001",
"arg_2" => "test002",
"arg_3" => "test003");
$headers = array( "Accept-Encoding" => "gzip",
"Content-Type" => "application/json",
"Accept" => "application/json",
"custom_header_1" => "test011",
"custom_header_2" => "test012",
"custom_header_3" => "test013");
$body = array( "body_arg_1" => "test021",
"body_arg_2" => array("test022", "test023"),
"body_arg_3" => "test024");
$request = new URLRequest($url, $headers, $query, "json", true, $body);
$response = $request->exec();
...and the response:
HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
X-Powered-By: Servlet 2.5; JBoss-5.0/JBossWeb-2.1
Content-Type: text/html;charset=utf-8
Content-Length: 1047
Date: Mon, 18 Jun 2012 16:30:44 GMT
<html><head><title>JBoss Web/2.1.3.GA - Error report</title></head><body><h1>HTTP Status 415 - </h1><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().</u></p><h3>JBoss Web/2.1.3.GA</h3></body></html>
Any insights or ideas?
Thanks in advance!
Problem solved! Here's the issue:
Sending an associative-array of headers DOES NOT WORK with cURL. There are several forums scattered around that show examples using an associative array for headers. DON'T DO IT!
The correct way (which is also scattered around the internets, but that I'm too dense to have noticed) is to construct your header key/value pairs as strings, and pass a standard array of these strings when setting the CURLOPT_HTTPHEADER option.
So in summary,
WRONG:
$headers = array( "Accept-Encoding" => "gzip",
"Content-Type" => "application/json",
"custom_header_1" => "test011",
"custom_header_2" => "test012",
"custom_header_3" => "test013");
RIGHT:
$headers = array( "Accept-Encoding: gzip",
"Content-Type: application/json",
"custom_header_1: test011",
"custom_header_2: test012",
"custom_header_3: test013");
I hope this comes in handy to some other noble doofus down the road before they waste as much time debugging as I did.
If I had to guess, I would assume that the same rule applies to the POST body key/value pairs as well, which is why #drew010 's comment about using http_build_query() or json_encode() to stringify your message body is a great idea as well.
Thanks to everyone for your very useful comments, and for you time and consideration. In the end, a side by side comparison of the http traffic (captured via Wireshark) revealed the issue.
Thanks!
I think the problem is that you are passing an array as the CURLOPT_POSTFIELDS option. By passing an array, this forces the POST request to use multipart/form-data when the server is probably expecting application/x-www-form-urlencoded.
Try changing
curl_setopt($request, CURLOPT_POSTFIELDS, $this->body);
to
curl_setopt($request, CURLOPT_POSTFIELDS, http_build_query($this->body));
See http_build_query for more information and also this answer: My cURL request confuses some servers?
I had the same problem and I fixed changing the header.
My code:
$authorization = 'authorization: Bearer '.trim($apiKey);
$header = [
'Content-Type: application/json',
$authorization
];
curl_setopt($session, CURLOPT_HTTPHEADER, $header);
I don't know why the array function doesn't work :
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:
application/json',
$authorization));
This worked for me
$data ="data";
$headers = [
"Content-Type: application/json",
"X-Content-Type-Options:nosniff",
"Accept:application/json",
"Cache-Control:no-cache"
];
$auth = $USER . ":" . $PASSWORD;
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_ENCODING, "");
curl_setopt($curl,CURLOPT_MAXREDIRS, 10);
curl_setopt($curl,CURLOPT_TIMEOUT, 0);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_USERPWD, $auth);
curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl);

Youtube Oauth 2.0 API Videos Upload Failed

So i managed to built oauth 2.0 youtube video upload, but everytime i upload a video i get an HTTP 400 ERROR with a invalid request.
But the weirdest thing is that the video is uploading to youtube while having : Failed (upload aborted).
im not using any framework, cause google doesnt have yet any to oauth 2.0, so i built all of my code on my own.
And also i did managed to send comments, and stuff.... the only problem is the video upload itself.
My code:
public function uploadVideo($video, $title, $description, $category, $keywords) {
$url = 'http://uploads.gdata.youtube.com/feeds/api/users/FacebookDevelopersIL/uploads';
$boundary = uniqid();
$accessToken = $this->refreshAccessToken("13", "11313", 'REFRESHTOKEN');
$xmlString = "<?xml version='1.0'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007'><media:group><media:title type='plain'>".$title."</media:title><media:description type='plain'>".$description."</media:description> <media:category scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>".$category."</media:category><media:keywords>".$keywords."</media:keywords></media:group></entry>";
$videoData = file_get_contents($video);
$headers = array(
'POST /feeds/api/users/FacebookDevelopersIL/uploads HTTP/1.1',
'Host: uploads.gdata.youtube.com',
'Authorization: Bearer '.$accessToken,
'GData-Version: 2',
'X-GData-Key: key='.YOUTUBE_SRM_DEVELOPER_KEY,
'Slug: IMG_0047.mp4',
'Content-Type: multipart/related; boundary='.$boundary,
'Content-Length:'.strlen($videoData),
'Connection: close'
);
$postData = "--".$boundary . "\r\n"
."Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n"
.$xmlString . "\r\n"
."--".$boundary . "\r\n"
."Content-Type: video/mp4\r\n"
."Content-Transfer-Encoding: binary\r\n\r\n"
.$videoData . "\r\n"
."--".$boundary . "--";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
$response = curl_exec($ch);
curl_close($ch);
Trace::dump($response); }
The error im getting: HTTP/1.1 400 Bad Request Server: HTTP Upload Server Built on May 7 2012 18:16:42 (1336439802) Content-Type: text/html; charset=UTF-8 X-GUploader-UploadID: AEnB2Uq7cHcf6rS4bcamu18ChAF3gnKJqsF6U_dk2qB4WR9GhAoTL_-iUejitgead-Gh-1fpJcke1z68TAxoopS2vYiGmCW69A Date: Thu, 10 May 2012 11:55:24 GMT Pragma: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Cache-Control: no-cache, no-store, must-revalidate Content-Length: 15 Connection: close
Invalid Request
thanx everyone!
Couple of things I notice: hard coding the POST and Host headers is poor form, because curl will take care of them automatically for you. I suspect part of the problem is the insertion of the carriage return/line feed between the $videoData and the last boundary marker. That will be interpreted as part of the video file. All you need are line feeds as line separators. Maybe the carriage return renders the video file invalid?
Maybe curl_setopt($ch, CURLOPT_VERBOSE, true) will provide some illumination.
This works for me (on a Linux host):
/*
** https://developers.google.com/youtube/2.0/developers_guide_protocol_direct_uploading
*/
private function send_to_youtube($video_file, $video_info) {
// Refresh access token
log_msg("Obtaining access token");
$response = http_post($this->config['token_url'], array(
'client_id' => $this->config['client_id'],
'client_secret' => $this->config['client_secret'],
'refresh_token' => $video_info->refresh_key,
'grant_type' => $this->config['grant_type']
));
if ($response['http_code'] != 200)
throw new Exception("Unable to obtain access token. ".print_r($response, true));
$authorization = json_decode($response['contents'], true);
// Build multi-part upload request
// api xml and then video file contents
$boundary = uniqid();
$location = '';
if ($video_info->latitude && $video_info->longitude)
$location = '
<georss:where>
<gml:Point>
<gml:pos>'. $video_info->latitude .' '. $video_info->longitude .'</gml:pos>
</gml:Point>
</georss:where>';
$content = '--'.$boundary.'
Content-Type: application/atom+xml; charset=UTF-8
<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:georss="http://www.georss.org/georss"
xmlns:gml="http://www.opengis.net/gml">
<media:group>
<media:title type="plain">'. $video_info->title .'</media:title>
<media:description type="plain">
'. $video_info->description .'
</media:description>
<media:category
scheme="http://gdata.youtube.com/schemas/2007/categories.cat">
'. $video_info->category .'
</media:category>
<media:keywords>'. implode(', ', $video_info->tags) .'</media:keywords>
</media:group>
'. $location .'
</entry>
--'.$boundary.'
Content-Type: '. $video_info->type .'
Content-Transfer-Encoding: binary
'.file_get_contents($video_file).'
--'.$boundary.'--';
$headers = array(
'Authorization: '.$authorization['token_type'].' '.$authorization['access_token'],
'GData-Version: 2',
'X-GData-Key: key='.$this->config['dev_key'],
'Slug: '.$video_info->filename,
'Content-Type: multipart/related; boundary="'.$boundary.'"',
'Content-Length: '.strlen($content),
'Connection: close'
);
// Upload video
log_msg("Sending video '{$video_info->title}', {$video_info->url}");
$ch = curl_init($this->config['upload_url']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (!$http_code == 201) { // Something other than 'New Entry'
log_msg("Upload Failed: ".print_r($response, true));
return new SimpleXMLElement();
}
$entry = new SimpleXMLElement($response);
$yt_link = $entry->link[0]->attributes()->href;
log_msg("Upload Complete: ".$yt_link);
return $entry;
}

Categories