I am working on installing the aws sdk for PHP on my Windows machine (Win7 64 bit) PHP v 5.5.12.
I tried using all the 3 methods viz Composer,zip and PHAR mentioned here.All the 3 ways give me the same error as below.
Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Space required after the Public Identifier in C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php on line 41
Here's the function which givess the error
public function parse(RequestInterface $request, Response $response)
{
$data = array(
'code' => null,
'message' => null,
'type' => $response->isClientError() ? 'client' : 'server',
'request_id' => null,
'parsed' => null
);
if ($body = $response->getBody(true)) {
$this->parseBody(new \SimpleXMLElement($body), $data); //THIS LINE GIVES ERROR
} else {
$this->parseHeaders($request, $response, $data);
}
return $data;
}
Here is how I try to use it.
error_reporting(E_ALL);
define('AWS_KEY', 'MyAWSKEY');
define('AWS_SECRET_KEY', 'MYSECRETKEY');
define('HOST', 'http://localhost'); //tried changing host to diff values,but don't
//think thats the issue
// require the AWS SDK for PHP library
require 'aws-autoloader.php';
//require '../../aws.phar';
use Aws\S3\S3Client;
// Establish connection with an S3 client.
$client = S3Client::factory(array(
'base_url' => HOST,
'key' => AWS_KEY,
'secret' => AWS_SECRET_KEY
));
$o_iter = $client->getIterator('ListObjects', array(
'Bucket' => 'mybucketname'
));
foreach ($o_iter as $o) {
echo "{$o['Key']}\t{$o['Size']}\t{$o['LastModified']}\n";
}
Heres the stacktrace
[17-Jul-2014 04:19:01 Europe/Paris] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php:41
Stack trace:
#0 C:\wamp\www\aws-sdk-php- master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php(41): SimpleXMLElement- >__construct('<!DOCTYPE HTML ...')
#1 C:\wamp\www\aws-sdk-php-master\src\Aws\S3\Exception\Parser\S3ExceptionParser.php(33): Aws\Common\Exception\Parser\DefaultXmlExceptionParser->parse(Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Message\Response))
#2 C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Client\ExpiredCredentialsChecker.php(61): Aws\S3\Exception\Parser\S3ExceptionParser->parse(Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Message\Response))
#3 C:\wamp\www\aws-sdk-php-master\vendor\guzzle\guzzle\src\Guzzle\Plugin\Backoff\AbstractBackoffStrategy.php(39): Aws\Common\Client\ExpiredCredentialsChecker->getDelay(0, Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Message\Resp in C:\wamp\www\aws-sdk-php-master\src\Aws\Common\Exception\Parser\DefaultXmlExceptionParser.php on line 41
Tried googling it and learnt might be due to magic_quotes in php.ini to be on,but thats not the case,actually I don't have magic_quotes itself in my ini file.
Checked the stack trace and it shows the same error.I am not able to figure out if its a system issue or some configuration problem as I get it for all the methods.
Is this a issue with some configuration? OR I am missing something?
Oh, I see what's going on. You should not be setting the base_url parameter. By setting that value you are telling the SDK to send the requests to your localhost, instead of the actual S3 service. Your localhost is returning HTML, not a XML, which is why SimpleXML is throwing parse errors.
To use S3, you should provide your credentials (key and secret), and optionally a region if you are intentionally not using S3's default region. Do not override the base_url value, which is something that the SDK resolves internally based on its knowledge of the service endpoints.
Note: we also encourage users to use a credential profile profile instead of explicit credentials (key and secret) so you can store your credentials in a file outside of your code and project, in order to prevent accidental credential leaks (e.g., committing credentials into version control). The S3 page in the User Guide walks you through how to properly create the client and provides a link to learn more about the credential file/profile.
Related
I'm trying to build an app around the brightzone gremlin php api for cosmos db (free tier). I can get the api to work through the console (with the provided app) but when I try to use my own custom functions to call the exact same methods available in the API class – practically copying the code, which worked through the console) – I get this...
Fatal error: Uncaught TypeError: fwrite(): Argument #1 ($stream) must be of type resource, null given {...}
on line 174 in vendor/brightzone/gremlin-php/src/Connection.php
I'm new to Gremlin in general, and have limited experience using APIs.
Is this some limitation to the free tier, or have I completely misunderstood something?
edit
I decided to test the api with varying degrees of extra setup on my part...
Running the PHP CLI script: connect.php (included in cosmos graph php getting started quickstart) from a browser through xampp gave no errors. I'm seeing a spike in requests in cosmos' dashboard when I do this, so I know it's hitting the database.
The same test through a vhost alias also gave no errors, while hitting the database.
Creating my own function that calls the class and methods results in the fwrite error above.
Initializing the object
This is the same on both the CLI version and my script.
<?php
require_once('define.php');
require_once('vendor/autoload.php');
use \Brightzone\GremlinDriver\Connection;
$db = new Connection([
'host' => HOST,
'username' => USER,
'password' => PASS
,'port' => PORT
// Required parameter
,'ssl' => TRUE
]);
code comparison
Here's the provided CLI script I'm trying to emulate...
function countVertices($db)
{
$query = "g.V().count()";
printf("\t%s\n\tQuery: %s\n", "Counting all the vertices.", $query);
$result = $db->send($query);
if($result)
{
printf("\tNumber of vertices in this graph: %s\n\n", $result[0]);
}
}
This results in an instant readout of the printf commands meant for command line responses, with correct data from the result property of the object, showing it was initialized, and then functioned properly.
but
Here's how I'm trying to call the method...
$query = "g.V().count()";
$result = $db->send($query);
var_dump($result);
The object initializes fine, but calling the send method throws the fwrite error.
Seriously... what am I missing?
I failed to check the END of the CLI php script, which had a "try" catch statement running all the functions. If I had checked, I'd have seen that the open and close methods...
$db->open();
//<--whatever querying here-->
$db->close();
are necessary to get the gremlin driver connected.
It's all working now with:
<?php
require_once('define.php'); //custom script defining credentials as constants
require_once('vendor/autoload.php');
use \Brightzone\GremlinDriver\Connection;
error_reporting(E_ALL ^ E_WARNING);
$db = new Connection([
'host' => HOST,
'username' => USER,
'password' => PASS,
'port' => '443'
// Required parameter
,'ssl' => TRUE
]);
$db->timeout = 0.5;
$db->open();
$query = "g.V().count()";
var_dump($db->send($query));
$db->close();
?>
This prints the correct response.
Using the PHP SoapClient, I make a call to the WSDL at https://webservices-test.ede.de:9443/ibis/ws/WS_EXT_ELC?wsdl and I get the following xml response (as indicated by $soapclient->__last_response)
<?xml version='1.0' encoding='UTF-8'?><soap:Envelope xmlns:ede="http://ede.de/webservices" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Body><Response action="ELC" requestId="1" version="1.0"><created>2017-09-04T16:04:46.556+02:00</created><StatusInformation>OK</StatusInformation><StatusCode>0</StatusCode><Payload><SalesOrderSimulateConfirmation><Items><Item><ID>10</ID><ProductID>0003062700050</ProductID><Price>2.970</Price><PositionPrice>2.970</PositionPrice><PriceUnit>1</PriceUnit><QuantityUnit>ST</QuantityUnit><QuantityAvailable>1</QuantityAvailable><QuantityProfile>1</QuantityProfile><Currency>EUR</Currency><Services /><Schedules>Geplante Liefertermine: 1 ST in KW 36.2017;</Schedules><Remark /><DangerMaterial /></Item></Items></SalesOrderSimulateConfirmation></Payload></Response></soap:Body></soap:Envelope>
Nevertheless, the call to $soapclient->simulateOrder() returns null.
How do I get the PHP SoapClient to return an object instead of null?
Note: The xml I use for the soap call is generated manually by an override to SoapClient::__doRequest(). The code for the soap call looks like:
$soapClient = new SoapClient('https://webservices-test.ede.de:9443/ibis/ws/WS_EXT_ELC?wsdl', array(
'cache_wsdl' => WSDL_CACHE_NONE,
'trace' => true,
'exceptions' => true,
'soap_version' => SOAP_1_2,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'login' => '------', // cannot post here for security purposes
'password' => '-----', // cannot post here for security purposes
'stream_context' => (
stream_context_create(array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
))
));
$result = $soapClient->simulateOrder();
No exceptions are thrown, but $result is null
The problem is the SSL setup, the error that is thrown when I try to call your code on my server is as follows:
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://webservices-test.ede.de:9443/ibis/ws/WS_EXT_ELC?wsdl' : failed to load external entity "https://webservices-test.ede.de:9443/ibis/ws/WS_EXT_ELC?wsdl" in /home/repojarilo/public_html/sc.php:22 Stack trace: #0 /home/repojarilo/public_html/sc.php(22): SoapClient->SoapClient('https://webserv...', Array) #1 {main} thrown in ... on line 22
I am assuming you are trying to get the code to work with a self signed certificate as indicated in your SSL array inside of the request, however it looks like the SoapClient is not paying attention to it and throwing an error anyway.
So my solution would be to either buy an SSL (very cheap now days, try sites such as namecheap etc...) or use something like https://letsencrypt.org/ to obtain an SSL that will allow your soap client to work correctly.
Lastly I noticed a typo, in your code one line before last you have )); which should read )));.
Koda
The Problem is that SOAP needs a valid SSL-Certificate.
For an testing-server it's sometimes not worth the effort, so maybe this link help you to use a little workarround, to got your SOAP-Request working without need to create a fully-validated SSL-Certificat:
http://automationrhapsody.com/send-soap-request-over-https-without-valid-certificates/
Problem is not your certificate as client, but server certificate itself (try to load https://webservices-test.ede.de:9443/ibis/ws/WS_EXT_ELC?wsdl in a browser), that is invalid. You can ignore it perfectly, as server certificate it's mainly to avoid phishing, and I understand that url it's really the one you're attempting to reach. In command line curl, this is realized with the -k option. In php, SoapClient exactly, you can use this (exactly your problem, check third answer, and see what says about PHP7)
NOTE: You are loading wsdl, the definition file of the service, at each construction of SoapClient. If you store $soapclient as a static variable, you can use it's methods all the time without the need of recreate the client object (and so, avoiding to reload and reinterpret the wsdl file, that can delay perfectly from 1 to 5 seconds) all the time.
Simple question. But cannot get it to work.
I created an IAM Role for EC2 with full access to CloudWatch.
I launched a new EC2 instance with this IAM Role attached.
I wrote a simple PHP application on this EC2 instance which tries to publish metrics to CloudWatch.
I am getting this error in nginx logs:
2017/08/23 11:44:06 [error] 32142#32142: *5 FastCGI sent in stderr:
"PHP message: PHP Fatal error:
Uncaught Aws\Exception\CredentialsException:
Cannot read credentials from /var/www/.aws/credentials
in /var/www/app/vendor/aws/aws-sdk-php/src/Credentials/CredentialProvider.php:394
From that same EC2 instance, the command:
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-attached-to-ec2-instance>
returns 200 OK with the Access Key and Secret in the response.
This is my PHP code that tries to write CloudWatch metrics:
<?php
require 'vendor/autoload.php';
use Aws\CloudWatch\CloudWatchClient;
use Aws\Exception\AwsException;
$count = $_GET["count"];
publishMetric($count);
function publishMetric($count) {
$client = new CloudWatchClient([
'profile' => 'default',
'region' => 'us-east-1',
'version' => '2010-08-01'
]);
try {
$result = $client->putMetricData(array(
'Namespace' => 'com.mynamespace',
'MetricData' => array(
array(
'MetricName' => 'Count',
//Timestamp : mixed type: string (date format)|int (unix timestamp)|\DateTime
'Timestamp' => time(),
'Value' => $count,
'Unit' => 'Number'
)
)
));
var_dump($result);
echo 'Done publishing metrics';
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
echo 'Failure to publish metrics';
}
}
?>
Any idea what is missing in this setup?
I know this is late. I had the same issue and resolved it by removing profile => default line while initializing the client. If you do not provide credentials and profile, SDK will try to retrieve instance profile creds from metadata server.
Authentication of EC2 instance while accessing other AWS Services can be done in multiple ways:
Assigning a role to EC2 instance. Used when u have to give some "EC2 instance" a permission.
Do not assign a role; but use access-key which has all required permissions. Used when you give permission to a "User"
Both these are independent authentication mechanism. If you have already assigned role to your server; you do not have to write any code in your application (CredentialProvider.php) to authenticate.
Your current code can also be worked by creating a file /var/www/.aws/credentials which will look something like this:
accessKey=AKIAIB6FA52IMGLREIIB
secretKey=NQjJWKT+WZOUOrQ2Pr/WcRey3PnQFaGMJ8nRoaVU
I'm using the PHP library of the BigCommerce API. I am seeming to have trouble and keep getting error messages. I am not sure if this is an authorization issue or if I'm missing something.
I'm using XAMPP and install composer along with the BigCommerce PHP package I need. I followed this guide: https://github.com/bigcommerce/bigcommerce-api-php
So here's what my code looks like (credentials X'd out):
<?php
require "vendor/autoload.php";
use Bigcommerce\Api\Client as Bigcommerce;
Bigcommerce::configure(array(
'store_url' => 'http://store-XXXXXXXX.mybigcommerce.com',
'username' => 'admin',
'api_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxx'
));
$ping = Bigcommerce::getTime();
if (!$ping ) {
$error = Bigcommerce::getLastError();
print_r($error);
}
?>
This returns: Array ( [0] => stdClass Object ( [status] => 400 [message] => The connection is not secure. API requests must be made via HTTPS. ) )
I was wondering if it had to do with the "store_url" I used in the configuring. So I changed it to the front-end URL (real name of my store), and upon doing so I get this message instead:
Fatal error: Uncaught exception 'Bigcommerce\Api\NetworkError' with message 'SSL certificate problem: self signed certificate in certificate chain' in C:\xampp\htdocs\test\PSC_BigC\bigcommerce-api-php-master\src\vendor\bigcommerce\api\src\Bigcommerce\Api\Connection.php:274 Stack trace: #0 C:\xampp\htdocs\test\PSC_BigC\bigcommerce-api-php-master\src\vendor\bigcommerce\api\src\Bigcommerce\Api\Connection.php(368): Bigcommerce\Api\Connection->handleResponse() #1 C:\xampp\htdocs\test\PSC_BigC\bigcommerce-api-php-master\src\vendor\bigcommerce\api\src\Bigcommerce\Api\Client.php(423): Bigcommerce\Api\Connection->get('https://psc-dev...') #2 C:\xampp\htdocs\test\PSC_BigC\bigcommerce-api-php-master\src\test.php(19): Bigcommerce\Api\Client::getTime() #3 {main} thrown in C:\xampp\htdocs\test\PSC_BigC\bigcommerce-api-php-master\src\vendor\bigcommerce\api\src\Bigcommerce\Api\Connection.php on line 274
Its because youre using a self signed certificate.
you need to configure Bigcommerce to ignore the warning.
Bigcommerce::verifyPeer(false);
this effectively turns checking off in the cURL client it seems to be using.
The error states : "API requests must be made via HTTPS."
Change your store URL to "https://store-XXXXXXXX.mybigcommerce.com" as it is secure.
Example from the docs (store URL needs to be HTTPS).
https://github.com/bigcommerce/bigcommerce-api-php
Bigcommerce::configure(array(
'store_url' => 'https://store.mybigcommerce.com',
'username' => 'admin',
'api_key' => 'd81aada4xc34xx3e18f0xxxx7f36ca'
));
I have just uploaded my Symfony (2.7) project online and I have a 500 error happening only online in prod environnement (app.php). I have set $kernel = new AppKernel('prod', true); in app.php file in order to see the error message:
Error: Cannot use object of type Symfony\Component\HttpFoundation\Request as array
in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/EventListener/RouterListener.php at line 143
}
if (null !== $this->logger) {
// Below is line 143
$this->logger->info(sprintf('Matched route "%s".', isset($parameters['_route']) ? $parameters['_route'] : 'n/a'), array(
'route_parameters' => $parameters,
'request_uri' => $request->getUri(),
));
(This file is part of Symfony, see complete code here.)
In local (WAMP), I have no issue using app.php or app_dev.php .
Online, app_dev.php is working well but when try to access http://mydomain.fr/web/, I have this error.
I am a bit lost here, if you need more information, just ask me which file or else I should copy in this question.
Just to see what happens I commented the logger line in RouterListener.php, I have another different error showing. I guess there's something wrong with my server's config or something like that... but I have no idea what I should look at.
Some controller code is trying to access values by keys on an object as if it were an Array;
<?php
$moo = (object) ['foo' => 'bar' ];
/* run-time error below: */
$moo['foo'];
This happens when you upgrade "the library" or API without updating client code. It happens also when client code (your code) confuses the order of parameters in function invocations.