Get alert response from external site - php
I'm trying ot figure out away to get a response from this website:
https://www.primarycare.nhs.uk/publicfn/catchment.aspx?oc=P91012&h=600&w=800&if=0
oc=P91012 - this is the practice identifier.
We then have a postcode field where a user checks if they are in the catchment area
The site issues a javascript alert to inform the user if they are / or not in the catchment area.
Is it possible to send a PHP Curl request that sends a postcode to this website and checks whether or not the postcode is in the catchment area and send a reponse back to my site?
<?php
$POSTurl = 'https://www.primarycare.nhs.uk/publicfn/geocode.ashx';
$fields = array(
'postcode' => urlencode('M41 0UX'),
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $POSTurl );
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
$url = 'https://www.primarycare.nhs.uk/publicfn/catchment.aspx?oc=P91012&h=600&w=800&if=0';
$ch = curl_init();
$result = curl_exec($ch);
curl_close($ch);
?>
So, here it is:
the problem, why you were not unable to pick proper response is because all valid coordinates was in source code of NHS. I stripped out unwanted code, and checked coordinates by postcode with existing coordinates from the list. Keep in mind, that if anything will be changed in the list in original source, you will need to update that also.
Also, this code, technically is not 100% correct and probably you will spent more time to make it more correct for your needs. As i said in the comment, this will work as little hack.
Just copy/paste into your php file, and refresh the page.
Code:
<?php
$postcode = 'M41 0UX';
$postcode = urlencode($postcode);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.primarycare.nhs.uk/publicfn/geocode.ashx");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "PostCode=".$postcode);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
else {
echo $result;
echo '<input id="checker" type="hidden" value="'.$result.'" />';
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="https://www.primarycare.nhs.uk/Private/js/gpos.js" type="text/javascript"></script>
<script type="text/javascript" src="https://maps-api-ssl.google.com/maps/api/js?v=3.7&sensor=false"></script>
<script type="text/javascript">
var point;
var poly1=[{x:53.45801,y: -2.33768},{x:53.46046,y: -2.32996},{x:53.45882,y: -2.32447},{x:53.45637,y: -2.3188},{x:53.45351,y: -2.31709},{x:53.44932,y: -2.31468},{x:53.44523,y: -2.31365},{x:53.44216,y: -2.31279},{x:53.43961,y: -2.31417},{x:53.43858,y: -2.31657},{x:53.4394,y: -2.32155},{x:53.44001,y: -2.32893},{x:53.44145,y: -2.33408},{x:53.44329,y: -2.33751},{x:53.44053,y: -2.33648},{x:53.4395,y: -2.34095},{x:53.43838,y: -2.34352},{x:53.44083,y: -2.34627},{x:53.44022,y: -2.35107},{x:53.43899,y: -2.35193},{x:53.43787,y: -2.35107},{x:53.43797,y: -2.35399},{x:53.43715,y: -2.35622},{x:53.43562,y: -2.3576},{x:53.43592,y: -2.35949},{x:53.43449,y: -2.36103},{x:53.43275,y: -2.36017},{x:53.43153,y: -2.36137},{x:53.43275,y: -2.36343},{x:53.43183,y: -2.36515},{x:53.43347,y: -2.36738},{x:53.4349,y: -2.36704},{x:53.43664,y: -2.36738},{x:53.43736,y: -2.3679},{x:53.43705,y: -2.37167},{x:53.43725,y: -2.37459},{x:53.43592,y: -2.37511},{x:53.43664,y: -2.377},{x:53.43623,y: -2.37974},{x:53.43787,y: -2.38077},{x:53.43858,y: -2.37888},{x:53.4395,y: -2.3782},{x:53.43981,y: -2.38197},{x:53.4392,y: -2.38403},{x:53.43797,y: -2.38352},{x:53.43848,y: -2.38609},{x:53.4395,y: -2.38592},{x:53.44073,y: -2.3842},{x:53.44063,y: -2.38747},{x:53.44001,y: -2.3909},{x:53.43776,y: -2.39193},{x:53.43603,y: -2.39141},{x:53.4348,y: -2.38884},{x:53.43255,y: -2.39038},{x:53.43388,y: -2.39553},{x:53.43459,y: -2.39914},{x:53.43684,y: -2.40051},{x:53.43766,y: -2.40223},{x:53.4394,y: -2.4012},{x:53.44012,y: -2.40429},{x:53.4394,y: -2.40824},{x:53.43868,y: -2.41219},{x:53.44533,y: -2.40807},{x:53.4485,y: -2.40669},{x:53.4529,y: -2.40309},{x:53.45545,y: -2.39965},{x:53.45995,y: -2.39313},{x:53.46363,y: -2.38438},{x:53.46608,y: -2.37614},{x:53.46894,y: -2.3703},{x:53.46588,y: -2.36532},{x:53.46455,y: -2.35931},{x:53.46281,y: -2.35296},{x:53.46158,y: -2.3461},{x:53.45995,y: -2.34198},{x:53.4577,y: -2.33974}];
function isPointInPoly(poly, pt){
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
&& (c = !c);
return c;
};
function ispostcodein(postcode) {
var ok = 1;
if (ok == 1) {
var responseText = $('#checker').val();
point = responseText.split(';');
}
var incatch = 0;
if (isPointInPoly(poly1, {x: point[0],y: point[1]})) { incatch = 1 };
if (incatch==0) {
alert("We're sorry, but your postcode is outside the catchment area for PRIMROSE AVENUE SURGERY.");
}
else {
alert("Your postcode is in the catchment area for PRIMROSE AVENUE SURGERY. You are able to register with this practice.");
}
}
ispostcodein('<?= $result; ?>');
</script>
<?php
}
curl_close($ch);
?>
Related
Waiting to rescue redirect url in PHP / cURL
I need to retrieve the redirect URL from a link, but when I pull the header information it just returns: Locations: redirecting... Afterwards, the page is redirected to the URL I want to redeem. I'm using the code: $url = 'http://168.0.51.253:8000/boleto/74140-P2UTT5T4IH/'; // Final URL I want to retrieve = https://data.galaxpay.com.br/prooverisp/boleto/202109YB0K77L7WYP5PPY0NGT6DMKOD01155936 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $a = curl_exec($ch); curl_close($ch); $headers = explode("\n", $a); $j = count($headers); $ticket = null; for ($i = 0; $i < $j; $i++) { if (strpos($headers[$i], "Location:") !== false) { $ticket = trim(str_replace("Location:", "", $headers[$i])); break; } } var_dump($headers); How can I wait for the redirect and retrieve the final URL? I work with PHP.
You are trying to grab a redirection (aka Location) header from the first link, but when you open it with JavaScript disabled in your browser you will see that there is none. In fact, you always get a response code 200 and no Location header. There actually is a javascript that instantly redirects you to the target URL: <!doctype html> <style type="text/css" media="all"> html, body { height: 100%; margin: 0; /* Reset default margin on the body element */ } iframe { display: block; /* iframes are inline by default */ border: none; /* Reset default border */ width: 100%; height: 100%; } </style> Redirecionando... <script type="text/javascript"> document.location.href = "XYZ" </script> XYZ= Target link you want to grab, I just removed it here for privacy reasons. You can grab it like so: $url = 'http://1.2.3.4:8000/foo/bar/'; // URL removed for privacy $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $a = curl_exec($ch); curl_close($ch); $lines = explode("\n", $a); $j = count($lines); $ticket = null; for ($i = 0; $i < $j; $i++) { if (preg_match('/document.location.href = \"(.*)\"/', $lines[$i], $matches)) { $ticket = trim($matches[1]); break; } } var_dump($ticket); Also, your array looping is kind of complicated for no reason, so you can simplify it by using a foreach: $ticket = null; foreach (explode("\n", $a) as $line) { if (preg_match('/document.location.href = \"(.*)\"/', $line, $matches)) { $ticket = trim($matches[1]); break; } }
Attempting to stimulate page to produce server sent event with POST data from another page not working
When I open update.php on its own (with self supplied test vars), it sends the SSE to testsse.php just fine and there are no issues (Everything I need to be printed is showing up in inspect element), However, I am trying to have POST data from another page (In this case mootssetest.php) get received by update.php so it may send out the SSE containing the data. I am not sure what I am doing wrong, but this test rig is not working. Guidance would be appreciated. testsse.php (front end page meant to receive SSE and print) <!DOCTYPE html> <html lang="en"> <head> <title>Using Server-Sent Events</title> <script> window.onload = function() { var link = new EventSource("update.php"); var antispam; var inputthing = event.data; var splitted; link.onmessage = function(event) { inputthing = event.data; splitted = inputthing.split(" "); if (splitted[0] != antispam && splitted[1] == <?php echo $page; ?>) { document.getElementById("livemsg").innerHTML += "<div id=\"post-" + splitted[0] + "\" class=\"reply\">" + "</div>"; antispam = splitted[0]; }; }; }; </script> </head> <body> <div id="livemsg"> <!--Server response will be inserted here--> </div> </body> </html> update.php (SSE sender, post receiver) <?php $data = json_decode(file_get_contents('php://input'), true); $postnum = $data[0]; $bread = $data[1]; postnum = 32; bread = 4; function liveupdate($postnum, $bread) { header("Content-Type: text/event-stream"); header("Cache-Control: no-cache"); echo "data: " . $postnum . " " . $bread . "\n\n"; flush(); } liveupdate($postnum, $bread); ?> mootssetest.php (POST sender) function httppost($postnum, $bread) { $url = "http://localhost/update.php"; $data = array($postnum, $bread); $curl = curl_init($url); $jsondata = json_encode($data); curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsondata ); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $result = curl_exec($ch); curl_close($ch); return $result; } httppost(420, 4); ?> (For context, I am trying to have this print a new post in some forum software every time a function is called without refreshing the page for the user)
you haven't included the event in your window.onload() function, please fix it first and try again.
Slow response rate from Curl / Ajax
General Info Hi guys, I was deciding to post this or not due to the question but i said hell, why not! What am i doing? I have an array of music tracks which is pushed into a ajax request which i then loop through in php and pass each track into a curl request to then go off and pull down coverart for them specific tracks! The coverart of course is in .jpg or .png format of a link, so rihanna.jpg is returned. I then push them into another array which is my end result which is then pushed back to my ajax result (data) and i go from there. My issue? When i push in 60 tracks, the response is around 30 seconds which is a long ass wait! I am trying to retrieve information as quick as possible so i can update the end-users GUI without leaving them with a loading bar for periods of time while the data loads. Now i looked into this and my theory behind why its so slow is either down to the api call is lacking in the response department or the curl is hogging and slowing it all down! I heard of curl_multi and all those but have never used nor do i no were to start! I am not even sure if that will solve this. Can someone please input on this to try ease my mind? Is this speed all i will ever get or is it possible to speed this up? Before i was creating ajax calls within a loop and i thought it was because of that so i did a change to push all the tracks into one array which is then passed into one ajax but it did not speed anything up.. Same response rate to be honest! My PHP code: function curlGet($url, $proxy = null) { $ch = curl_init($url); #curl_setopt($curl, CURLOPT_HTTPHEADER, array("Connection: close")); #curl_setopt($ch, CURLOPT_NOSIGNAL, 1); #curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); if (isset($proxy)) { if ($proxy['enable'] === '1') { $proxy['user'] === '' || #curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy['user'].':'.$proxy['pass']); #curl_setopt($ch, CURLOPT_PROXY, $proxy['host']); } } #curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 400); #curl_setopt($ch, CURLOPT_TIMEOUT, 10); #curl_setopt($ch, CURLOPT_HEADER, 0); #curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch); return $response; } $trackarray = $_POST['trackarray']; $returnarray = []; foreach($trackarray as $i => $track) { $strippedarray = explode(" - ", $track, 2); $strippedartist = $strippedarray[0]; $strippedtrack = $strippedarray[1]; $ArtistTrack = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=KEYHERE&artist=".$strippedartist."&track=".$strippedtrack."&format=json"; $ArtistL = "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&api_key=KEYHERE&artist=".$strippedartist."&format=json"; $AToutput = json_decode(curlGet($ArtistTrack, $proxy), true); $Aoutput = json_decode(curlGet($ArtistL, $proxy), true); if($AToutput == "" || $AToutput['track']['album']['image']['3']['#text'] == "") //Artist-Track failed, lets try just arist! { if($Aoutput == "" || $Aoutput['artist']['image']['3']['#text'] == "") //If Artist Failed, serve default-coverart.png { array_push($returnarray, "../location/cover-default.png"); } else //Artist success, serve artist.png { array_push($returnarray, $Aoutput['artist']['image']['3']['#text']); } } else //Artist-Track Success, Serve artist-track.png { array_push($returnarray, $AToutput['track']['album']['image']['3']['#text']); } } echo json_encode($returnarray); My Javascript: $('#spinner-db').removeClass('hide'); var windowwidth = $(window).width(); var blockwidth = 350; var rowcount = parseInt(windowwidth / blockwidth); var buffersize = parseInt(rowcount * 4); var endindex = parseInt(buffersize * 2); var loadimagearray = localcontent.slice(0,endindex); var currentdatabase = "#database-entries"; $.ajax({ url : '/location/script.php?cmd=commandhere', cache: false, type: 'POST', data: {trackarray: loadimagearray} }).done(function(data) { $.each( loadimagearray, function( i, l ) //Loop through each item in array { if($(currentdatabase+' li[track-info="' + l + '"] img').attr('src') == "../assets/img/cover-default.png") { $(currentdatabase+' li[track-info="' + l + '"] img').attr('src',JSON.parse(data)[i]); if(i == (loadimagearray.length - 1)) //Hide Loader { $('#spinner-db').addClass('hide'); } } }); });
PHP and timestamp protocol
In PHP i must sign a document with the Timestamp Protocol via HTTP (RFC 3161) using ARUBA as CA. The Aruba's documentation says: To time-stamp a datum you must call the url https://servizi.arubapec.it/tsa/ngrequest.php with a POST method. In the POST body you must insert the structure TimeStampReq (RFC 3161) encode in DER. How can i make the request using the php?
you can use curl function in php. Ok, This is part of my edited/modified tcpdf.php. //Send request to TSA Server with Curl if(extension_loaded('curl')) { $hdaLog .= "\nCurl was already Loaded\nCurl is sending tsRequest to \"".$this->timestamp_url."\""; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->timestamp_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_USERAGENT, '1'); curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data); $tsResponse = curl_exec($ch); if($tsResponse != false) { $hdaLog .= "\ntsRequest is sent"; } else { hdaLog("$hdaLog\ncan't send tsRequest, Timestamp failed",'w'); } //parse ts response $hexTs = bin2hex($tsResponse); $tsparse = asn1parse($hexTs); $tsparse0 = asn1parse($tsparse[0][1]); if(count($tsparse0 > 1)) { //Remove response status data, only take timeStampToken $timeStamp = seq($tsparse0[1][1]); } else { $timeStamp = seq($tsparse0[0][1]); } //Add timestamp to TCPDF Signature $timeStamp = seq("060B2A864886F70D010910020E".set($timeStamp)); $pkcs7 = int($pa1[0][1]).seq($pa1[1][1]).seq($pa1[2][1]).explicit(0, $pa1[3][1]).seq($pa1[4][1]).oct($pa1[5][1]); $time = seq($pkcs7.explicit(1,$timeStamp)); $aa=seq(int(1). set($p3[1][1]).seq($p3[2][1]).explicit(0, $p3[3][1]).set($time)); $hdaSignature = seq("06092A864886F70D010702".explicit(0,($aa)))."0000"; $signature = $hdaSignature; hdaLog("$hdaLog\nTimestamp Success"); } else { $hdaLog .= "\nCurl was not loaded, trying to load it..."; if(#dl('php_curl.dll')) { $hdaLog .= "\nCurl successfully Loaded"; } else { hdaLog("$hdaLog\nCurl failed to load timestamping failed", 'w'); } }
How to load details automatically
Thanks guys and gals got it working //create a function function get_stock_data($symbol){ //set up the url to be called $revenue_url = "http://finance.yahoo.com/q/is?s=".$symbol; //curl call: // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $revenue_url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // grab URL and pass it to the browser $result = curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); //finish by returning the result return $result; } //REQUEST WILL BE POPULATED IF EITHER GET OR POST IS SET! $data = null; // this will hold our data, declared here for accessibility if(isset($_REQUEST['symbol']) && $_REQUEST['symbol'] != ''){ //call our get_data function $data = get_stock_data($_REQUEST['symbol']); } // data returned from our get_stock_data() call. $ppe = $data['ppe']; $revenue = $data['revenue']; $income = $data['income']; $market_cap = $data['market_cap']; $depreciation = $data['depreciation']; $rate_of_return = $data['rate_of_return']; $rate_of_return_w_ppe = $data['rate_of_return_w_ppe']; $debt = $data['debt']; }
Add following code in your update button(page) script at last <script type="text/javascript"> var php_var = "<?php echo $symbol; ?>"; locationInfo="stock_next.php?symbol="+php_var; setTimeout(function(){ location =locationInfo },2000) </script> Your page will be automatically updated after some seconds