I might be asking the wrong question here, but I cant seem to figure out where this is coming form. I am using both the HTTP Request2 and NET URL2 libraries in order to send some GET request to the Vuforia web services. This all works fine, but everytime I send a request, it also shows said request on screen.
GET d41d8cd98f00b204e9800998ecf8427e Mon, 09 Dec 2019 22:49:52 GMT /summary/ba2246f8cd29466899c69b8d05af09a1
The code that I use to get the above text appear on screen is as follows.
Main code:
<?php if(sizeof($items) > 0){
foreach($items as $item){
echo '<tr>';
echo'<td>'.$item['itemid'].'</td>';
echo'<td>'.$item['name'].'</td>';
echo'<td>'.$item['surname'].'</td>';
echo'<td>'.$item['phone'].'</td>';
$recos = $targetdata = json_decode(CheckVuforiaTarget("ba2246f8cd29466899c69b8d05af09a1"), true);
echo'<td>'.$recos['current_month_recos'].'</td>';
}
} else echo '<tr><td>Geen kandidaten</td></tr>';?>
Script holding the CheckVuforiaTarget function:
function CheckVuforiaTarget($vuforiaid){
$vuforiaTargetTracker = new TargetTracker($vuforiaid);
$response = $vuforiaTargetTracker->TargetTracker();
return ($response);
//print_r($vuforiaResult);
}
TargetTracker class:
<?php
require_once 'HTTP/Request2.php';
require_once 'SignatureBuilder.php';
// See the Vuforia Web Services Developer API Specification - https://developer.vuforia.com/resources/dev-guide/retrieving-target-cloud-database
// The DeleteTarget sample demonstrates how to delete a target from its Cloud Database using the target's target id.
// * note that targets cannot be 'Processing' and must be inactive to be deleted.
class TargetTracker{
//Server Keys
private $access_key = "...";
private $secret_key = "...";
private $url = "https://vws.vuforia.com";
private $requestPath = "/summary/";
private $request;
private $targetId = "";
public function __construct($targetId) {
$this->targetId = $targetId;
}
function TargetTracker(){
$this->requestPath = $this->requestPath . $this->targetId;
return $this->execTargetTracker();
}
public function execTargetTracker(){
$this->request = new HTTP_Request2();
$this->request->setMethod( HTTP_Request2::METHOD_GET );
$this->request->setConfig(array('ssl_verify_peer' => false));
$this->request->setURL( $this->url . $this->requestPath );
$this->setHeaders();
try {
$response = $this->request->send();
if (200 == $response->getStatus()) {
return $response->getBody();
} else {
//echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
// $response->getReasonPhrase(). ' ' . $response->getBody();
return $response->getBody();
}
} catch (HTTP_Request2_Exception $e) {
return $e->getMessage();
}
}
private function setHeaders(){
$sb = new SignatureBuilder();
$date = new DateTime("now", new DateTimeZone("GMT"));
// Define the Date field using the proper GMT format
$this->request->setHeader('Date', $date->format("D, d M Y H:i:s") . " GMT" );
// Generate the Auth field value by concatenating the public server access key w/ the private query signature for this request
$this->request->setHeader("Authorization" , "VWS " . $this->access_key . ":" . $sb->tmsSignature( $this->request , $this->secret_key ));
}
}
?>
Both HTTP/Request2.php(and everything it came with) and SignatureBuilder.php are both default scripts/classes I've downloaded from the internet without altering them.
Now with my basic understanding of PHP, i've tried to find anything related to an echo or whatever command would show this on screen, but I can't seem to find it.
Does someone have some pointers for me, so I can figure out the source?
Thanks in advance!
The code you provided has no echo/print output that would explain the message you see. The echo/print statement must be somewhere else.
Related
I can't seem to find any code to display returned values from the call.
I am running the xml-lib from the software vendor at the following link
https://support.sippysoft.com/support/solutions/articles/3000013653-xml-rpc-api-sign-up-html-page-fresh-version-
<?php
include 'xmlrpc/xmlrpc.inc';
function listAccounts()
{
//$params = array(new xmlrpcval(array("i_account"=> new xmlrpcval('14719', "string")), 'struct'));
$msg = new xmlrpcmsg('listAccounts');
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('https://DOMAINHERE/xmlapi/xmlapi');
$cli->setSSLVerifyPeer(false);
$cli->setSSLVerifyHost(false);
$cli->setCredentials('USERNAME', 'PASSWORD', CURLAUTH_DIGEST);
$r = $cli->send($msg, 20);
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
print_r ($r->faultString());
return false;
}
else
{
return $r->value();
// I need something here to write returned values to normal PHP variable
}
}
Ok thanks to the comment from halfer.
I managed to get the issue and digging through the code in the library I found a function that does the trick.
Thanks a million for your pointer it really helped.
I am new to php and xml and the learning curve is quite tall but thanks.
for someone else reference maybe in the future here is the corrected code with the last 2 lines that does the magic for me.
<?php
include 'xmlrpc/xmlrpc.inc';
// $params = array(new xmlrpcval(array("offset"=> new xmlrpcval("1", "int")
// ,"i_customer"=> new xmlrpcval("321", "int")
// ), 'struct'));
$params = array(new xmlrpcval(array("i_customer"=> new xmlrpcval("321", "int")
), 'struct'));
$msg = new xmlrpcmsg('listAccounts', $params);
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('DOMAIN');
$cli->setSSLVerifyPeer(false);
$cli->setdebug(0);
$r = $cli->send($msg, 20); /* 20 seconds timeout */
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
echo $r->faultString();
}
// now lets decode the xml response..
$values=php_xmlrpc_decode($r->value());
var_dump ($values['accounts'][0][username]);
?>
I get my file via:
require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
use google\appengine\api\cloud_storage\CloudStorageTools;
$public_link = CloudStorageTools::getPublicUrl("gs://bucket/file.pdf", false);
If I go to $public_link in the browser, it shows the PDF inside the browser. I am trying to figure out how I can force the download of this file.
Google App Engine only has a 60 second timeout so I'm afraid the serve function wont work via GAE. Does anyone have any suggestions?
--
EDIT
Andrei Volga's previous answer in this post suggests I use a Signed URL with a response-content-distribution header.
So far, I am able to create a signed URL that successfully shows the file but I am not able to generate a signed url that has any sort of header at all aka create a signed URL that will force the download instead of just showing it.
This is what I have so far, most of which is courtesy of mloureiro.
function googleBuildConfigurationString($method, $expiration, $file, array $options = [])
{
$allowedMethods = ['GET', 'HEAD', 'PUT', 'DELETE'];
// initialize
$method = strtoupper($method);
$contentType = $options['Content_Type'];
$contentMd5 = $options['Content_MD5'] ? base64_encode($options['Content_MD5']) : '';
$headers = $options['Canonicalized_Extension_Headers'] ? $options['Canonicalized_Extension_Headers'] . PHP_EOL : '';
$file = $file ? $file : $options['Canonicalized_Resource'];
// validate
if(array_search($method, $allowedMethods) === false)
{
throw new RuntimeException("Method '{$method}' is not allowed");
}
if(!$expiration)
{
throw new RuntimeException("An expiration date should be provided.");
}
return <<<TXT
{$method}
{$contentMd5}
{$contentType}
{$expiration}
{$headers}{$file}
TXT;
}
function googleSignString($p12FilePath, $string)
{
$certs = [];
if (!openssl_pkcs12_read(file_get_contents($p12FilePath), $certs, 'notasecret'))
{
echo "Unable to parse the p12 file. OpenSSL error: " . openssl_error_string(); exit();
}
$RSAPrivateKey = openssl_pkey_get_private($certs["pkey"]);
$signed = '';
if(!openssl_sign( $string, $signed, $RSAPrivateKey, 'sha256' ))
{
error_log( 'openssl_sign failed!' );
$signed = 'failed';
}
else $signed = base64_encode($signed);
return $signed;
}
function googleBuildSignedUrl($serviceEmail, $file, $expiration, $signature)
{
return "http://storage.googleapis.com{$file}" . "?GoogleAccessId={$serviceEmail}" . "&Expires={$expiration}" . "&Signature=" . urlencode($signature);
}
$serviceEmail = '<EMAIL>';
$p12FilePath = '../../path/to/cert.p12';
$expiration = (new DateTime())->modify('+3hours')->getTimestamp();
$bucket = 'bucket';
$fileToGet = 'picture.jpg';
$file = "/{$bucket}/{$fileToGet}";
$string = googleBuildConfigurationString('GET', $expiration, $file, array("Canonicalized_Extension_Headers" => ''));
$signedString = googleSignString($p12FilePath, $string);
$signedUrl = googleBuildSignedUrl($serviceEmail, $file, $expiration, $signedString);
echo $signedUrl;
For small files you can use serve option instead of public URL with save-as option set to true. See documentation.
For large files you can use a Signed URL with response-content-disposition parameter.
You can add and additional query string only.
https://cloud.google.com/storage/docs/xml-api/reference-headers#responsecontentdisposition
response-content-disposition
A query string parameter that allows content-disposition to be overridden for authenticated GET requests.
Valid Values URL-encoded header to return instead of the content-disposition of the underlying object.
Example
?response-content-disposition=attachment%3B%20filename%3D%22foo%22
I am new to Web Services and am struggling to access/read the XML data using PHP (my website that will be using the data is in PHP).
The WSDL Url: http://services.mywheels.co.za/BWAVehicleStockService.svc?wsdl
I need to get access and read the Vehicle stock information but cant see to access anything.
the Array vehicle are stored under: http://services.mywheels.co.za/BWAVehicleStockService.svc?xsd=xsd2 .
i am using this code but it doesnt give my any data. I also have a GUID that i need to pass but have no idea how to add it to the header.
<?PHP
define('NEWLINE', "<br />\n");
// SOAP client
$wsdl = 'http://services.mywheels.co.za/BWAVehicleStockService.svc?wsdl';
$soapClient = new SoapClient($wsdl, array('cache_wsdl' => 0));
// SOAP call
$parameters->ArrayOfVehicle->Vehicle;
try
{
$result = $soapClient->GetVehicleStock($parameters);
}
catch (SoapFault $fault)
{
echo "Fault code: {$fault->faultcode}" . NEWLINE;
echo "Fault string: {$fault->faultstring}" . NEWLINE;
if ($soapClient != null)
{
$soapClient = null;
}
exit();
}
$soapClient = null;
echo "<pre>\n";
print_r($result);
echo "</pre>\n";
echo "Return value: {$result->GetDataResult}" . NEWLINE;
?>
if someone can help or point me in the right direction with this that would be great.
Thanks
You can add headers using __setSoapHeaders():
$h = new SoapHeader('http://tempuri.org/', 'Guid', '123');
$soapClient->__setSoapHeaders($h);
I had to read the WSDL itself to find out what namespace I should use; in this case they refer to Guid as tns:Guid and from the top you can read what URI is used to express that, hence http://tempuri.org.
I am trying to purge a file through the MaxCDN API but it's not working. Here's the code I'm using. The print_r doesn't return any result.
function purge() {
date_default_timezone_set('America/Los_Angeles');
$date = date('c');
$apiid = 'myapiid';
$apikey = 'myapi';
$auth_key = hash('sha256', $date.':'.$apikey.':purge');
$url = 'http://softsailor.alexdumitru.netdna-cdn.com/wp-content/themes/ss3/includes/sprite.jpg';
if (!class_exists('IXR_Client')) {
require_once (ABSPATH . WPINC . '/class-IXR.php');
}
$client = new IXR_Client('api.netdna.com','/xmlrpc/cache',80);
$client->timeout = 30;
$client->query('cache.purge', $apiid, $auth_string, $date, $url);
print_r($client->getResponse());
}
I turned debug on and I'm getting the following error
Something went wrong - -32300 : transport error - HTTP status code was not 200
Hey Alex. I work at MaxCDN and here is a code example that I took from our Wiki:
<?php
date_default_timezone_set('America/Los_Angeles');
include("lib/xmlrpc.inc");
$cur = date('c');
$apiKey = 'api-key';
$apiUserId = 'api-user-id';
$namespace = 'cache';
$method = 'purge';
$authString = hash('sha256', $cur . ':' . $apiKey . ':' . $method);
// this is the url to purge
$url= 'http://static.jdorfman.netdna-cdn.com/static/images/frugal-it-logo.png';
$f=new xmlrpcmsg("$namespace.$method", array(php_xmlrpc_encode($apiUserId),
php_xmlrpc_encode($authString), php_xmlrpc_encode($cur),
php_xmlrpc_encode($url)));
$c=new xmlrpc_client("/xmlrpc/cache", "api.netdna.com", 80,'http11');
$r=&$c->send($f);
print_r($r);
?>
If you have any other questions or concerns feel free to get in contact with me: jdorfman at maxcdn dot com
jdorfman's example dumps the entire raw response but if you are like me you want to get it into data objects using php
Here are some helpful tips:
$r->serialize() to access just the raw XML response
to convert to JSON use this:
$xml = simplexml_load_string($r->serialize());
echo json_encode($xml);
I wrote the class Link which has a method shortTolong() this should return the real URL for a shortened url by returning the 'location' response header. i tested it and it works OK
here is the code
public function shortTolong()
{
$urlMatch = array();
$ch = curl_init();
$options = array
(
CURLOPT_URL=>$this->getUrl(),
CURLOPT_HEADER=>true,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_FOLLOWLOCATION=>false,
CURLOPT_NOBODY=>true);
curl_setopt_array($ch, $options);
$server_output = curl_exec($ch);
preg_match_all(LINK, $server_output,&$urlMatch,PREG_SET_ORDER);
if($urlMatch)
{
foreach($urlMatch as $set)
{
$extracted_url = $set[2].'://'.$set[3];
}
return $extracted_url;
}
else
{
return $this->getUrl();
}
}
the problem starts when i try to use this method on other file which uses FeedParser to get feed entries that contain this short urls i ned to analyze from some reason i get as a result the short url instead of the long one here is the code:
foreach($parser->getItems() as $item)
{
$idpreg = '/\d+/';
preg_match_all($idpreg, $item['ID'],$statusid);
$retweetid = ($statusid[0][1]);
$datetime = $item['PUBLISHED'];
$user = $item['AUTHOR']['NAME'];
preg_match_all(LINK, $item['TITLE'], &$linkMatch);
$final = $linkMatch[0][0];
//if($linkMatch[0][0])
echo '<p>';
$link = new Link($final);
echo $link->getUrl();
echo '<br>';
echo $link->shortTolong();
echo '<br>';
echo $user;
echo '<br>';
echo $retweetid;
echo '</p>';
}
from some reason i get the same result for getUrl() and shortTolong() and i know for certain this is an error.
any ideas why this is happening?
Thanks
Edit- I added an error notice to the method with curl_eror
i get this error message: "Protocol http not supported or disabled in libcurl"
as i said i tested this method from the and it's working fine as as stand alone in the same environment (no changes) i suspect it has something to do with FeedParser using curl too....
i think you should trim() the url and that should resolve the issue.