Retrieving ID of newly provisioned EC2 instance - php

I am trying to speed up the time it takes me to launch instances from a specific AMI using this AWS blog post as a starting point, however I am not sure how to grab the ID of the newly acquired Instance I have spun up using V3 of the PHP API (opposed to V2 in the blog post) so I can retrieve further information about the Instance (using the ID I would have retrieved)
<?php
require 'C:\wamp\bin\php\php5.5.12\vendor\autoload.php';
use Aws\Ec2\Ec2Client;
$ec2Client = \Aws\Ec2\Ec2Client::factory(array(
'region' => 'eu-west-1',
'version' => 'latest'
));
//Default vars
$aws_key = 'aws-ireland';
$ami_id = 'ami-000000';
$min_count = '1';
$max_count = '1';
$instance_type = 't2.micro';
$instance_region = 'eu-west-1b';
$server_name = 'API Test Server';
$result = $ec2Client->runInstances(array (
//Creating the instance
'KeyName' => $aws_key,
'ImageId' => $ami_id,
'MinCount' => $min_count,
'MaxCount' => $max_count,
'InstanceType' => $instance_type,
'Placement' => array('AvailabilityZone' => $instance_region),
));
//Wait for server to be created
//Return the instance ID
Following the blog post any further from this results in errors as the method waitUntilInstanceRunning doesn't exist in V3 of the API. I believe I need to use a waiter, but I'm not sure how I would use this for my problem?

What about this:
$result = $aws->DescribeInstances();
$reservations = $result['Reservations'];
foreach ($reservations as $reservation) {
$instances = $reservation['Instances'];
foreach ($instances as $instance) {
$instanceName = '';
foreach ($instance['Tags'] as $tag) {
if ($tag['Key'] == 'Name') {
$instanceName = $tag['Value'];
}
}
echo 'Instance Name: ' . $instanceName . PHP_EOL;
echo '<br>';
echo '---> State: ' . $instance['State']['Name'] . PHP_EOL;
echo '<br>';
echo '---> Instance ID: ' . $instance['InstanceId'] . PHP_EOL;
echo '<br>';
echo '---> Image ID: ' . $instance['ImageId'] . PHP_EOL;
echo '<br>';
echo '---> Private Dns Name: ' . $instance['PrivateDnsName'] . PHP_EOL;
echo '<br>';
echo '---> Instance Type: ' . $instance['InstanceType'] . PHP_EOL;
echo '<br>';
echo '---> Security Group: ' . $instance['SecurityGroups'][0]['GroupName'] . PHP_EOL;
echo '<br>';
echo '-----------------------------------------------------------------------------------------------------';
echo '<br>';
echo '<br>';
}
}

Related

Running PHP API call without Page Reloading

I have a multistep form (HTML / JS / PHP) and the form data gets sent to a backend after submitting, which results in a page reload.
Is it possible to pass the data live to the backend when the user gets to a new page of the form (clicks on the next button)?
<?php
require_once dirname(__FILE__) . '/MailWizzApi/Autoloader.php';
MailWizzApi_Autoloader::register();
// configuration object
$config = new MailWizzApi_Config(array(
'apiUrl' => 'http://email.mddasd.de/api/index.php',
'publicKey' => 'SAMPLEKEY',
'privateKey' => 'SAMPLEKEY',
// components
'components' => array(
'cache' => array(
'class' => 'MailWizzApi_Cache_File',
'filesPath' => dirname(__FILE__) . '/MailWizzApi/Cache/data/cache', // make sure it is writable by webserver
)
),
));
// now inject the configuration and we are ready to make api calls
MailWizzApi_Base::setConfig($config);
// start UTC
date_default_timezone_set('UTC');
$email = $_POST ['email'];
$name = $_POST['name'];
$phone = $_POST['telephone'];
if (isset($_POST['branch_0_answers']) && $_POST['branch_0_answers'] != "")
{
foreach($_POST['branch_0_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$grundflaeche .= $_POST['grundflaeche-grundstueck'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_1_answers']) && $_POST['branch_1_answers'] != "")
{
foreach($_POST['branch_1_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$wohnflaeche .= $_POST['wohnflaeche-haus'] . "\n";
$grundflaeche .= $_POST['grundflaeche-haus'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_2_answers']) && $_POST['branch_2_answers'] != "")
{
foreach($_POST['branch_2_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$wohnflaeche .= $_POST['wohnflaeche-wohnung'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
if (isset($_POST['branch_3_answers']) && $_POST['branch_3_answers'] != "")
{
foreach($_POST['branch_3_answers'] as $value)
{
$art.= trim(stripslashes($value)) . "\n";
};
$gewerbeflaeche .= $_POST['gewerbeflaeche'] . "\n";
$grundflaeche .= $_POST['grundflaeche-gewerbe'] . "\n";
$baujahr .= $_POST['baujahr'] . "\n";
$plz .= $_POST['plz'] . "\n";
}
foreach($_POST['branch_1_1_answers'] as $value)
{
$stand.= trim(stripslashes($value)) . "\n";
};
$endpoint = new MailWizzApi_Endpoint_ListSubscribers();
$response = $endpoint->create('ma503j6m97b75', array(
'EMAIL' => $email,
'TELEFON' => $phone,
'NAME' => $name,
'ART' => $art,
'GEWERBEFLAECHE' => $gewerbeflaeche,
'WOHNFLAECHE' => $wohnflaeche,
'GRUNDFLAECHE' => $grundflaeche,
'BAUJAHR' => $baujahr,
'PLZ' => $plz,
'STAND' => $stand
));
?>
The .php gets executed with the final submit button.
Thanks for your answers.

Php Elastica - how to resolve - No enabled connection error - in long cycle

I have a php console script which processes long array in foreach cycle and send Elasticsearch bulks to database. I need to solve case if bulk insert fails on connection error like: No enabled connection. I would like to catch it and try it again. But my solution does not work. Still no enabled connection error. Here is the code:
/** #var Elastica\Client $elastic */
$elastic = new Elastica\Client(['servers' => [['host' => 'xxx.xxx.x.xx', 'port' => 9200]]]);
/** #var \Elastica\Index $searchCz */
$searchCz = $elastic->getIndex('search_cz');
$bulkLimit = 500;
$scrollIcos = [About 2mil items...];
$continue = TRUE;
while ( $continue && $bulkIcos = array_splice( $scrollIcos, 0, $bulkLimit ) )
{
try
{
$elasticBulk = [];
$icos = array_values($bulkIcos);
foreach ($bulkIcos as $ico) // Numeric key does not work with array_splice()
{
$offset++;
$companyData = [];
$companyData['ico'] = $ico;
$companyData['xxx'] = 'yyy';
...
$elasticBulk[] = new \Elastica\Document((string)$ico, $companyData);
}
if( $elasticBulk )
{
echo 'Bulk send start ' . PHP_EOL;
$searchCz->getType('doc')->addDocuments($elasticBulk);
echo '----- offset ' . $offset . ' OK' . PHP_EOL;
}
}
catch( \Exception $e )
{
echo '------------------------' . PHP_EOL;
echo 'Error while bulk insert. ' . $e->getMessage() . PHP_EOL . PHP_EOL;
setIcosBackToScrollIcos($bulkIcos, $scrollIcos);
sleep(30);
}
}

Hashes not similar between PHP and Paw REST Client

I'm building a HMAC API and I have issues testing the hashing with Paw.
On Paw I have this payload:
GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
and a custom HMAC-SHA256 variable (actually function like this that sets it in the X-Hash header.
X-Hash: 4Cq2yehWumDcUk1dYyfhm6qWjJVBkOCB8o12f5l0WGE=
In my PHP API I have the same thing:
GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
and used:
hash_hmac('sha256', $this->getPayload(), '9a6e30f2016370b6f2dcfb6880501d7f2305d69bout', false);
So when comparing the hashes:
Paw: 4Cq2yehWumDcUk1dYyfhm6qWjJVBkOCB8o12f5l0WGE=
PHP: 6961b9d1f6e986c49d963cbebd691fa68dfa59b4ce3b7f05320c2d43eae3c7c3
They are very different. Any idea why is that?
Update
Paw Code:
function evaluate(context){
var loc = getLocation(context.getCurrentRequest().url);
var payload = "";
payload += context.getCurrentRequest().method + ':';
payload += loc.pathname + ':';
payload += JSON.stringify(context.getCurrentRequest().body) + ':';
payload += "9a6e30f2016370b6f2dcfb6880501d7f2305d69bout"; // Private key
return payload;
};
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
PHP Code (with lots of comments):
if (strpos(strtoupper($authHeader), 'HMAC') !== 0) {
echo 'out';
throw new HttpForbiddenException();
}
else {
$hmacSignature = $app->request->headers()->get('X-Hash');
$publicKey = $app->request->headers()->get('X-Public');
if ( empty($hmacSignature) || empty($publicKey) ) {
echo 'out2';
throw new HttpForbiddenException();
}
else {
$this->hmacManager->setPublicKey($publicKey);
print '$publickey = ' . $publicKey . '<br>';
// Validate if base64_encoded or not
if( base64_decode($hmacSignature, true) !== FALSE ) {
$binaryString = base64_decode($hmacSignature);
$hmacSignature = bin2hex($binaryString);
print 'decoding ' . '<br>';
}
$this->hmacManager->setHmacSignature($hmacSignature);
print '$hmacSignature = ' . $hmacSignature . '<br>';
$this->hmacManager->setRequestMethod($app->request->getMethod());
print 'method = ' . $app->request->getMethod() . '<br>';
$this->hmacManager->setRequestResourceUri($app->request->getResourceUri());
print 'uri = ' . $app->request->getResourceUri() . '<br>';
$requestBody = $app->request()->getBody();
if (Utils::isJson($requestBody)) {
$requestBody = json_decode($requestBody);
}
$this->hmacManager->setRequestBody(json_encode($requestBody));
print 'body = ' . json_encode($requestBody) . '<br>';
print 'private key = ' . $this->hmacManager->getPrivateKey() . '<br>';
$payload = '';
$payload .= $this->hmacManager->getRequestMethod() . ":";
$payload .= $this->hmacManager->getRequestResourceUri() . ":";
$payload .= $this->hmacManager->getRequestBody() . ":";
$payload .= $this->hmacManager->getPrivateKey();
print 'PHP payload [' . $payload . ']';
$this->hmacManager->setPayload($payload);
$hmacValue = $this->hmacManager->generateHmac();
$isValid = $this->hmacManager->isValid($this->hmacManager->generateHmac(), $hmacSignature);
if ($isValid !== true) {
echo 'out3';
throw new HttpForbiddenException();
}
}
}
generateHmac from another class:
public function generateHmac()
{
print 'Generating HMAC' . '<br>';
$algorithm = $this->getAlgorithm();
print 'algo ' . $algorithm . '<br>';
$privateKey = $this->getPrivateKey();
print 'privk ' . $privateKey . '<br>';
if (empty($algorithm)) {
throw new \RuntimeException('Algorithm must be set and not empty');
} elseif (empty($privateKey)) {
throw new \RuntimeException('Private key must be set and not empty');
}
print 'payload ' . $this->getPayload() . '<br>';
$hash = hash_hmac($this->getAlgorithm(), $this->getPayload(), $this->getPrivateKey(), false);
print 'php hasj: ' . $hash . '<br>';
return $hash;
}
Finally, here's the output statements:
$publickey = 95f97b93560f951b4cae46c86d03d9b1a81d4ae8
decoding
$hmacSignature = e02ab6c9e856ba60dc524d5d6327e19baa968c954190e081f28d767f99745861
method = GET
uri = /hello/world
body = ""
private key = 9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
PHP payload [GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout]
Generating HMAC
algo sha256
privk 9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
payload GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
php hash: 6961b9d1f6e986c49d963cbebd691fa68dfa59b4ce3b7f05320c2d43eae3c7c3
Hope it helps!
The paw hash is base64 encoded while the PHP one is in hexadecimal. So decode the paw hash first:
$binary = base64_decode($pawHash);
$hex = bin2hex($binary);
And then compare this to your own hash.
We've just added new Base 64 to Hex conversion dynamic values, this should solve your problem.
Wrap your HMAC signature dynamic value inside the new Base 64 to Hex one, and you'll get a valid hexadecimal signature:
You can install this new dynamic value here: Base 64 to Hex Dynamic Value

how to make array 3 dimension with php?

help me please,, syntax eror
$Prodi = array("Ilmu Hukum" => array("Angkatan 2010" => array("Siswono","Hariono","Madun"),
"Teknik Informatika" => array("Angkatan 2010" => array("Atep","Ferdinan","I Made"),
"Akutansi" => array("Angkatan 2010" => array("Ridwan","Firman","Zulkifli")))));
while(list($key1) = each($Prodi)) {
echo "$key1 : <br>";
}
while(list($key2,$val) = each($Prodi["$key1"])){
echo "-$val<br>";
}
While(list($key3,$val) = each($Prodi["$key2"])){
echo "-$val<br>";
}
You may use the following code.
foreach($Prodi as $a1key => $a1val) {
echo $a1key . '===' . json_encode($a1val) . '<br />';
foreach($a1val as $a2key => $a2val) {
echo $a2key . '===' . json_encode($a2val) . '<br />';
foreach($a2val as $a3key => $a3val) {
echo $a3key . '===' . json_encode($a3val) . '<br />';
}
}
}

eBay API SKU missing from response

I am trying to download all my listings from ebay into my database using following code:
$client = new eBaySOAP($session);
$ebay_items_array = array();
try {
$client = new eBaySOAP($session);
$params = array(
'Version' => $Version,
'GranularityLevel' => "Fine",
'OutputSelector' => "ItemID,SKU,Title",
'EndTimeFrom' => date("c", mktime(date("H"), date("i")+10, date("s"), date("n"), date("j"), date("Y"))),
'EndTimeTo' => date("c", mktime(date("H"), date("i"), date("s"), date("n"), date("j")+120, date("Y"))),
'Pagination' => array(
'PageNumber' => $_GET['linkebaynum'],
'EntriesPerPage' => "20"
)
);
$results = $client->GetSellerList($params);
if($results->Ack == "Success")
{
$c = 0;
if(is_array($results->ItemArray->Item))
{
foreach($results->ItemArray->Item as $key => $value)
{
array_push($ebay_items_array, $value->ItemID);
$Qcheck = tep_db_query('select ebay_productstoitems_items_id from ' . TABLE_EBAY_PRODUCTS_TO_ITEMS . ' where ebay_productstoitems_items_id = ' . $value->ItemID);
$check = tep_db_fetch_array($Qcheck);
if($check == 0) {
if($check['ebay_productstoitems_items_id'] = $value->ItemID) {
echo 'Not in Database - Inserting ' . $value->ItemID . '<br>';
tep_db_query("insert ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}else{
echo 'Found - ' . $value->ItemID . ' Nothing to Change<br>';
tep_db_query("update ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "' where ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}
$c++;
}
}
} catch (SOAPFault $f) {
print "error<br>";
}
print "Request:<br>".ebay_formatxmlstring($client->__getLastRequest())."<br><br>";
print "Response:<br>".ebay_formatxmlstring($client->__getLastResponse())."<br><br>";
But it will not recover the SKU (or CustomLabel).
Can anyone explain what I am missing to get the SKU into the database along with the ItemID.
Or would I have to recover lists of ItemID and then do a second call to recover the SKU or CustomLabel?
Found out what the problem was the Sandbox does not appear to pass the SKU back. I switched to the live site and hey presto the SKU is being retrieved along with the Itemid.

Categories