PHP Curl - Get data generated with AJAX - php

I want to get data generated by an AJAX request. In this page http://www.fipe.org.br/web/index.asp?p=51&aspx=/web/indices/veiculos/default.aspx there are some html selects. When the user click on the first one (Marca), the second one is filled. I want to get this data.
This is my code:
<?php
$curl = curl_init();
$postData = array('ddlAnoValor' => 0,
'ddlMarca' => 1,
'ddlModelo' => 0,
'ddlTabelaReferencia' => 123,
'txtCodFipe' => '');
$result = null;
$httpResponse = null;
curl_setopt($curl, CURLOPT_URL, 'http://www.fipe.org.br/web/indices/veiculos/default.aspx?p=51');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.fipe.org.br/web/indices/veiculos/introducao.aspx');
curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($curl);
$httpResponse = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($httpResponse == '404') {
throw new exception('This page doesn\'t exists.');
}
echo $result;
curl_close($curl);
?>
Page request header
Host: www.fipe.org.br
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.13) Gecko/20100916 Iceweasel/3.5.13 (like Firefox/3.5.13)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
X-MicrosoftAjax: Delta=true
Cache-Control: no-cache, no-cache
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Referer: http://www.fipe.org.br/web/indices/veiculos/default.aspx?p=51
Content-Length: 9415
Cookie: __utma=106123796.1351303072.1287075522.1287075522.1287075522.1; __utmb=106123796; __utmc=106123796; __utmz=106123796.1287075522.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); ASPSESSIONIDAADQDQRD=EKBEJHEDKCIOAAHNFFMLGMKO
Pragma: no-cache
But I always get the form as result. I've tried to set cookie but cookies.txt file is always empty. I don't know if this cookie is required. cookies.txt has 777 permission. What am I doing wrong? Thank you.

If you look at the post variables (use the net panel on firebug to do this) when using the form on the site, you will see that it contains some variables which you are not submitting with your PHP code, such as _VIEWSTATE and _EVENTVALIDATION.
I guess that these relate to the session established by the browser when displaying the form, and I further guess that if these and their related variables are not present then the server will return the full page HTML including the form.
You could try to simulate these variables, but I suspect you are doomed to fail.
Ideally you should contact the site and ask them how you can retrieve the information you are looking for. Perhaps they have a webservice which exposes it?

Related

Access Denied with CURL and PHP

I'm trying to access this website natura.com.br to get info about some products, I'm trying to make a request the same way I do in the browser but I receive Access denied.
<?php
$url = "https://www.natura.com.br/";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:89.0) Gecko/20100101 Firefox/89.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Connection: keep-alive",
"Cookie: dtPC=11$302937546_809h-vKVNUNMUJAHDKTQPPAHFQIMSCQPPRKILC-0e0; rxvt=1625712010903|1625710210903; _abck=141C18ABCC9C79DFA1F4D45EF108501A~-1~YAAQk9j2SGYWZX56AQAAtC1zgwbF2BpCRBBWxNKDpMPWjPEYtw7XLvfB2g+dxkZSpfXBRCTvbE4fZTzGxjqtGVa7tZqz9pWp/hYSf65phFg2VW06IioCwpy7tox8su7QlWIt3eZUeTFIJ5S7nRtSv3Te859lzghM7a2lLnZOjpjS5eYLrJzYzyKFsRdc8Kpgj+sGCZA9iKiMvfqtJlI5e+90UfUDDzTQB2sV2U5i2yavjB+GsgBZ1qcKIfmo41PYfXtS8efG+3C4F4cw3sePIjj4vQIex1pQdg3twIbyqAMsEClNaqbGJ29NVu/orK7dAJ7rteSqWvyMuMu9MCltlPoYaYYi/O0Uzv18AiK9hSMYYWod7U/IqUkfE/touhQz6OT0S2KPjG0wJVJ8dghA8LdDJFH4+Y3YX4+oDw==~0~-1~-1; dtCookie=v_4_srv_11_sn_44IDRCETVPHGS7OCQ5F7DV8IS6T6HDI3_perc_100000_ol_0_mul_1_app-3A2a1999229615da92_1_app-3A58ea22250e34b990_1_rcs-3Acss_0; rxVisitor=1625332161003TGNBC4CH08VFEACK6NT19CQ14GERSQEA; dtSa=-; dtLatC=6; RT="z=1&dm=www.natura.com.br&si=a6979d10-a558-4bb3-a962-ccb19999271b&ss=kqu5jycl&sl=0&tt=0"; JSESSIONID=IUGNrH_B8h7DHZlVAsWr38FYiZq_I13dabE1sdnURzTRvdlsps50!-405357702; verifyFirstRequest=true; ORDER_ID=%3B%20; ORDER_NUMBER=%3B%20; X-Oracle-BMC-LBS-Route=93a9c3aed1d29d32ea0391633407edd696daed8327da03a11a2ff120e313e9b656c62fd8a7c42ae86da5fb4c73ec2333f092dbf8c9611add8055dec1; undefined; GTMUtmTimestamp=1625702943894; GTMCampaignReferrer=https%3A%2F%2Fwww.google.com%2F; GTMCampaignLP=https%3A%2F%2Fwww.natura.com.br%2Fp%2Fdesodorante-Col%25C3%25B4nia-kaiak-urbe-masculino-100ml%2F34075%3Futm_content%3DSP_Resp_MCKaiak_2020_Kaiak_Urbe%26cnddefault%3Dtrue%26gclid%3DEAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; _gcl_au=1.1.467484977.1625332166; _ga_15QCH7XEDY=GS1.1.1625874531.3.0.1625874531.60; _ga=GA1.3.1744316957.1625332166; GTMBrowserSessionEntranceTimestamp=1625332166546; GTMBrowserSessionEntranceLP=https%3A%2F%2Fwww.natura.com.br%2Facesso-consultor; GTMBrowserSessionEntranceReferrer=https%3A%2F%2Fwww.google.com%2F; GTMLastEntranceTimestamp=1625702945066; GTMLastEntranceLP=https%3A%2F%2Fwww.natura.com.br%2Fp%2Fdesodorante-Col%25C3%25B4nia-kaiak-urbe-masculino-100ml%2F34075%3Futm_content%3DSP_Resp_MCKaiak_2020_Kaiak_Urbe%26cnddefault%3Dtrue%26gclid%3DEAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; GTMLastEntranceReferrer=https%3A%2F%2Fwww.google.com%2F; _fbp=fb.2.1625332167173.86579534; GTMUtmSource=google; GTMUtmMedium=cpc; GTMUtmCampaign=auto; GTMGclid=EAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; _gcl_aw=GCL.1625702944.EAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; _ttgclid=EAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; _ttgclid=EAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; __bid=4dbbd24a-fc0e-42aa-a664-43c865cae2ef; _gac_UA-35236522-3=1.1625703004.EAIaIQobChMIxrmerJfS8QIV7R-tBh01uwM5EAAYASAAEgIZU_D_BwE; cto_bundle=qVL1jF8yb3h2cW01cmFaUjF5S2VnMkdGcDEyNHdrWWM3ZXpZcFFIMkowdmZqOFZpNTE3VGIlMkJibkZZZXpMJTJGYXBqRElFT0FwdFRia3ZwQ1JZSzZ2ZEx1RSUyQnBXUW54MmM1S3UlMkY3WjlqenBXU1dDZFlRaTYlMkZucVdPM2c5MTJUcERYc2pLcEdyeURWQU9ieDhmaTR1WGJoN1FhaHR4Nm5MZWdJUUNmZUI0MkdNYk50VXpFRGg0Z2hUSlNxS25xZGFNVjJZTGpC; GTMVisitSession=1625702947208; GTMVisitPermanent=1625702947208; _uetvid=b67fe410df8011eb85947b37dce069f8; smeventsclear_d13b2682b72e42cc9203ee1f0a20b68d=true; personNumber=141692103; smCloseBounce=true",
"Upgrade-Insecure-Requests: 1",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>
I get this HEADER when I do the request
"HTTP/1.1 403 Forbidden Server: AkamaiGHost Mime-Version: 1.0 Content-Type: text/html Content-Length: 271 Cache-Control: max-age=1800 Expires: Sat, 10 Jul 2021 21:35:46 GMT Date: Sat, 10 Jul 2021 21:05:46 GMT Connection: close Server-Timing: cdn-cache; desc=HIT Server-Timing: edge; dur=1 Timing-Allow-Origin: true Access-Control-Max-Age: 86400 Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: * Access-Control-Allow-Methods: GET,POST,OPTIONS Access-Control-Allow-Origin: *
First of all, within "" PHP tries to convert variables to strings. So
$foo = "Hello, ";
echo "$foo World" . PHP_EOL;
would output
Hello, World
You are using "" and have the $-sign in your cookie (not to mention the fact that the cookie-string itself contains the "-sign). So PHP is not sending that "as-is" in the cookie but instead trying to find that variable and turn it into a string. If you don't want this behavior use single quotes ' instead.
So that could be your issue as long as the information in the cookie is valid and should allow you access.
Besides this it is hard to know what happens in the backend of natura.com.br to block your access. It could be any number of things. Do you need to login, do you have a valid session etc.
Instead of working with curl directly you could use Guzzle which is a great PHP based HTTP-Client that simplifies a lot of stuff. It can keep track of cookies and append them automatically etc.

fileshark.pl login using curl php

i have big problem with login to site fileshark.pl
I use something like this
function grab_page($site){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL, $site);
ob_start();
return curl_exec ($ch);
ob_end_clean();
curl_close ($ch);
}
function post_data($site,$data){
$datapost = curl_init();
$headers[] = "Content-type: application/json";
$headers[] = "X-Requested-With: XMLHttpRequest";
curl_setopt($datapost, CURLOPT_URL, $site);
curl_setopt($datapost, CURLOPT_TIMEOUT, 40000);
curl_setopt($datapost, CURLOPT_HEADER, TRUE);
curl_setopt($datapost, CURLOPT_HTTPHEADER, $headers);
curl_setopt($datapost, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($datapost, CURLOPT_POST, TRUE);
curl_setopt($datapost, CURLOPT_POSTFIELDS, $data);
curl_setopt($datapost, CURLOPT_COOKIEFILE, "cookie.txt");
ob_start();
return curl_exec ($datapost);
ob_end_clean();
curl_close ($datapost);
unset($datapost);
}
$token = "";
$data = grab_page("https://fileshark.pl/zaloguj");
$token = cut_str($data,'_csrf_token" value="','" />'); -> take token, i need this to login post data
post_data("https://fileshark.pl/login_check","_username=MYUSER&_password=MYPASSWORD&_csrf_token={$token}");
$data = grab_page("https://fileshark.pl/");
echo $data;
but when i go to normal website i am not logged ... every time not logged :/ this is post data from website...
https://fileshark.pl/login_check
POST /login_check HTTP/1.1
Host: fileshark.pl
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0
Accept: */*
Accept-Language: pl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://fileshark.pl/
Content-Length: 97
Cookie: hl=pl; _ga=GA1.2.816314079.1500843124; __gfp_64b=Ocm7N2W0C.LWu6Ga3q6MIsWU1devhoy.6XNO0Bth6q3.O7; _gid=GA1.2.234598376.1502038746; PHPSESSID=j1ch3848vrg4itpd8fgl4ul1j4; _gat=1
Connection: keep-alive
_username=MYUSER&_password=MYPASSWORD&_csrf_token=xBcS0AVCVvLnN5e2puEfxd8v_Ol6a-KG0uscwqlLU98
HTTP/1.1 200 OK
Server: nginx/1.10.3
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache
Date: Sun, 06 Aug 2017 19:41:55 GMT
Set-Cookie: PHPSESSID=nsvibi4o3u5kqdc6u5rbjbi444; path=/; HttpOnly
Set-Cookie: REMEMBERME=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; HttpOnly
Anyone can help me with this? When i try to other site like catshare all working but not for this site :)
first off, you ignore any and all setopt errors, fix that (use something like
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ){
if(curl_setopt($ch,$option,$value)!==true){
//option should be obvious by stack trace
throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . curl_errno ($ch).'. curl_error: '.curl_error($ch) );
}
}
)
.
second, obviously the csrf token is tied to a cookie session, which you completely ignore (you make no attempt to store nor resend any cookies), and without a cookie session in the login request, your csrf token will always be invalid, fix that (check CURLOPT_COOKIEFILE to get curl to handle cookies automatically). third, you extracts the csrf token from the html with a regex, that regex will NOT decode html entities for you (like & for &, < for <, > for >, etc), so if/when the csrf token contains any such encoded characters, you will send the wrong token, fix that (see html_entity_decode, or better yet, use a proper html parser to extract it). fourth, you don't urlencode the username, nor the password, nor the token, so if any of those contains any characters with special meaning in urlencoded, you will send the wrong credentials, and won't get logged in, fix that (this includes &, =, spaces, all non-ascii characters, and even some ascii characters). fifth, you never stop the output buffer started in the grab_page function, you put the code to stop it after the return statement, thus that code will never be executed, fix that. if, after fixing all those mentioned issues, you still can't get log in, let me know, and i'll dig deeper

PHP cURL doesn't set content-length properly

I'm trying to upload a file via cURL but something is missing. I forces this request to be HTTP 1.0 because cURL adds the Expect: 100 header if I use HTTP 1.1 so thats why the extra header. Here is a simple test code:
<?php
if(isset($_POST["id"])) {
$data = array("id" => $_POST["id"]);
$data["file"] = "#".realpath($_FILES["file"]["tmp_name"]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer 0e39ffba-66cd-4933-9e94-fcdf600c2453',
'Connection: keep-alive'
));
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/test-api/upload");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_HTTP_VERSION, 1);
$response = curl_exec($ch);
var_dump($response);
exit;
}
?>
My Jersey based server picks it up, and I can see these headers:
INFO: 25 * Server has received a request on thread http-nio-8080-exec-1
25 > POST http://localhost:8080/test-api/upload
25 > authorization: Bearer 0e39ffba-66cd-4933-9e94-fcdf600c2453
25 > connection: keep-alive
25 > content-length: 261
25 > content-type: multipart/form-data; boundary=------------------------53f7ba34739b4d9e
25 > host: localhost:8080
See the content-length? It's way too short. When I send the same file and the same request via my Postman REST client, I get these headers:
INFO: 26 * Server has received a request on thread http-nio-8080-exec-3
26 > POST http://localhost:8080/test-api/upload
26 > accept-encoding: gzip, deflate
26 > accept-language: hu-HU,hu;q=0.8,en-US;q=0.6,en;q=0.4
26 > authorization: Bearer 0e39ffba-66cd-4933-9e94-fcdf600c2453
26 > cache-control: no-cache, no-cache
26 > connection: keep-alive
26 > content-length: 144954
26 > content-type: multipart/form-data; boundary=----WebKitFormBoundarye5Tg0kEqi10nEBwv
26 > cookie: ff_uvid=126143952; _ga=GA1.1.459454356.1439469592; CAKEPHP=9mffidqo8203ugktan4roc0u82
26 > host: localhost:8080
26 > origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
26 > user-agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
The content-length now is set property. What could be wrong here?
It sounds like you're using PHP 5.6.0 or later. As of this release, the # prefix for file uploads is disabled by default. You can enable it with
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
This option was added in 5.5, but the default was false for backward compatibility; 5.6 changed the default incompatibly.
The preferred way to perform file uploads starting with 5.5 is with the CurlFile class.
$data["file"] = new CurlFile(realpath($_FILES["file"]["tmp_name"]));
You have to actually insert the filecontent, this differs from the cli-version of curl.
try:
$data["file"] = file_get_contents($_FILES["file"]["tmp_name"]);

How to perform a PUT operation using CURL in PHP?

I would like to perform a PUT operation on a webservice using CURL. Let's assume that:
webservice url: http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3
municipality= NMBM
sgc= 12345
I've written the code below, but it outputs this error message: "ExceptionMessage":"Object reference not set to an instance of an object.". Any help would be so much appreciated. Thanks!
<?php
function sendJSONRequest($url, $data)
{
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'X-MP-Version: 10072013')
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();
$result = curl_exec($ch);
$info = curl_getinfo($ch);
if ($result === false || $info['http_code'] == 400) {
return $result;
} else {
return $result;
}
ob_end_clean();
curl_close($ch);
}
$mun = $_GET['municipality'];
$sgc = $_GET['sgc'];
$req = $_GET['req']; //cac52674-1711-e311-b4a8-00155d4905d3
//myPrepaid PUT URL
echo $mpurl = "http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/$req";
// Set Variables
$data = array("Municipality" => "$mun", "SGC" => "$sgc");
//Get Response
echo $response = sendJSONRequest($mpurl, $data);
?>
I copied your code, but changed it so it pointed at a very basic HTTP server on my localhost. Your code is working correctly, and making the following request:
PUT /api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3 HTTP/1.1
Host: localhost:9420
Content-Type: application/json
Accept: application/json
X-MP-Version: 10072013
Content-Length: 37
{"Municipality":"NMBM","SGC":"12345"}
The error message you're receiving is coming from the stageapi.myprepaid.co.za server. This is the full response when I point it back to them:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 30 Aug 2013 04:30:41 GMT
Connection: close
Content-Length: 867
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MyPrepaidApi.Controllers.ConsumerRegisterRequestController.Put(CrmRegisterRequest value) in c:\\Workspace\\MyPrepaid\\Prepaid Vending System\\PrepaidCloud\\WebApi\\Controllers\\ConsumerRegisterRequestController.cs:line 190\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
You may want to check out the API to make sure you're passing them the correct information. If you are, the problem could be on their end.
And while I realize this isn't part of your question and this is in development, please remember to sanitize any data from $_GET. :)
Try with:
curl_setopt($ch, CURLOPT_PUT, true);

[Dead]How to successfully POST to an old ASP.NET site utilizing Asynchronous Postback

[Update] Unfortunately I never had an opportunity to solve this problem. However, there are some interesting responses below that are worth a try for other readers looking to do something similar.
I'm trying to parse data from a site running ASP.NET. This site has a login page that I've successfully traversed (using a legitimate account) and stored the cookie for, but when I get deeper into the site I need to navigate it by updating UpdatePanels via Asynchronous Postbacks. The UpdatePanels contain the data that I want.
I'm trying to do this all using PHP and curl. I can successfully load the initial page. When I POST to my target page with all the relevant data (obtained via Firefox's Tamper Data plugin), the echoed result returned from curl always clears my page. Typically, echoing the result would just print out (or spew some error/garbled text) further down the page. curl_error() doesn't print out anything, so it's something wrong with what's being returned to me.
I'm at wits end about how to go about this from here. Please tell me if: a) you know what error I'm getting, b) if this is even going to be possible with exclusively PHP, and c) if, conversely, I need to brush off javascript to interact with ASP.NET's UpdatePanels.
$uri = "TARGETURL";
$cl=curl_init();
curl_setopt($cl, CURLOPT_URL, $uri);
curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0');
curl_setopt($cl, CURLOPT_COOKIEFILE, "/tmp/cookie2.txt");
curl_setopt($cl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($cl, CURLOPT_POST, 1);
$postdata=array(
"__VIEWSTATE" => $viewstate,
"OTHER DATA" => "asdfkljsddflkjshdjf",
"__ASYNCPOST" => "true",
);
echo "<PRE>";
print_r($postdata);
echo "</PRE>";
curl_setopt ($cl, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($cl); // execute the curl command
echo $result;
Here is the Header and Body I am receiving back from the server (e-mailed to myself to bypass the page-clearing happening with the echo statement):
HEADER RESPONSE:
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-Content-Type-Options: nosniff
Set-Cookie: culture=en-US; expires=Tue, 27-Nov-2012 20:02:37 GMT; path=/
X-Powered-By: ASP.NET Date: Mon, 28 Nov 2011 20:02:37 GMT
Content-Length: 112
BODY RESPONSE:
69|dataItem||<script type="text/javascript">window.location="about:blank"</script>|11|pageRedirect||/Error.aspx|
This explains the problem I'm getting with the page going blank (javascript redirecting my browser output). It also seems to indicate that the header isn't the issue as I'd be getting an HTTP error from bad header values.
A. You state in your request that you are Firefox browser:
curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0');
Do not claim you're Firefox:
if you cannot process scripts (as Firefox can and does)
if you want to prevent ASP.NET from sending you a partial rendering response
Make your own user agent name, or don't send it at all.
ASP.NET checks if user agent supports callbacks:
HttpCapabilitiesBase.SupportsCallback Property
B. Don't send __ASYNCPOST = true (give it a try).
Here you are an addapted approach that works for me:
public function doPostbackToAspDotNetPage()
{
$uri = '*** THE_URL ***';
$cl = curl_init();
curl_setopt($cl, CURLOPT_URL, $uri);
curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:54.0) Gecko/20100101 Firefox/54.0');
curl_setopt($cl, CURLOPT_COOKIESESSION, '*** OPTIONAL ***');
curl_setopt($cl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($cl, CURLOPT_POST, 1);
// Just in case the url is https and the certification gives some kind of error
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
$postdata = array(
'__EVENTTARGET' => '*** A value such as: SOME_ID$ctl20$ctl02 ***',
'__EVENTARGUMENT' => ' *** OPTIONAL ***',
"__VIEWSTATE" => '*** REQUIRED BUNCH OF CHARACTERS ***',
"__ASYNCPOST" => "true",
'__VIEWSTATEGENERATOR' => '*** OPTIONAL ***',
'__EVENTVALIDATION' => "*** REQUIRED BUNCH OF CHARACTERS ***",
);
curl_setopt($cl, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($cl);
if (!$result) {
echo sprintf('ERROR:%s', PHP_EOL);
echo curl_error($cl);
} else {
echo $result;
}
curl_close($cl);
}
A different approach can be use a very useful PHP tool (a class emulating browser behavior) that do all the job to keep trace of all fields, do the post/get by clicking on links or buttons.
Here the link:
simpletest
I have no clue about php and curl, but if I understand Correctly, you are trying to send info to an ASP page. Maybe the problem is that the page has the CausesValidation option activated. so, the server is not allowing external POSTs to the page.

Categories