No OpenID Server found at https://www.google.com/accounts/o8/id - php

Interesting enough I am using the same .php scripts on two different servers (a.com, b.com) with different results, I guess those have different configurations. While on a.com I am able to go through SSO process nicely, the b.com throws "No OpenID Server found at https://www.google.com/accounts/o8/id".
my php script looks as following:
$openid = new LightOpenID($_SERVER["HTTP_HOST"]);
$openid->required = array
(
'contact/email',
'namePerson/first',
'namePerson/last'
);
if(!$openid->mode)
{
$openid->identity = 'https://www.google.com/accounts/o8/id';
header('Location: ' . $openid->authUrl());
}
in b.com the line $openid->authUrl() throws an error saying:
No OpenID Server found at https://www.google.com/accounts/o8/id
What server configuration may cause this isse?

Luckily, server admins were able to quickly discover the config difference in php configuration allow_url_fopen = 1 solved the issue

Google has discontinued OpenID support and as of July 22nd 2015 has removed this endpoint.
The approved solution/answer has become obsolete.
Please migrate to OAuth. If using a client (javascript) login, this tutorial by google comes with a fully functional example.
this code below is another fully functional example (just tested it), but it goesone step further and integrates with a server side PHP script. please substitute your own CLIENT ID (as defined in your google developer console) and YOURDOMAIN.COM (in php).
<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="1111111111111111111-11111111111111111111111111111111111.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
userDataClear();
});
}
function disassociate() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.disconnect().then(function () {
console.log('User disconnected from association with app.');
userDataClear();
});
}
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://YOURDOMAIN.COM/twoStep02.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('NEW Signed in Google Client ID: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
console.log("ID Token: " + id_token);
userDataDisplay(profile);
}
function userDataDisplay(profile) {
document.getElementById("foto").innerHTML = '<img src="' + profile.getImageUrl() + '"></img>';
document.getElementById("email").innerHTML = profile.getEmail();
document.getElementById("nome").innerHTML = profile.getName();
}
function userDataClear() {
document.getElementById("foto").innerHTML = ' ';
document.getElementById("email").innerHTML = ' ';
document.getElementById("nome").innerHTML = ' ';
}
</script>
</head>
<body>
<div id="login-button" class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<div>Sign out</div>
<div>Disassociate App and Site (easily undone)</div>
<div id="foto"></div>
<div id="nome"></div>
<div id="email"></div>
</body>
</html>
and this is the php side to the jquery/ajax call (twoStep.php)
<?php
$idToken = $_POST["idtoken"];
$url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token='.$idToken;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$json = json_decode($response, true);
curl_close($ch);
$userEmail = $json["email"];
$clientId = $json["azp"];
print_r($json); // returns array console readable
?>
HINT 4 newbies: read console output by rightclicking on any element of the page and choosing "inspect element", then changing to CONSOLE tab.

Related

Tableau Trusted Authentication Ticket with PHP

I am trying to understand how the Trusted Authentication ticket is meant to work with PHP. I've been looking up different questions and came up with this code
$url = 'https://tableau.godigitally.io/trusted/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=" . $userid . ""); // define what you want to post
$response = curl_exec($ch);
curl_close($ch);
//echo 'Test: ' . $response;
echo '<iframe src=', $url, $ticket, 'views/Dashboard2_0/Dashboard1?', $urlparams, '"
width="700" height="400">
</iframe>';
But I get the following error when I run this code
I have no idea where I'm going wrong. I have confirmed that my server configuration is correct by using the testing techniques described in https://help.tableau.com/current/server/en-us/trusted_auth_testing.htm
To Work with Tableau and web UI , the best way, you should add a Tableau js library to your web application and follow the steps
Generate the Ticket from tableau server call ,
To generate the ticket from tableau server ,first you should add your user to tableau server and follow the below steps
this is the code sample which you can use to generate the ticket
function getTabTicket(tableauServer, username, site){
return new Promise((resolve,reject)=>{
let url = new URL(tableauServer + '/trusted');
let body = {
username: username,
};
if (site) {
body['target_site'] = site;
}
let postData = querystring.stringify(body);
let proto = http;
if (url.protocol === 'https:') {
proto = https;
}
let req = proto.request({
method: 'POST',
hostname: url.hostname,
port:url.port,
path: '/trusted',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}, function (response) {
let ticketData = '';
response.on('data', function (chunk) {
ticketData += chunk;
});
response.on('end', function () {
let contents = {ticket: ticketData};
resolve(contents);
});
});
req.on('error', function (error) {
reject(error);
console.log('ERROR: ' + error);
});
req.write(postData);
req.end();
})
}
You can check this library which is open source you can use to generate the Ticket.
https://github.com/aalteirac/jwt-tableau-broker
https://anthony-alteirac.medium.com/tableau-trusted-authentication-the-ticket-broker-cloud-friendly-709789942aa3
After generating Ticket , you have to call the tableau server to get the report .
I am using js library for that .
Now 2 step is include js using NPM or by reference
and then you can call the function
var tableuReport = new tableau.Viz(this.reportContainerDiv, fullTableauDashboardUrl, Constants.tableauReportUISettings);
reportContainerDiv // the div element in which you have to render the component
fullTableauDashboardURL = {tableau_server_url}+"trusted"/{ticektId}/reportsuburl // the tableau URL it is in the format
for example your ,
tableau_server_url = "https://tableau-dev-abc.com"
tableauDashboardUrl = "#/site/CovidApp/views/IndiaReport/IndiaReport_v2?:iid=1/"
ticketId = "fjdjadheuihrieywfiwnfih"
So your final URL will be like
fullTableauDashboardUrl = "https://tableau-dev-abc.com/trusted/fjdjadheuihrieywfiwnfih/t/CovidApp/views/IndiaReport/IndiaReport_v2?:iid=1
fullTableauDashboardUrl.replace("#/site", "t");
PS: we have to replace the #/site to t

Authentication for BandPage API

I am trying to access the BandPage API using this script which I found on Github. I have very little experience with PHP so can't really figure out what is wrong with this. This is the script:
<?php
function bandpageToken($client_id,$shared_secret) {
if($_COOKIE['bp_access_token']) {
$access_token = $_COOKIE['bp_access_token'];
} else {
//set POST variables
$url = 'https://api-read.bandpage.com/token';
$fields = array(
'client_id' => $client_id,
'grant_type' => "client_credentials"
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch,CURLOPT_USERPWD, $client_id . ':' . $shared_secret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
$obj = json_decode($result);
setcookie("bp_access_token", $obj->access_token, time()+$obj->expires_in-10);
$access_token = $obj->access_token;
//close connection
curl_close($ch);
}
return $access_token;
}
$app_id = 'MyIdIsHere';
$client_id = 'clientIdIsHere';
$shared_secret = 'sharedSecerecIsHere';
$access_token = bandpageToken($client_id,$shared_secret);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Bandpage Connect</title>
<script type='text/javascript'>;(function(){var e="sdk-js.bandpage.com",t="/embedscript/connect";window._rm_lightningjs||function(e){function n(n,r){var i="1";return r&&(r+=(/\?/.test(r)?"&":"?")+"lv="+i),e[n]||function(){var i=window,s=document,o=n,u=s.location.protocol,a="load",f=0;(function(){function l(){n.P(a),n.w=1,e[o]("_load")}e[o]=function(){function a(){return a.id=s,e[o].apply(a,arguments)}var t=arguments,r=this,s=++f,u=r&&r!=i?r.id||0:0;return(n.s=n.s||[]).push([s,u,t]),a.then=function(e,t,r){var i=n.fh[s]=n.fh[s]||[],o=n.eh[s]=n.eh[s]||[],u=n.ph[s]=n.ph[s]||[];return e&&i.push(e),t&&o.push(t),r&&u.push(r),a},a};var n=e[o]._={};n.fh={},n.eh={},n.ph={},n.l=r?r.replace(/^\/\//,(u=="https:"?u:"http:")+"//"):r,n.p={0:+(new Date)},n.P=function(e){n.p[e]=new Date-n.p[0]},n.w&&l(),i.addEventListener?i.addEventListener(a,l,!1):i.attachEvent("on"+a,l),n.l&&function(){function e(){return["<",r,' onload="var d=',p,";d.getElementsByTagName('head')[0].",u,"(d.",a,"('script')).",f,"='",n.l,"'\">"].join("")}var r="body",i=s[r];if(!i)return setTimeout(arguments.callee,100);n.P(1);var u="appendChild",a="createElement",f="src",l=s[a]("div"),c=l[u](s[a]("div")),h=s[a]("iframe"),p="document",d="domain",v,m="contentWindow";l.style.display="none",i.insertBefore(l,i.firstChild).id=t+"-"+o,h.frameBorder="0",h.id=t+"-frame-"+o,/MSIE[ ]+6/.test(navigator.userAgent)&&(h[f]="javascript:false"),h.allowTransparency="true",c[u](h);try{h[m][p].open()}catch(g){n[d]=s[d],v="javascript:var d="+p+".open();d.domain='"+s.domain+"';",h[f]=v+"void(0);"}try{var y=h[m][p];y.write(e()),y.close()}catch(b){h[f]=v+'d.write("'+e().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}n.P(2)}()})()}(),e[n].lv=i,e[n]}var t="_rm_lightningjs",r=window[t]=n(t);r.require=n,r.modules=e}({}),function(n){if(n.bandpage)return;var r=_rm_lightningjs.require("$rm","//"+e+t),i=function(){},s=function(t){t.done||(t.done=i),t.fail||(t.fail=i);var n=r("load",t);n.then(t.done,t.fail);var s={done:function(e){return n.then(e,i),s},fail:function(e){return n.then(i,e),s}};return s},o=null;n.bandpage={load:s,ready:function(e){o.then(e,i)}},o=r("bootstrap",n.bandpage,window)}(window)})(this);</script>
<script type="text/javascript">
bandpage.load({
"done" : function() {
var connection = bandpage.sdk.connect({
appId : "<?=$app_id?>",
access_token : "<?=$access_token?>",
container : $('.btn-container').get(0),
allow_reconnect : false
});
connection.on("bpconnect.complete", function(bands){
console.log("User has authed bands!");
console.log(bands);
});
connection.on("bpconnect.cancel", function(){
console.log("User clicked the cancel button and connect window is closed");
});
},
"fail" : function() {
console.log("Failed to initialize sdk");
}
});
</script>
<style>
.btn-container {
top: 50%;
position: absolute;
left: 50%;
margin: -22px 0 0 -117px;
}
</style>
</head>
<body>
<div class='btn-container'></div>
</body>
</html>
and the error seems to be with the bp_access_token, errors below.
Notice: Undefined index: bp_access_token in C:\wamp\www\Testing\index.php on line 5
Notice: Trying to get property of non-object in C:\wamp\www\Testing\index.php on line 33
Notice: Trying to get property of non-object in C:\wamp\www\Testing\index.php on line 34
Do I need to declare bp_access_token somewhere or am I missing something else?
The script hasn't been written very well. On line 5, an array access is made in the cookies array without first checking it exists. The author may have display_errors turned off, but not everyone does.
This:
if($_COOKIE['bp_access_token']) {
would be better expressed as:
if(isset($_COOKIE['bp_access_token']) && $_COOKIE['bp_access_token']) {
That will fix your first notice. As for the other two, you are making object accesses on null values in these lines:
setcookie("bp_access_token", $obj->access_token, time()+$obj->expires_in-10);
$access_token = $obj->access_token;
My guess would be that your authentication to BandPage has failed, and you don't have a valid response object to work with. Double-check the values of these in the script, which must be supplied by you:
$app_id
$client_id
$shared_secret
You can probably get these from a control panel somewhere in your BandPage account screen.
add error_reporting(E_ALL ^ E_NOTICE);
just after <?php tag.
if your script is working perfectly but warning/notices are showing, you can add
error_reporting(0);
keep in mind to comment out this line as soon as you face some problem with this script next time.

jQuery send file chunks to PHP upload to Ooyala

I have been stuck on this for over a week and I think I am long overdue for asking on here.. I am trying to get my users to upload their video files using the jQuery File Upload Plugin. We do not want to save the file on our server. The final result is having the file saved in our Backlot using the Ooyala API. I have tried various approaches and I am successful in creating the asset in Backlot and getting my upload URLs, but I do not know how to upload the file chunks using the URLs into Backlot. I have tried FileReader(), FormData(), etc. I am pasting the last code I had that created the asset, and gave me the upload URLs, but did not save any chunks into Backlot. I assume I may be getting stuck in one of my AJAX calls, but I am not very sure.
I keep getting:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
Here is my page with the JS for the jQuery File Upload widget by BlueImp:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.fileupload.js"></script>
</head>
<body>
<input id="fileupload" type="file" accept="video/*">
<script>
//var reader = FileReader();
var blob;
$('#fileupload').fileupload({
forceIframeTransport: true,
maxChunkSize: 500000,
type: 'POST',
add: function (e, data) {
var goUpload = true;
var ext = ['avi','flv','mkv','mov','mp4','mpg','ogm','ogv','rm','wma','wmv'];
var uploadFile = data.files[0];
var fileName = uploadFile.name;
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if ($.inArray( fileExtension, ext ) == -1) {
alert('You must upload a video file only');
goUpload = false;
}
if (goUpload == true) {
$.post('../sites/all/themes/episcopal/parseUploadJSON.php', 'json=' + JSON.stringify(data.files[0]), function (result) {
var returnJSON = $.parseJSON(result);
data.filechunk = data.files[0].slice(0, 500000);
data.url = returnJSON[0];
//reader.onloadend = function(e) {
//if (e.target.readyState == FileReader.DONE) { // DONE == 2
//data.url = returnJSON[0];
// }
//}
//$.each(returnJSON, function(i, item) {
//data.url = returnJSON[0];
//blob = data.files[0].slice(0, 500000);
//console.log(blob);
//reader.readAsArrayBuffer(blob);
//data.submit();
//});
data.submit();
});
}
},//end add
submit: function (e, data) {
console.log(data); //Seems fine
//console.log($.active);
$.post('../sites/all/themes/episcopal/curlTransfer.php', data, function (result) { //fails
console.log(result);
});
return false;
}
});
</script>
</body></html>
Then there is the parseUploadJSON.php code, please keep in mind that my real code has the right Backlot keys. I am sure of this:
<?php
if(isset($_POST['json'])){
include_once('OoyalaAPI.php');
$OoyalaObj = new OoyalaApi("key", "secret",array("baseUrl"=>"https://api.ooyala.com"));
$expires = time()+15*60; //Adding 15 minutes in seconds to the current time
$file = json_decode($_POST['json']);
$responseBody = array("name" => $file->name,"file_name"=> $file->name,"asset_type" => "video","file_size" => $file->size,"chunk_size" => 500000);
$response = $OoyalaObj->post("/v2/assets",$responseBody);
$upload_urls = $OoyalaObj->get("/v2/assets/".$response->embed_code."/uploading_urls");
$url_json_string = "{";
foreach($upload_urls as $key => $url){
if($key+1 != count($upload_urls)){
$url_json_string .= '"' . $key . '":"' . $url . '",';
}else {
$url_json_string .= '"' . $key . '":"' . $url . '"';
}
}
$url_json_string .= "}";
echo $url_json_string;
}
?>
Then I have the curlTransfer.php:
<?php
echo "starting curl transfer";
echo $_POST['filechunk'] . " is the blob";
if(isset($_FILES['filechunk']) && isset($_POST['url'])){
echo "first test passed";
$url = $_POST['url'];
//print_r(file_get_contents($_FILES['filechunk']));
$content = file_get_contents($_FILES['filechunk']);
print_r($content);
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: multipart/mixed"));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
try {
//echo 'success';
return httpRequest($ch);
}catch (Exception $e){
throw $e;
}
}
/****Code from Ooyala****/
function httpRequest($ch){
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if(curl_error($ch)){
curl_close($ch);
return curl_error($ch);
}
$head=curl_getinfo($ch);
$content = $head["content_type"];
$code = $head["http_code"];
curl_close($ch);
}
?>
And the OoyalaApi.php is here (I saved a copy on my server):
https://github.com/ooyala/php-v2-sdk/blob/master/OoyalaApi.php
I apologize in advance if the code is messy and there's a lot of parts commented out. I have changed this code so much and I cannot get it. I appreciate all of your time and effort.
EDIT
I went back to trying FileReader out as this post Send ArrayBuffer with other string in one Ajax call through jQuery kinda worked for me, but I think it would be safer to read it using readAsArrayBuffer and now I am having trouble saving the array buffer chunks in some sort of array...
We have implemented ooyala file chunk upload in Ruby On Rails by referring this.
We have used the entire JS file as it is from this link.
https://github.com/ooyala/backlot-ingestion-library

Executing Javascript in an external file via php script

I have been trying to create a php file which basically is a mobile shortcode message. Since any output on the page automatically gets shown in the mobile SMS, I cannot use any html on the page. But I am having a problem in executing some google analytics javascript code before the text is outputted on the page. I create an external file and wrote the javascript there and tried to execute the file via curl, but curl does not execute the javascript. So my code for the main file SMSapi.php is something like this:
<?php
if(isset($_GET['mobile'])){
$number = $_GET['mobile'];
}
if(isset($_GET['text'])){
$data = $_GET['text'];
}
$brand = "mybrand";
$event = "MyEvent";
$deal = "MyDeal";
$url = "http://myurl.com/sms.php";
$post_string = "brand={$brand}&event={$event}&deal={$deal}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$success = curl_exec($ch);
curl_close($ch);
echo "Your discount code is XYZ123";
?>
The sms.php code is as follows:
<?php
if(isset($_POST) && !empty($_POST['event']) && !empty($_POST['brand']) && !empty($_POST['deal'])):
$event = urldecode($_POST['event']);
$brand = urldecode($_POST['brand']);
$deal = urldecode($_POST['deal']);
?>
<html>
<head>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-MyNum']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
_gaq.push(['_trackEvent', '<?php echo $event; ?>', '<?php echo $brand; ?>', '<?php echo $deal; ?>']);
</script>
</head>
</html>
<?php endif ?>
the main SMS api file makes a curl request to the sms.php file and while the file gets executed, the html and javascript gets returned back as text without any execution happening there. And hence the javascript shows up in the SMS.
Is there a way to implement a external url and all the javascripts in it there and there via php?
This link might be useful for you: http://curl.haxx.se/docs/faq.html#Does_curl_support_Javascript_or
I am presuming this is a script that runs on a call from an SMS provider, and you are tying to log this event in Google Analytics.
Firstly, I would have thought this would more easily be accomplished by logging to a database, rather than to Analytics. As the javascript is running server side, you won't get any extra information other that the event.
If you really do need to run the Google code then you need to try searching on "server side javascript google analytics". The solution is going to be highly dependant on what server platform you are running and what is/can be installed.
One interesting link though which may work for your PHP is:
http://code.google.com/p/serversidegoogleanalytics/
but I haven't used it so don't know how well this works.

Proxy to connect to XML cross server..Using Ajax works on some browsers not others? code included

Ok so first let me explain what I am doing:
I am trying to connect to http://www.nfl.com/liveupdate/scorestrip/ss.xml to grab the xml and parse it of course cross domain policy wont allow me to do this directly. SOOOO..
I am using PHP to connect to the site through a proxy and this works perfectly
Then back in my main HTML file I am using Ajax to parse through that XML file. Problem is I am getting mixed results. For instance on my macbook pro with all the latest browsers (Safari, Firefox, Chrome) this doesn't work. On my iPhone it works. and on my Mac Desktop with all latest browsers it works.
Anyone know why?
ALSO I have no clue what I am doing with XML this is my very first attempt to learn how to read through XML. SO I may need you to explain how to better parse though as the way I am doing it now is from a fellow online user.
Here is the PHP proxy which works:
<?php
$server_url = "http://www.nfl.com/liveupdate/scorestrip/ss.xml";
$options = array
(
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 0,
CURLOPT_HTTPGET => 1
);
$service = $_GET["service"];
$request_headers = Array();
foreach($_SERVER as $i=>$val) {
if (strpos($i, 'HTTP_') === 0) {
$name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
if ($name != 'HOST')
{
$request_headers[] = "{$name}: {$val}";
}
}
}
$options[CURLOPT_HTTPHEADER] = $request_headers;
switch (strtolower($_SERVER["REQUEST_METHOD"]))
{
case "post":
$options[CURLOPT_POST] = true;
$url = "{$server_url}".$service;
$options[CURLOPT_POSTFIELDS] = file_get_contents("php://input");
break;
case "get":
unset($_GET["service"]);
$querystring = "";
$first = true;
foreach ($_GET as $key => $val)
{
if (!$first) $querystring .= "&";
$querystring .= $key."=".$val;
$first = false;
}
$url = "{$server_url}".$service."?".$querystring;
break;
default:
throw new Exception("Unsupported request method.");
break;
}
$options[CURLOPT_URL] = $url;
$curl_handle = curl_init();
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);
$response = explode("\r\n\r\n",$server_output);
$headers = explode("\r\n",$response[0]);
foreach ($headers as $header)
{
if ( !preg_match(';^transfer-encoding:;ui', Trim($header)) )
{
header($header);
}
}
echo $response[1];
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
Here is the troublesome HTML file with AJAX:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
$.ajax({
type: "GET",
url: "http://www.allencoded.com/test3.php",
dataType: "xml",
success: function(xml) {
// Interpret response
$(xml).find('g').each(function() {
// Example: Show the XML tag in the console
console.log(this);
// Example: Put some output in the DOM
$("#divOutput").append($(this).attr("hnn"));
});
$(xml).find('g').each(function() {
// Example: Put some output in the DOM
$("#divOutput").append($(this).attr("vnn"));
});
}
});
</script>
<div id="divOutput"></div>
</body></html>
Finally here is XML for reference:
http://www.nfl.com/liveupdate/scorestrip/ss.xml
I am really looking for a way to parse this as it will be an awesome learning experience. BTW if it helps Firefox on my macbook with all the problems is telling me: missing ) in parenthetical line 12
Also I would greatly appreciate it if you were so kind to answer in terms a noobie may understand for dealing with XML as I am new to it.
Thanks!
Edit:
Adding my website links to this code:
http://allencoded.com/footballxml.html
and
http://allencoded.com/test3.php
If it's not caused by some C&P issue, this could be the cause:
$(xml).find('g').each(function() {
// Example: Put some output in the DOM
$("#divOutput").append($(this).attr("vnn"));
}) //Here is a colon missing!

Categories