How to properly retrieve POST data through cURL and PHP? - php

I am trying to extract the data from this web page:
https://portal.icuregswe.org/siri/report/corona.vtfstart
I have identified that this data can be retrieved from https://portal.icuregswe.org/siri/api/reports/GenerateHighChart (POST). My attempted solution in PHP using cURL is as follows:
$url = 'https://portal.icuregswe.org/siri/api/reports/GenerateHigh';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Host: portal.icuregswe.org',
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
'Accept: application/json, text/plain, */*',
'Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding: gzip, deflate, br',
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: 179',
'Origin: https://portal.icuregswe.org',
'Connection: keep-alive',
'Referer: https://portal.icuregswe.org/siri/report/corona.vtfstart',
'Cookie: _ga=GA1.2.1861236498.1591648329; _gid=GA1.2.1182050970.1608386303',
'Pragma: no-cache',
'Cache-Control: no-cache'));
$output = curl_exec ($ch);
print $output;
curl_close ($ch);
I am expecting to retrieve the raw data but instead I am getting HTTP Error 400. The header is generated by accessing the given url in Firefox. Any help would be appreciated how to solve this problem.

there's no need to lie on the useragent, they don't run a user-agent blacklist; but it does require a bunch of POST parameters, and in fact, you don't need ANY of those headers (well, except the Content-Type header, but curl will add that for you automatically when setting CURLOPT_POSTFIELDS to a string, so you don't need to add it yourself, where you might risk introducing typos, while curl won't, so it's better if you don't), this
<?php
declare(strict_types=1);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://portal.icuregswe.org/siri/api/reports/GenerateHighChart',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query(array(
'highChartUrl' => '/api/reports/GenerateHighChart',
'tableUrl' => '/api/reports/GenerateExcel',
'chartWidth' => '900',
'reportName' => 'corona.vtfstart',
'startdat' => '2020-01-01',
'stopdat' => '2020-12-19',
'sasong' =>
array(
0 => '2020',
),
))
));
curl_exec($ch);
outputs:
{"ReportName":"Antal nyinskrivna vårdtillfällen med Coronavirus \\n Period ###","ChartTitle":"Antal nyinskrivna vårdtillfällen med Coronavirus ","ChartSubTitle":" Period 2020-01-01 - 2020-12-19","ChartColors":["#53a8c3","#ee5773","#f0d86e","#f6854f","#15ceac","#5773ee","#f597a9","#df7f23","#10a085","#986ef0"],"YaxisTitle":"Antal vtf","YaxisTitleColor":"","HasY2Axis":false,"Y2axisTitle":null,"Y2axisTitleColor":null,"XaxisTitle":"Datum","XaxisColors":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"Credits":"Detta är en originalrapport från Svenska Intensivvårdsregistret","SqlString":"<b>-- SQL-sats 1</b><br />SELECT<br /> DATEADD(DAY, 0, DATEDIFF(DAY, 0, Xa.VtfStart)) AS vtfstartdag#0,<br /> SUM(CASE WHEN Xa.InfEnkatSiriLabfyndId=3 THEN 1 ELSE 0 END) AS antalcorona#1,<br /> COUNT(DISTINCT Xa.PersonId) AS antalpersoner#2<br />FROM<br /> vueSiri AS Xa<br />WHERE<br /> (Xa.InfEnkatSiriLabfyndId=3) AND ((Xa.VtfStart>='2020-01-01 00:00:00') AND (Xa.VtfStart<='2020-12-19 23:59:00'))<br />GROUP BY<br /> DATEADD(DAY, 0, DATEDIFF(DAY, 0, Xa.VtfStart))<br />ORDER BY<br /> vtfstartdag#0<br /><br />","ChartSeries":[{"Name":"Antal vtf","Stack":null,"Type":"column","Color":"","Data":[{"Value":1.0,"Name":"2020-03-06 00:00:00","Color":null},{"Value":1.0,"Name":"2020-03-07 00:00:00","Color":null},{"Value":1.0,"Name":"2020-03-08 00:00:00","Color":null},{"Value":1.0,"Name":"2020-03-09 00:00:00","Color":null},{"Value":3.0,"Name":"2020-03-10 00:00:00","Color":null},{"Value":1.0,"Name":"2020-03-11 00:00:00","Color":null},{"Value":3.0,"Name":"2020-03-13 00:00:00","Color":null},{"Value":7.0,"Name":"2020-03-14 00:00:00","Color":null},{"Value":6.0,"Name":"2020-03-15 00:00:00","Color":null},{"Value":6.0,"Name":"2020-03-16 00:00:00","Color":null},{"Value":3.0,"Name":"2020-03-17 00:00:00","Color":null},{"Value":15.0,"Name":"2020-03-18 00:00:00","Color":null},{"Value":13.0,"Name":"2020-03-19 00:00:00","Color":null},{"Value":20.0,"Name":"2020-03-20 00:00:00","Color":null},{"Value":19.0,"Name":"2020-03-21 00:00:00","Color":null},{"Value":33.0,"Name":"2020-03-22 00:00:00","Color":null},{"Value":45.0,"Name":"2020-03-23 00:00:00","Color":null},{"Value":44.0,"Name":"2020-03-24 00:00:00","Color":null},{"Value":43.0,"Name":"2020-03-25 00:00:00","Color":null},{"Value":45.0,"Name":"2020-03-26 00:00:00","Color":null},{"Value":40.0,"Name":"2020-03-27 00:00:00","Color":null},{"Value":34.0,"Name":"2020-03-28 00:00:00","Color":null},{"Value":51.0,"Name":"2020-03-29 00:00:00","Color":null},{"Value":40.0,"Name":"2020-03-30 00:00:00","Color":null},{"Value":44.0,"Name":"2020-03-31 00:00:00","Color":null},{"Value":60.0,"Name":"2020-04-01 00:00:00","Color":null},{"Value":55.0,"Name":"2020-04-02 00:00:00","Color":null},{"Value":54.0,"Name":"2020-04-03 00:00:00","Color":null},{"Value":49.0,"Name":"2020-04-04 00:00:00","Color":null},{"Value":56.0,"Name":"2020-04-05 00:00:00","Color":null},{"Value":59.0,"Name":"2020-04-06 00:00:00","Color":null},{"Value":58.0,"Name":"2020-04-07 00:00:00","Color":null},{"Value":62.0,"Name":"2020-04-08 00:00:00","Color":null},{"Value":52.0,"Name":"2020-04-09 00:00:00","Color":null},{"Value":45.0,"Name":"2020-04-10 00:00:00","Color":null},{"Value":61.0,"Name":"2020-04-11 00:00:00","Color":null},{"Value":45.0,"Name":"2020-04-12 00:00:00","Color":null},{"Value":59.0,"Name":"2020-04-13 00:00:00","Color":null},{"Value":56.0,"Name":"2020-04-14 00:00:00","Color":null},{"Value":45.0,"Name":"2020-04-15 00:00:00","Color":null},{"Value":51.0,"Name":"2020-04-16 00:00:00","Color":null},{"Value":54.0,"Name":"2020-04-17 00:00:00","Color":null},{"Value":43.0,"Name":"2020-04-18 00:00:00","Color":null},{"Value":42.0,"Name":"2020-04-19 00:00:00","Color":null},{"Value":37.0,"Name":"2020-04-20 00:00:00","Color":null},{"Value":52.0,"Name":"2020-04-21 00:00:00","Color":null},{"Value":64.0,"Name":"2020-04-22 00:00:00","Color":null},{"Value":44.0,"Name":"2020-04-23 00:00:00","Color":null},{"Value":66.0,"Name":"2020-04-24 00:00:00","Color":null},{"Value":37.0,"Name":"2020-04-25 00:00:00","Color":null},{"Value":33.0,"Name":"2020-04-26 00:00:00","Color":null},{"Value":38.0,"Name":"2020-04-27 00:00:00","Color":null},{"Value":40.0,"Name":"2020-04-28 00:00:00","Color":null},{"Value":35.0,"Name":"2020-04-29 00:00:00","Color":null},{"Value":53.0,"Name":"2020-04-30 00:00:00","Color":null},{"Value":30.0,"Name":"2020-05-01 00:00:00","Color":null},{"Value":43.0,"Name":"2020-05-02 00:00:00","Color":null},{"Value":36.0,"Name":"2020-05-03 00:00:00","Color":null},{"Value":33.0,"Name":"2020-05-04 00:00:00","Color":null},}
(...capped, but you get the idea)

You can just copy and paste to see the result. I am also saving cookies in case we need later.
$end_date= date('Y-m-d');//You dont have to use like this, you can write directly the date in the array below.
$start_date = date("Y-m-d", strtotime("-91 day"));
$data = array(
'highChartUrl'=> '/api/reports/GenerateHighChart',
'tableUrl'=> '/api/reports/GenerateExcel',
'chartWidth'=> '900',
'reportName'=> 'corona.vtfstart',
'startdat'=> $start_date,
'stopdat'=> $end_date,
'sasong[0]'=> '2020'
);
$url = 'https://portal.icuregswe.org/siri/api/reports/GenerateHighChart';
$ch = CURL_INIT();
CURL_SETOPT($ch, CURLOPT_URL, $url);
CURL_SETOPT($ch, CURLOPT_POST, true); //Post request
CURL_SETOPT($ch, CURLOPT_PROXYTYPE,CURLPROXY_SOCKS5);
CURL_SETOPT($ch, CURLOPT_POSTFIELDS, $data);
CURL_SETOPT($ch, CURLOPT_RETURNTRANSFER,True);
CURL_SETOPT($ch, CURLOPT_FOLLOWLOCATION,True);
CURL_SETOPT($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) ."/cookie.txt");
CURL_SETOPT($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) ."/cookie.txt");
CURL_SETOPT($ch, CURLOPT_FOLLOWLOCATION, true); //ALLOW REDIRECTION
CURL_SETOPT($ch, CURLOPT_CONNECTTIMEOUT,90);
CURL_SETOPT($ch, CURLOPT_TIMEOUT,90);
$result = CURL_EXEC($ch);
echo $result;

Related

Sending json with cURL doesn't echo the result back, why?

I'm trying to send this POST request and it won't echo any result,
I've tried to use different techniques but it's either giving me 500 error or just stuck on a blank page, whereas it should echo back at least something like this:
{"errorCode":"APP-0001","message":"Something really bad happened. Please contact your administrator, right now!","fields":{},"operationMessage":"Something really bad happened. Please contact your administrator, right now!"}
<?php
$countryCode = $_POST['countryCode'];
$phoneNumber = $_POST['phoneNumber'];
$data = array("countryCode" => "$countryCode", "phoneNumber" => "$phoneNumber");
$data_string = json_encode($data);
$ch = curl_init('https://consumer-edge-service.careem.com/api/v8/user/partialSignup?device=ACMA');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: SCBOHw6OOZD1lOJyS2dz',
'Agent: ACMA',
'User-Agent: ACMA/8.7.7',
'Device: ' . $phoneNumber,
'Provider-Access-Key: 6ba82ffa',
'Version: 8772',
'x-careem-position: 29.452370,32.752543,1799.999023,1552014765404',
'Content-Type: application/json; charset=UTF-8',
'Content-Length: 46',
'Host: consumer-edge-service.careem.com',
'Connection: close',
'Accept-Encoding: gzip, deflate',
'X-NewRelic-ID: VQMAWFVVABAHVVBXDwgFVA==')
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
?>

Instagram API retrieve the code using PHP

I try to use the Instagram API but it's really not easy.
According to the API documentation, a code must be retrieved in order to get an access token and then make requests to Instagram API.
But after few try, I don't succeed.
I already well-configured the settings in https://www.instagram.com/developer
I call the url api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code with curl, but I don't have the redirect uri with the code in response.
Can you help me please ;)!
I would recommend you use one of the existing PHP instagram client libraries like this https://github.com/cosenary/Instagram-PHP-API
I did this not too long ago, here's a good reference:
https://auth0.com/docs/connections/social/instagram
Let me know if it helps!
I've made this code, I hope it doesnt have error, but i've just made it for usecase like you wantedHere is the code, I'll explain it below how this code works.
$authorization_url = "https://api.instagram.com/oauth/authorize/?client_id=".$instagram_client_id."&redirect_uri=".$your_website_redirect_uri."&response_type=code";
$username='ig_username';
$password='ig_password';
$_defaultHeaders = array(
'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: ',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
'Cache-Control: max-age=0'
);
$ch = curl_init();
$cookie='/application/'.strtoupper(VERSI)."instagram_cookie/instagram.txt";
curl_setopt( $ch, CURLOPT_POST, 0 );
curl_setopt( $ch, CURLOPT_HTTPGET, 1 );
if($this->token!==null){
array_push($this->_defaultHeaders,"Authorization: ".$this->token);
}
curl_setopt( $ch, CURLOPT_HTTPHEADER, $this->_defaultHeaders);
curl_setopt( $ch, CURLOPT_HEADER, true);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_COOKIEFILE,getcwd().$cookie );
curl_setopt( $ch, CURLOPT_COOKIEJAR, getcwd().$cookie );
curl_setopt($this->curlHandle,CURLOPT_URL,$url);
curl_setopt($this->curlHandle,CURLOPT_FOLLOWLOCATION,true);
$result = curl_exec($this->curlHandle);
$redirect_uri = curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
$form = explode('login-form',$result)[1];
$form = explode("action=\"",$form)[1];
// vd('asd',$form);
$action = substr($form,0,strpos($form,"\""));
// vd('action',$action);
$csrfmiddlewaretoken = explode("csrfmiddlewaretoken\" value=\"",$form);
$csrfmiddlewaretoken = substr($csrfmiddlewaretoken[1],0,strpos($csrfmiddlewaretoken[1],"\""));
//finish getting parameter
$post_param['csrfmiddlewaretoken']=$csrfmiddlewaretoken;
$post_param['username']=$username;
$post_param['password']=$password;
//format instagram cookie from vaha's answer https://stackoverflow.com/questions/26003063/instagram-login-programatically
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookieFileContent = '';
foreach($matches[1] as $item)
{
$cookieFileContent .= "$item; ";
}
$cookieFileContent = rtrim($cookieFileContent, '; ');
$cookieFileContent = str_replace('sessionid=; ', '', $cookieFileContent);
$cookie=getcwd().'/application/'.strtoupper(VERSI)."instagram_cookie/instagram.txt";
$oldContent = file_get_contents($cookie);
$oldContArr = explode("\n", $oldContent);
if(count($oldContArr))
{
foreach($oldContArr as $k => $line)
{
if(strstr($line, '# '))
{
unset($oldContArr[$k]);
}
}
$newContent = implode("\n", $oldContArr);
$newContent = trim($newContent, "\n");
file_put_contents(
$cookie,
$newContent
);
}
// end format
$useragent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0";
$arrSetHeaders = array(
'origin: https://www.instagram.com',
'authority: www.instagram.com',
'upgrade-insecure-requests: 1',
'Host: www.instagram.com',
"User-Agent: $useragent",
'content-type: application/x-www-form-urlencoded',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: deflate, br',
"Referer: $redirect_uri",
"Cookie: $cookieFileContent",
'Connection: keep-alive',
'cache-control: max-age=0',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__)."/".$cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arrSetHeaders);
curl_setopt($ch, CURLOPT_URL, $this->base_url.$action);
curl_setopt($ch, CURLOPT_REFERER, $redirect_uri);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_param));
sleep(5);
$page = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $page, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie1);
$cookies = array_merge($cookies, $cookie1);
}
var_dump($page);
Step 1:
We need to get to the login page first.
We can access it using curl get, with CURLOPT_FOLLOWLOCATION set to true so that we will be redirected to the login page, we access our application instagram authorization url
$authorization_url = "https://api.instagram.com/oauth/authorize/?client_id=".$instagram_client_id."&redirect_uri=".$your_website_redirect_uri."&response_type=code";
$username='ig_username';
This is step one from this Instagram documentation here
Now the result of the first get curl we have the response page and its page uri that we store at $redirect_uri, this must be needed and placed on referer header when we do http post for login.
After get the result of login_page, we will need to format the cookie, I know this and use some code from vaha answer here vaha's answer
Step 2:
After we get the login_page we will extract the action url , extract csrfmiddlewaretoken hidden input value.
After we get it, we will do a post parameter to login.
We must set the redirect uri, and dont forget the cookiejar, and other header setting like above code.After success sending the parameter post for login, Instagram will call your redirect uri, for example https://www.yourwebsite.com/save_instagram_code at there you must use or save your instagram code to get the access token using curl again ( i only explain how to get the code :D)
I make this in a short time, I'll update the code which I have tested and work if i have time, Feel free to suggest an edit of workable code or a better explanation.

PHP scrapy cURL request not working

I am implementing a scrapy spider to crawl a website that contains real estate offers. The site contains a telephone number to the real estate agent, which can be retreived be an ajax post request.
To get a phone number I have to get ID from URL, next get from source csrfToken and send this with POST by special URL with ID. This method was working good but since yesterday not working.
My code:
$urlSite = "https://www.otodom.pl/mazowieckie/oferta/piekne-mieszkanie-na-mokotowie-do-wynajecia-ID3ezHA.html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_URL, $urlSite);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
preg_match("/csrfToken = '(.+?)'/", $result, $output_array);
preg_match("/ID(.+?).html/", $urlSite, $output_array_id);
$token = $output_array[1];
$id = $output_array_id[1];
$url = "https://www.otodom.pl/ajax/mazowieckie/misc/contact/phone/" . $id . "/";
$headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding: gzip, deflate, br',
'Accept-Language: pl,en-US;q=0.8,en;q=0.6,ru;q=0.4',
'Cache-Control: no-cache',
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length: 74',
'Host: www.otodom.pl',
'Referer: ' . $urlSite,
'User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'
];
$data = array(
'CSRFToken' => $token
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$phone = utf8_decode(curl_exec($ch));
curl_close($ch);
echo $phone;
Please help me, I am working for this a few hours and nothing.
{"status":"error","message":"Spróbuj wykonać operację ponownie. Jeśli
to nie pomoże, sprawdź czy masz włączoną obsługę JavaScript w
przeglądarce."}
As I mentioned on my comment, you need JavaScript in order to get the phone number. One way to achieve this is using selenium, here's a python example:
import time
from selenium import webdriver
geckodriver = 'C:/path_to/geckodriver.exe'
driver = webdriver.Firefox(executable_path = geckodriver)
driver.get("https://www.otodom.pl/mazowieckie/oferta/piekne-mieszkanie-na-mokotowie-do-wynajecia-ID3ezHA.html")
driver.find_element_by_class_name("phone-spoiler").click()
time.sleep(2)
print driver.find_element_by_class_name("phone-number").text
# 515 174 616
Notes:
1 - Install Selenium:
pip install selenium
2 - Download the geckodriver
3 - Replace C:/path_to with the path where you saved geckodriver.exe.
4 - Add C:/path_to to your environment.
5 - Restart your system.
6 - Run python name_of_script.py and the phone number will be displayed.
The steps above assume that you're using a windows machine.

cURL http request returns no response from server but fiddler or firebug network tool does

I can send HTTP request via fiddler or firebug network tool and receive server response but I cannot receive the same response via cURL and php; What is wrong?
I opened the URL (http://search.icbar.org) in my browser and searched with a filled "lawyer license number" field with "102", I caught the http request and then wrote the code below to imitate the action once more, but there was no response from server at all.
my code is here:
<?php
//echo phpinfo();
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
$pf=array('name' => '','family' => '','licenseNumber' => '102','Gender' => '','workState' => '','Province' => '','address' => '');
$headers = array(
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: gzip, deflate',
'Cache-Control: no-cache',
'Content-Type: application/json',
'X-Requested-With: XMLHttpRequest',
'Pragma: no-cache',
'Content-Length: 99',
'Connection: keep-alive',
'Host: search.icbar.org',
'Referer: http://search.icbar.org/',
'User-Agent: me');
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, 'http://search.icbar.org/Handler/Law.ashx?Method=mGetLawyers');
curl_setopt($curl, CURLOPT_USERAGENT, 'ali');
curl_setopt($curl, CURLOPT_POST, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pf);
// Send the request & save response to $resp
$resp=curl_exec($curl);
print_r(json_decode($resp));
if(!$resp)
{
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
// Close request to clear up some resources
curl_close($curl);
?>
As you are sending json request to the server, convert your array into json object.
$pf = json_encode($pf);

Pinterest login with PHP and cURL not working

I have been trying to make cURL login into pinterest.com for the last 17 hours straight, have tried countless and countless different ways just with cURL but it does not work at all.
My current code only goes to the page but the data is not posted, so it does not login just takes me to the login page.
This first code is using USERPWD which is where it takes me to the login page but it does not login.
error_reporting(E_ALL);
ini_set("display_errors", 1);
$url = "https://www.pinterest.com/login/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // allow https verification if true
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // check common name and verify with host name
curl_setopt($ch, CURLOPT_SSLVERSION,3); //
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "pin.pem"); // allow ssl cert direct comparison
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE); // set new cookie session
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_USERPWD, "email:password");
curl_setopt($ch, CURLOPT_SSLVERSION,3);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL connection, save cookie file, free up system resources
curl_close($ch);
and if I switch it from CURLOPT_USERPWD to
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username_or_email=$email&password=$password');
it just displays a blank page.
The pin.pem is the X.509 Certificate (PEM) file.
Any direction to make this work would be greatly appreciated it.
Edit
new code but leaves blank page and I got the output with a few arrays and displays this:
Array ( [url] => https://www.pinterest.com/login/ [content_type] => [http_code] => 0 [header_size] => 0 [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.036169 [namelookup_time] => 3.3E-5 [connect_time] => 0.036186 [pretransfer_time] => 0 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0 [redirect_time] => 0 [certinfo] => Array ( ) [redirect_url] => )
error_reporting(E_ALL);
ini_set("display_errors", 1);
$email = 'email';
$password = 'password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.pinterest.com/login/');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSLVERSION,3); //
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . 'pin.pem');
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username_or_email=$email&password=$password');
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_exec($ch);
$output=#curl_exec($ch);
$info = #curl_getinfo($ch);
echo $output;
print_r($info);
curl_close($ch);
The Pinterest login process isn't quite that simple. They use a CSRF token which you must extract and send with your login, along with the username and password in the POST body.
Here is what an actual login request to Pinterest looks like, so you will need to emulate this with cURL.
POST /resource/UserSessionResource/create/ HTTP/1.1
Host: www.pinterest.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-CSRFToken: 2rjgN4Qv67pN4wX91kTr4eIkgF54CzJH
X-NEW-APP: 1
X-APP-VERSION: 737af79
X-Requested-With: XMLHttpRequest
Referer: https://www.pinterest.com/login/
Content-Length: 300
Cookie: csrftoken=2rjgN4Qv67pN4wX91kTr4eIkgF54CzJH; _pinterest_sess="aPgJnrIBzvSKLUY/4H5UocshliA47GkkGtHLQwo1H4IcQv58vrdazclonByOb4fWCzb3a3nycKjQzDc6SkCB9eBKoejaLiCjkKLk/QAFRn2x1pvHFlFM+1EoD01/yFxmeQKlvULYU9+qf4D6Mkj8A=="; _track_cm=1;
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
source_url=%2Flogin%2F&data=%7B%22options%22%3A%7B%22username_or_email%22%3A%22YOU%40YOUROMAIN.COM%22%2C%22password%22%3A%22YOURPASSWORD%22%7D%2C%22context%22%3A%7B%7D%7D&module_path=App()%3ELoginPage()%3ELogin()%3EButton(class_name%3Dprimary%2C+text%3DLog+In%2C+type%3Dsubmit%2C+size%3Dlarge)
The source_url data in the request is the POST body (urlencoded). Take note that username_or_email is your login (I put YOU%40YOURDOMAIN.COM) and password is the password.
What you will have to do is make a GET request to /login/ to establish a session and cookies in the cURL session. Then using the same cURL handle, you can switch to a POST request, set CURLOPT_POSTFIELDS with the data from the source_url...... line.
You will probably also need to set the headers X-CSRFToken, X-NEW-APP, X-APP-VERSION, and X-Requested-With to match the above (except you will need to figure out how to get the correct CSRF Token value).
Unfortunately I don't have the time right now to make a working example, the next paragraph may help. You will need to use your browser to help you debug some of the HTTP requests to figure out all the requests you may need to make to get all the relevant data for your request.
If you check out this answer it shows curl login with PHP and links to a number of useful other related answers with examples.
EDIT:
Here is a working example of using PHP and cURL to log in to Pinterest.
This code is a Pinterest PHP login example (works as of 2014-05-11]. You may ask yourself, can what I want to do be done with the API instead of this hackish code which could break at any time???
As you can see I parse the CSRF_Token out of the headers, you should probably do this for the APP-VERSION as well since it can update almost daily. Right now it's hard coded.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$username = 'you#yoursite.com'; // your username
$password = 'yourpassword'; // your password
// this is the http post data for logging in - username & password are substituted in later
$login_post = array(
'source_url' => '/login/',
'data' => '{"options":{"username_or_email":"%s","password":"%s"},"context":{}}',
'module_path' => 'App()>LoginPage()>Login()>Button(class_name=primary, text=Log In, type=submit, size=large',
);
$pinterest_url = 'https://www.pinterest.com/'; // pinterest home url
$login_url = $pinterest_url . 'login/'; // pinterest login page url
$login_post_url = $pinterest_url . 'resource/UserSessionResource/create/'; // pinterest login post url
// http headers to send with requests
$httpheaders = array(
'Connection: keep-alive',
'Pragma: no-cache',
'Cache-Control: no-cache',
'Accept-Language: en-US,en;q=0.5',
);
// http headers to send when logging in
$login_header = array(
'X-NEW-APP: 1',
'X-APP-VERSION: d2bb370', // THIS WILL UPDATE FREQUENTLY, CHANGE IT!!!
'X-Requested-With: XMLHttpRequest',
'Accept: application/json, text/javascript, */*; q=0.01');
// ----------------------------------------------------------------------------
// request home page to establish cookies and a session, set curl options
$ch = curl_init($pinterest_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Iron/31.0.1700.0 Chrome/31.0.1700.0');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen('/tmp/debug.txt', 'w+'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheaders);
$data = curl_exec($ch);
// ----------------------------------------------------------------------------
// parse the csrf token out of the cookies to set later when logging in
list($headers, $body) = explode("\r\n\r\n", $data, 2);
preg_match('/csrftoken=(.*?)[\b;\s]/i', $headers, $csrf_token);
// next request the login page
curl_setopt($ch, CURLOPT_URL, $login_url);
$data = curl_exec($ch);
// ----------------------------------------------------------------------------
// perform login post
$login_header[] = 'X-CSRFToken: ' . $csrf_token[1];
$login_post['data'] = sprintf($login_post['data'], $username, $password);
$post = http_build_query($login_post);
curl_setopt($ch, CURLOPT_URL, $login_post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($httpheaders, $login_header));
curl_setopt($ch, CURLOPT_REFERER, $login_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
// check response and output status
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
echo "Error logging in.<br />";
var_dump(curl_getinfo($ch));
} else {
$response = json_decode($data, true);
if ($response === null) {
echo "Failed to decode JSON response.<br /><br />";
var_dump($response);
} else if ($response['resource_response']['error'] === null) {
echo "Login successful, " . $response['resource_response']['data']['username'] . "<br /><br />";
echo "You have {$response['resource_response']['data']['follower_count']} followers, are following {$response['resource_response']['data']['following_count']} users. You have liked {$response['resource_response']['data']['like_count']} pins.";
}
}
My output:
Login successful, drew010
You have 0 followers, are following 0 users. You have liked 0 pins.
FYI, Pinterest has login rate limit so don't run this before every request.
Here is my Ruby implementation of the Pinterest login/session mechanism.
Run this once a day to save the headers (including csrftoken). Then use the saved headers to do requests that are not (yet) supported by the api (like ads reports).
class PinterestHeadersScheduler
include Sidekiq::Worker
sidekiq_options queue: :recurring, retry: 0
HOMEPAGE = 'https://ads.pinterest.com/'
LOGIN_URL = "#{HOMEPAGE}login/"
SESSION_URL = "#{HOMEPAGE}resource/UserSessionResource/create/"
LOGIN_DATA = {
source_url: '/login/',
data: { options: { username_or_email: ENV['PI_USERNAME'], password: ENV['PI_PASSWORD'] }, context: {} }.to_json
}
HEADERS = {
'Accept': 'application/json,text/html,image/webp,image/apng,*/*;q=0.8',
'Origin': 'https://ads.pinterest.com',
'Referer': 'https://ads.pinterest.com/',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
'Accept-Charset': 'utf-8;ISO-8859-1q=0.7,*;q=0.7',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8'
}
SESSION_HEADERS = HEADERS.merge({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
})
def perform
login = HTTParty.get(LOGIN_URL, { headers: HEADERS })
cjar = login.get_fields('Set-Cookie').each_with_object(HTTParty::CookieHash.new) { |cookie, jar| jar.add_cookies(cookie) }
headers = SESSION_HEADERS.merge({ 'Cookie': cjar.to_cookie_string, 'X-CSRFToken': cjar[:csrftoken] })
res = HTTParty.post(SESSION_URL, { headers: headers, body: LOGIN_DATA.to_param })
session = JSON.parse(ActiveSupport::Gzip.decompress(res.body))
raise "login error #{session['resource_response']['error']}" if session['resource_response']['error']
cjar = res.headers.get_fields('Set-Cookie').each_with_object(HTTParty::CookieHash.new) { |cookie, jar| jar.add_cookies(cookie) }
save_session_headers(HEADERS.merge({ 'Cookie' => cjar.to_cookie_string }))
end
def save_session_headers(headers)
# replace this with your cache/db
Utils::RedisUtil.set(:pinterest_session_headers, headers.to_json)
end
end

Categories