XML parsing in PHP not capturing one variable - php

I am doing user Basic Auth in PHP and getting the results of the authentication via an XML file which is then parsed into PHP variables.
Here is the PHP code:
<?php
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
$str = $username . ":" . $password;
$client_id = md5($str);
$auth_str = base64_encode($str);
$client_id_str = "client-identifier: " . $client_id;
$plex_auth = "authorization: Basic " . $auth_str;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://someurl/sign_in.xml",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
$plex_auth,
$client_id_str,
"header3",
"header4"
),
));
$response = curl_exec($curl);
$xml = simplexml_load_string($response);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
$user_token = $xml->authenticationtoken;
$user_email = $xml->email;
echo $user_email;
echo $user_token;
?>
This is the response in XML:
<?xml version="1.0" encoding="UTF-8"?>
<user email="xyz#gmail.com" id="2567053"
thumb="https://secure.gravatar.com/avatar/somenumber"
username="Admin" title="Admin" cloudSyncDevice=""
authenticationToken="SomeToken" scrobbleTypes="">
<subscription active="1" status="Active" plan="lifetime">
<feature id="pass"/>
<feature id="sync"/>
<feature id="cloudsync"/>
<feature id="home"/>
</subscription>
<profile_settings auto_select_audio="1" auto_select_subtitle="0"
default_audio_language="en" default_subtitle_language="en"/>
<username>Admin</username>
<email>xyx#gmail.com</email>
<joined-at type="datetime">2014-05-08 17:59:24 UTC</joined-at>
<authentication-token>SomeToken</authentication-token>
</user>
Now for some reason while I can extract every other variable from the XML, the authenticationToken refuses to get parsed. when I echo user_token, it's completely empty!

According to the PHP docs examples on SimpleXML:
Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.
So you can access it like this:
$user_token = $xml->{'authentication-token'};

The response in XML you provided does not appear to be a valid xml string.
I was unable to parse it until i added a '>' to the end of the 'user' tag.
Also, as mentioned in the answer before mine, you will need to access object properties that contain special characters with bracers and single qoutes:
$user_token = $xml->{'authentication-token'};
or like this:
$auth_token = 'authentication-token';
$user_token = $xml->$auth_token;

Related

Generate Public API Key from USAePay Rest API Returning Error

I have been trying to generate a Public API key for my USAePay account to use with a USAePay Client JS iFrame using PHP.
The CURL request keeps returning error code 80: Transaction type not allowed from this source.
I have tried with and without a pin and in both test mode using sandbox.usaepay. . . and in regular mode without the sandbox in the URL (changing the SourceKey in the console appropriately).
Is it possible that there is something wrong with my PHP code, or am I missing some other setting?
$seed = "abcdefghijklmnop";
$apikey = "mysourcekeyfromconsole";
$apipin = "1234";
$prehash = $apikey . $seed . $apipin;
$apihash = "s2/" . $seed . "/" . hash("sha256",$prehash);
$authKey = base64_encode($apikey . ':' . $apihash);
//print("Authorization: Basic " . $authKey);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://sandbox.usaepay.com/api/v2/publickey",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
]);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"Content-Type: application.json",
"Authorization: Basic " . $authKey
]);
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
It seems that this does not work from the sandbox, only from "https://usaepay.com/api/v2/publickey". I don't know why it did not work initially when I tried that, unless I changed some other code or setting. Now, though, when I try to change my code to sandbox, it returns an error, and without sandbox, it returns the public key.

PHP JSON error parsing the JSON document. The document may not be well-formed

This is my code:
if ($_SERVER ["REQUEST_METHOD"] === "GET") {
include_once('../database/dbSource.php');
$databaseSource = DataBaseSource::getInstance();
//Parse
$ini_array = parse_ini_file("../../pto/config.ini");
$user = $_GET['userSid'];
$username = $ini_array['ctsi_CIBMON_fid'];
$password = $ini_array['ctsi_CIBMON_pass'];
$ctsi_url = $ini_array['ctsi_url'] . $user . '&view=full';
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n" .
"Authorization: Basic " . base64_encode("$username:$password")
)
);
$context = stream_context_create($opts);
echo file_get_contents($ctsi_url, false, $context);
} else {
echo $_SERVER ["REQUEST_METHOD"];
}
I get the following error :
There was an error parsing the JSON document. The document may not be
well-formed.
I tried checking addiitonal spaces in code (which i removed) etc.
Also there is no issues with authorization.
Can't figure out what's the issue.
Please help.
Note: Also it used to work but stopped working without any change to code even. so Strange.
also the url that i am trying to access is https://xxx.xxx.net not http - does it matter?

Global scope not working within PHP function [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
I declared configuration variables in a configuration file and want to access these variables from within a function on the same page. This function will make a SOAP call to a service to fetch some data.
I include this configuration file on various pages, but when I access the function, the variables are empty, even when I declare a global score. My (simplified) code looks like this:
config.php
// Set environment
$environment = 'dev';
switch($environment){
case 'dev':
$username = 'dev';
$client = new SoapClient('http://dev.example.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0));
break;
case 'prod';
$username = 'prod';
$client = new SoapClient('http://prod.example.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0));
break;
default:
$username = 'prod';
$client = new SoapClient('http://prod.example.com/wsdl?wsdl', array('trace' => 1, 'exceptions' => 0));
}
function fetch_data($request_id){
global $username;
$xml_post_string = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ver="https://example.com">
<soapenv:Header/>
<soapenv:Body>
<ver:options>
<ver:rid>'.$request_id.'</ver:rid>
<ver:uid>'.$username.'</ver:uid>
</ver:options>
</soapenv:Body>
</soapenv:Envelope>
';
echo '<pre>';
echo 'Var: '.$username; // = empty
echo '</pre>';
// Curl headers
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: "https://example.com",
"Content-length: ".strlen($xml_post_string),
);
// Curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/call?wsdl');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute Curl call
$response = curl_exec($ch); // = credential error
}
On page.php i include & call the function like this:
require_once('config.php');
[..]
$response = fetch_data('1');
When I type the username in the XML string I get the response I want, but when I use the variable (as in the example) I get an empty value for $username.
But why?
edit: changed exit; to break; and added process & output example
** edit 2:**
The code between the [..]
require_once('config.php');
global $current_user, $wp_query;
$user = wp_get_current_user();
$user_meta = get_user_meta($user->data->ID, 'exID');
$user_member_number = trim($user_meta[0]);
// Set locale for date notation
setlocale(LC_ALL, 'nl_NL');
$policy_id = $_GET['polis'];
$customer_call = array(
'options' => array(
'Credentials' => array(
'UserId' => $username // Normally more credentials like password are required as well
)
)
);
$customer_response = $client->FetchCustomer($customer_call);
$member_details = $customer_response->FetchCustomerResult->Result->PlatformCustomer;
$product_call = array(
'options' => array(
'Credentials' => array(
'UserId' => $username // Normally more credentials like password are required as well
)
),
);
$product_response = $client->FetchProduct($product_call);
if($product_response->FetchProductResult->Succeeded){
// Extract results
$product_info = $product_response->FetchProductResult->Result;
// Differentiate product response, depending on the amount of rows returned
if($product_info->SummarizedProductInfo >= 2){
$products = $product_response->FetchProductResult->Result->Summary;
}else{
$products = $product_response->FetchProductResult->Result;
}
// Policy numbers for given user (for authentication purpose)
$member_active_policies = array();
// Iterate through policies and write policy number to array
foreach($products as $product){
array_push($member_active_policies, $product->PolicyNumber);
}
// Check if requested polis belongs to user
if(in_array($policy_id, $member_active_policies)){
// Iterate through products to find the requested
foreach($products as $product){
if($product->PolicyNumber == $policy_id){
// Set member variables, all with prefix $member_
// Set product variables, all with prefix $product_
// Fetch information about other members
$all_members = fetch_data(1)->GetProductInfo;
I can see 2 problems here.
Your fetch_data function is not returning anything. I guess it should return $xml_post_string ?
Even if you return $xml_post_string , your code will work if your environment is "dev", when you will supply "prod", it will exit from the script on "exit", therefore your script will not be having fetch_data function.

Get data from XML sites

I want to get some data from a site based on xml's.
The problem is I need to be logged to it as a PublicUser without password.
I have tryed:
$url = 'http://IP/wcd/system_counter.xml';
$content = file_get_contents($url);
echo $content
But i only get this:
err En ReloginAttempt /wcd/index.html false
This is the xml code used for loggin:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="top.xsl" type="text/xsl"?>
<MFP>
<SelNo>Auto</SelNo>
<LangNo>En</LangNo>
<Service><Setting><AuthSetting><AuthMode><AuthType>None</AuthType>
<ListOn>false</ListOn>
<PublicUser>true</PublicUser>
<BoxAdmin>false</BoxAdmin>
</AuthMode><TrackMode><TrackType>None</TrackType></TrackMode></AuthSetting>
<MiddleServerSetting><ControlList><ArraySize>0</ArraySize></ControlList><Screen>
<Id>0</Id></Screen></MiddleServerSetting>
</Setting></Service><LangDummy>false</LangDummy></MFP>
Is there a way to send the user as well when i want to get the XML info ?
You cannot access pages requiring posted login information using file_get_contents. Instead you need to use curl. Something along these lines:
$ch = curl_init($url); // The url you want to call
curl_setopt_array(
$ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $login_xml, // The xml login in string form
)
);
//getting response from server
$response = curl_exec($ch);
echo curl_error($ch);
curl_close($ch);

Strange chars in JSON (obtained after cURL auth)

This is the function I use to grab a JSON file from Feedbin API.
<?php
error_reporting(E_ALL);
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';
$username = 'my_username'; // authentication
$password = ' my_password'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password // authentication
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
print_r ($result);
?>
Problem is the JSON I get is a bit.. strange.
It has a lot of chars like \u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E ...
You can see the JSON here.
When you call json_decode in PHP on strings that contain these encodings they will be correctly decoded. http://json.org/ lists \ufour-hex-digits as a valid character. There is no issue.
$ echo json_decode('"\u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E"');
></a></p>
<p>
They are valid unicode sequence. Here is a simple example
$data = array(
"abc" => 'åbcdéfg'
);
// Encode
$data = json_encode($data) . "\n";
// Output Value
echo $data;
// Output Decoded Value
print_r(json_decode($data));
Output
{"abc":"\u00e5bcd\u00e9fg"}
stdClass Object
(
[abc] => åbcdéfg
)

Categories