PHP Curl GET & POST - php

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.

Related

How to start session with php code

I would like to send request to server. I am using this code for it
$data=[..];
$header=[
"Accept-language: en-US,en;q=0.5",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection: keep-alive",
"Host: www.rvvi.cz",
"Referer: https://www.rvvi.cz/riv?s=rozsirene-vyhledavani",
"Upgrade-Insecure_Requests:1",
"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/2010",
"Cookie: PHPSESSID=4ck9tc3vm4prgfubnjvutilgd2",
"Content-type: application/x-www-form-urlencoded"
];
$url = "https://www.rvvi.cz/riv";
$query = http_build_query($data);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST,strlen($query));
curl_setopt($ch,CURLOPT_POSTFIELDS,$query);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$page=curl_exec($ch);
echo($page);
but problem is with PHPSESSID in header. To access that, i have to manually go to this server with my browser ( this that probably start my SESSION ), copy PHPSESSID and paste it into my script. But, i would like to make this script automatic. I need to to active them from my server without using browser or copying something.
Is there any way how can i start this session just with my php code?
$curl = curl_init( 'https://httpbin.org/post' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_POSTFIELDS, array( 'field1' => 'some data', 'field2' => 'some more data' ) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $curl );
curl_close( $curl );

firebase messaging api php subscribe to topic 411 error

I am trying to implement notifications into my web app. I have this php file in which I send notifications:
<?php
function sendGCM($title,$message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
"notification" => array(
"title" => $title,
"body" => $message,
"click_action" => "https://google.com"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . $MY_KEY,
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
?>
Now what I want to do is to send a notification to a topic instead of individual ids. On this page it shows how you can subscribe an id to a topic. Here is the function I created to do that:
function createTopic($topic,$id) {
$url = 'https://iid.googleapis.com/iid/v1/' . $id . '/rel/topics/' . $topic;
$headers = array (
'Authorization: key=MY_KEY'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
I am getting this error from Google and I can't figure out what is going wrong:
That’s an error.
POST requests require a Content-length header. That’s all we know.
Any help?
The example in the documentation shows use of a Content-Length header:
https://iid.googleapis.com/iid/v1/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA/rel/topics/movies
Content-Type:application/json
Content-Length: 0
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
Add that to your request:
$headers = array (
'Authorization: key=' . $MY_KEY,
'Content-Length: 0'
);

Google Firebase iOS push works in console but not in API

I'm using https://github.com/arnesson/cordova-plugin-firebase/ to receive Google Firebase messages on a ionic based app.
After set certificates, install plugin and setup Firebase account I was able to receive notifications (on both android and ios devices) sended through the Firebase Console.
But when I send through the Firebase API (https://firebase.google.com/docs/cloud-messaging/http-server-ref) only android devices receive the notification. I'm using the following code:
$data = Array
(
[to] => <token>
[notification] => Array
(
[title] => My Title
[text] => Notification test
[sound] => default
[vibrate] => 1
[badge] => 0
)
)
$jsonData = json_encode($data);
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
$header = array(
'Content-Type: application/json',
"Authorization: key=".$gcmApiKey
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
No errors are returned:
{"multicast_id":904572753471539870406,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1477063422322568734%3d5c78243d5c7824"}]}
What can be wrong?
For iOS, try adding in parameter priority set to high and content_available set to true in your payload.
See the parameter details here.
try this code
function sendGCM($message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => $message
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_KEY_HERE",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
}
?>
also try it in curl terminal
curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"body\":\"Yellow\"},\"priority":10}"
a little late but with working example,
I'm using the code below for ios and android push, you are missing the priority and content_available fields
example :
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $token,
'notification' => array('body' => $message , "sound" => "default"),
'data' => $message,
"sound"=> "default",
'priority' => "high" ,
'content_available' => false
);
$headers = array(
'Authorization:key = your-key',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);

calling REST cloudsight api in php

I am trying to use cloudsight API (http://cloudsight.readme.io/v1.0/docs) that requires me to use both POST and GET. I've never used a REST API before but after doing some research found that to POST using PHP would work.
I found the following code in the api documentation but am not sure how to convert this command line curl to PHP. The response is in JSON.
curl -i -X POST \
-H "Authorization: CloudSight [key]" \
-F "image_request[image]=#Image.jpg" \
-F "image_request[locale]=en-US" \
https://api.cloudsightapi.com/image_requests
curl -i \
-H "Authorization: CloudSight [key]" \
https://api.cloudsightapi.com/image_responses/[token]
If you're still interesting by the answer :
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests" );
$postFields = array(
'image_request' => array(
'remote_image_url' => $url,
'locale' => 'en-US'
)
);
$fields_string = http_build_query($postFields);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: CloudSight [key]', "Content-Type:multipart/form-data" ) );
curl_exec( $ch );
curl_close( $ch );
If using the php curl library, you can do this for the POST:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://api.cloudsightapi.com/image_requests" );
$postFields = array(
'image_request' => array(
'image' => '#/path/to/image.jpeg',
'locale' => 'en-US'
)
);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Authorization: CloudSight [key]' ) );
curl_exec( $ch );
curl_close( $ch );
PHP>=5.5 also provides a CURLFile class (http://php.net/manual/en/class.curlfile.php) for working with files instead of passing the path, as in the example above.
For the GET, you can just remove these two lines and alter the url:
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
Another option would be to use Guzzle if you use Composer in your project ( http://guzzle.readthedocs.org/en/latest/).

PHP: Cannot retrieve correct ajax response using curl or file_get_contents

Start page
Frame page
End page
I can't figure out what I'm missing. I've tried mimicking the firefox request headers, but it doesn't work.
Also, the frame page reaches the end page using a javascript ajax request. It posts the data to $post_to_link (see code below) then navigates to the expected result (not my current result), where the megaupload link is located.
Expected output:
/membersonly/components/com_iceplayer/GMorBMlet.php?url=http%3A%2F%2Fwww.megaupload.com%2F%3Fd%3DVNICBFWL&
Current output:
file_get_contents outputs 3
curl outputs error 403 forbidden access
Here is my code:
// call it like so...
echo GetHosterLink( 1148, 252636, '', '37fn8Oklq', 15, -75 );
// $s is incremented every second you are 'visiting' the referer page
// $m decreases below zero when you move your mouse `down` on the start page
function GetHosterLink( $id, $link_id, $cap, $sec, $s, $m )
{
$link_page = str_replace( '[ID]', $id, 'http://www.icefilms.info/membersonly/components/com_iceplayer/video.php?vid=[ID]' );
$post = "id={$link_id}&s={$s}&iqs=&url=&m={$m}&cap=&sec={$sec}&t={$id}";
$header = implode( "\r\n", array(
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Accept-Encoding: gzip, deflate",
"Accept-Language: en-us,en;q=0.5",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: " . strlen( $post ),
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
"Host: www.icefilms.info",
"Pragma: no-cache",
"Referer: http://www.icefilms.info/membersonly/components/com_iceplayer/video.php?h=374&w=631&vid={$id}&img=",
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0"
));
$opts = array('http' =>
array(
'method' => 'POST',
'header' => implode("\r\n",
array(
'Content-type: application/x-www-form-urlencoded',
'Content-length: ' . strlen( $post ),
'Referer: ' . $link_page . '&h=374&w=631',
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0',
'Host: www.icefilms.info'
)
),
'content' => http_build_query(
array(
'id' => $link_id,
's' => $s,
'sec' => $sec,
't' => $id,
'm' => $m,
'iqs' => '',
'url' => '',
'cap' => ''
)
)
)
);
$context = stream_context_create($opts);
$post_to_link = 'http://www.icefilms.info/membersonly/components/com_iceplayer/video.phpAjaxResp.php';
$get_result = file_get_contents( $post_to_link, false, $context );
$f_result = cURL::DoRequest( $post_to_link, $post, '',
array( array( CURLOPT_HTTPHEADER, $header ) ) );
$f_r = array(
'result' => $f_result,
'get_result' => $get_result,
'get_opts' => $opts,
'get_response' => $http_response_header,
'req_post' => $post,
'req_href' => $post_to_link,
'req_header' => $header
);
return ( $f_r );
}
Here is my curl.php file:
class cURL
{
public static function DoRequest( $url, $post = '',
$cookie_file = '', $variables = array() )
{
$curl = curl_init();
#session_start();
$cookie = ( 'PHPSESSID=' . session_id() . '; path=/' );
#session_write_close();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_COOKIE, $cookie );
if ( !empty( $cookie_file ) )
{
curl_setopt( $curl, CURLOPT_COOKIEFILE, $cookie_file );
curl_setopt( $curl, CURLOPT_COOKIEJAR, $cookie_file );
}
if ( !empty( $post ) )
{
//curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post );
}
foreach ( $variables as $var )
curl_setopt( $curl, $var[0], $var[1] );
$result = curl_exec( $curl );
curl_close( $curl );
return ( $result );
}
}
Try visiting initial page (the one's url you have in $link_page) with curl and make sure the file you point to in:
curl_setopt( $curl, CURLOPT_COOKIE, $cookie );
exists and is writeable.
Then request the $post_to_link url with same curl resource.
By visiting the initial page you are getting cookies and making sure there is a valid session for your next request. That also secures the referer you then provide in headers. There are many ways to figure "automatic" requests, and things like checking cookie and if you actually visited "referer"-ed link are quite common.

Categories