I have a really weird problem, I am doing a script that executes a symfony command.
Here it is :
<?php
$checkname = 'symfony_checker';
$sensu_ip = '192.168.13.000';
$port = 3002;
function write_to_sensu($json)
{
echo('writing');
try
{
$fp = fsockopen($sensu_ip, $port, $errno, $errstr, 10);
if ($fp)
{
fwrite($fp, $json);
fclose($fp);
}
}
catch (Exception $E)
{
}
}
ini_set('max_execution_time', 0);
require_once dirname(__DIR__).'/app/bootstrap.php.cache';
require_once dirname(__DIR__).'/app/AppKernel.php';
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
$input = new ArrayInput(array(
'command' => 'security:check',
'--format' => 'json',
));
$output = new BufferedOutput();
$kernel = new AppKernel('dev', true);
$application = new Application($kernel);
$application->setAutoExit(false);
$application->run($input, $output);
$payload = array(
'name' => $checkname,
"status" => 0
);
$payload = json_encode($payload);
$arr = json_decode($output->fetch());
$vulnerabilites = array();
foreach ($arr as $key => $errors)
{
$var = 0;
foreach ($errors as $error)
{
if ($var == 1)
{
foreach ($error as $key => $one)
array_push($vulnerabilites, $key);
}
$var++;
}
}
$vulnerabilites = implode(' ', $vulnerabilites);
$payload['output'] = 'Vulnerabilities found : ' . $vulnerabilites;
dump($vulnerabilites);
write_to_sensu($payload);
Problem is that the program leave at the line :
$payload['output'] = 'Vulnerabilities found : ' . $vulnerabilites;
If I comment this line the code continue fine and goes to my function write to sensu.
If I just update $payload['output'] with a random string it doesn't work either.
Every time I try to update payload, the program quit! Anywhere in the code.
Have any idea why ?
You are converting $payload into a string with the line
$payload = json_encode($payload);
so you cannot use it as an array anymore. Either assign the result of json_encode() to another variable, or update your array before the conversion.
You've already encoded your array to JSON before you attempt to add the vulnerabilities. So you're treating a string as an associative array.
You just need to move your line
$payload = json_encode($payload);
to after this line:
$payload['output'] = 'Vulnerabilities found : ' . $vulnerabilites;
Related
I am trying to get tracking information from amazon using provided url
https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302
I am getting response using file_get_contents() function in php,
what I want is to show only that part of the response which contains the tracking information as an output of my php script and eliminate/hide all the unnecessary content from file_get_contents() response.
One way to do what you're looking for is use DomDocument to filter out the json data in the source ($file) and then use a recursive function to get the elements you need.
You can set the elements you need using an array, $filter. In this example we've taken a sample of some of the available data, i.e. :
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
The code
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$trackingData = []; // store for order tracking data
$html = new DOMDocument();
#$html->loadHTML($file);
foreach ($html->getElementsByTagName('script') as $a) {
$data = $a->textContent;
if (stripos($data, 'shortStatus') !== false) {
$trackingData = json_decode($data, true);
break;
}
}
// set the items we need
$filter = [
'orderId', 'shortStatus', 'promiseMessage',
'lastTransitionPercentComplete', 'lastReachedMilestone', 'shipmentId',
];
// invoke recursive function to pick up the data items specified in $filter
$result = getTrackingData($filter, $trackingData);
echo '<pre>';
print_r($result);
echo '</pre>';
function getTrackingData(array $filter, array $data, array &$result = []) {
foreach($data as $key => $value) {
if(is_array($value)) {
getTrackingData($filter, $value, $result);
} else {
foreach($filter as $item) {
if($item === $key) {
$result[$key] = $value;
}
}
}
}
return $result;
}
Output:
Array
(
[orderId] => 203-2171364-3066749
[shortStatus] => IN_TRANSIT
[promiseMessage] => Arriving tomorrow by 9 PM
[lastTransitionPercentComplete] => 92
[lastReachedMilestone] => SHIPPED
[shipmentId] => 23796758607302
)
Try this
<?php
$filename = 'https://www.amazon.co.uk/progress-tracker/package/ref=pe_3187911_189395841_TE_typ?_encoding=UTF8&from=gp&itemId=&orderId=203-2171364-3066749&packageIndex=0&shipmentId=23796758607302';
$file = file_get_contents($filename);
$html = new DOMDocument();
#$html->loadHTML($file);
foreach($html->getElementsByTagName('span') as $a) {
$property=$a->getAttribute('id');
if (strpos($property , "primaryStatus"))
print_r($property);
}
?>
It should show "Arriving tomorrow by 9 PM" status.
I have a PHP file that grabs a .txt file and decodes the JSON to push the user's e-mail and name entry to my campaign monitor database. The JSON is wonky because new entries are added with a ][ as seen in this example:
[{"email":"drake.scott#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]
The problem I am having right now is uploading the entries to my database. I have managed to strip the ][ and doing a var_dump($content); shows a valid JSON string. However, doing var_dump($user) gives me 0 array(0) { }.
The entries will not upload to my database because there is essentially nothing in my array. Can anyone give me some insight on how to proceed?
<?php
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$content = str_replace('}][{', '},{', $content);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
}
else {
echo "failed";
var_dump($result->response);
var_dump($user);
}
?>
There are multiple JSON objects concatenated in the file. The easiest way to make the JSON valid is to create an array:
$content = str_replace('][', ',', $content);
$users = json_decode($content, true);
Then you have a multi-dimensional array with multiple users that you will need to decide what you want from it:
print_r($users);
foreach($users as $user) {
echo $user['email'] . "\n";
}
I am using parse_ini_file to parse an ini file using PHP.
Now I first upload an INI file to my server then open it and allow user to mak custom changes to the file.
Now once users has edited the file i get the data from post and save the file back to server. But Now i dont get my sections. INIdetails,Dialplan in the updated file so when i also want to write that to file how to do that?
This is the code :
$this->data['parameters'] = parse_ini_file($path.$filename,true);
/*Getting Our POST DATA from View*/
$data = array(
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'Param_1' => $this->input->post('Param_1'),
'Param_2' => $this->input->post('Param_2')
);
/*Creating New file with the name of customer loggedin*/
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
$custom_file = fopen('uploads/'.$name.'_'.$ext.'.ini', 'w');
fwrite($custom_file, "[INIDetails]\n");
foreach ($data as $key => $value)
{
fwrite($custom_file, " $key = $value\n");
}
fclose($custom_file);
/*Setting path to New CUSTOM file with customer name as prefix*/
$file = $path.$custom_file;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Creates ini file, dumps array to string and creates .INI file*/
write_php_ini($data,$file);
The culprit from your previous code is that your array is not formatted correctly, it should be array of arrays to achieve what you want.
Try below code:
// First read the ini file that the user was editing
// Your idea to read the existing ini file is good, since it will generate you the structured array
$previous_data = parse_ini_file($path . $filename, true);
// Overwrite/edit the previous_data using user's post data
$previous_data['INIDetails']['SipUserName'] = $this->input->post('SipUserName');
$previous_data['INIDetails']['Password'] = $this->input->post('Password');
$previous_data['INIDetails']['Domain'] = $this->input->post('Domain');
$previous_data['INIDetails']['Proxy'] = $this->input->post('Proxy');
$previous_data['INIDetails']['Port'] = $this->input->post('Port');
$previous_data['INIDetails']['SipAuthName'] = $this->input->post('SipAuthName');
$previous_data['INIDetails']['DisplayName'] = $this->input->post('DisplayName');
$previous_data['INIDetails']['ServerMode'] = $this->input->post('ServerMode');
$previous_data['INIDetails']['UCServer'] = $this->input->post('UCServer');
$previous_data['INIDetails']['UCUserName'] = $this->input->post('UCUserName');
$previous_data['INIDetails']['UCPassword'] = $this->input->post('UCPassword');
$previous_data['DialPlan']['DP_Exception'] = $this->input->post('DP_Exception');
$previous_data['DialPlan']['DP_Rule1'] = $this->input->post('DP_Rule1');
$previous_data['DialPlan']['DP_Rule2'] = $this->input->post('DP_Rule2');
$previous_data['DialPlan']['OperationMode'] = $this->input->post('OperationMode');
$previous_data['DialPlan']['MutePkey'] = $this->input->post('MutePkey');
$previous_data['DialPlan']['Codec'] = $this->input->post('Codec');
$previous_data['DialPlan']['PTime'] = $this->input->post('PTime');
$previous_data['DialPlan']['AudioMode'] = $this->input->post('AudioMode');
$previous_data['DialPlan']['SoftwareAEC'] = $this->input->post('SoftwareAEC');
$previous_data['DialPlan']['EchoTailLength'] = $this->input->post('EchoTailLength');
$previous_data['DialPlan']['PlaybackBuffer'] = $this->input->post('PlaybackBuffer');
$previous_data['DialPlan']['CaptureBuffer'] = $this->input->post('CaptureBuffer');
$previous_data['DialPlan']['JBPrefetchDelay'] = $this->input->post('JBPrefetchDelay');
$previous_data['DialPlan']['JBMaxDelay'] = $this->input->post('JBMaxDelay');
$previous_data['DialPlan']['SipToS'] = $this->input->post('SipToS');
$previous_data['DialPlan']['RTPToS'] = $this->input->post('RTPToS');
$previous_data['DialPlan']['LogLevel'] = $this->input->post('LogLevel');
// Set Name of New file with the name of customer logged in
$name = $this->session->userdata('username');
$ext = $this->session->userdata('extension');
$custom_file = "$name_$ext.ini";
$new_filename = $path . $custom_file;
// Write the INI file
write_php_ini($data, $new_filename);
function write_php_ini($array, $new_filename)
{
$res = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
$res[] = "[$key]";
foreach ($val as $skey => $sval) {
$res[] = "$skey = " . (is_numeric($sval) ? $sval : '"' . $sval . '"');
}
} else {
$res[] = "$key = " . (is_numeric($val) ? $val : '"' . $val . '"');
}
}
safefilerewrite($new_filename, implode("\r\n", $res));
}
function safefilerewrite($new_filename, $dataToSave)
{
if ($fp = fopen($new_filename, 'w')) {
$startTime = microtime(true);
do {
$canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if (!$canWrite) {
usleep(round(rand(0, 100) * 1000));
}
} while ((!$canWrite) and ((microtime(true) - $startTime) < 5));
//file was locked so now we can store information
if ($canWrite) {
fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
From your previous code, there are bunch of inappropriate codes which I remove. Also, too many inconsistencies like Method naming, variable naming etc.
If your function was named Camel cased then through out your code it must be named as camel-cased. If your variables are with underscore, then through out your code, they must have underscore for two or more worded variable.
I didn't edit the naming convention of your code so you won't be confused but i suggest to have a consistent naming convention through out your project.
UPDATED:
based on your answer, it seems like you changed your whole code. I would like to provide another way using nested foreach and passing by reference that save couple of lines:
$this->data['params'] = $this->parameter_m->get();
$this->data['parameters'] = parse_ini_file($path . $filename, true);
foreach ($this->data['parameters'] as $key_header => &$value_header) {
foreach ($value_header as $key_item => &$value_item) {
$value_item = $this->input->post($key_item);
}
}
$this->load->helper('file');
$this->load->library('ini');
$file = $path . $filename;
$ini = new INI($file);
$ini->read($file);
$ini->write($file, $this->data['parameters']);
Finally i got an answer:
I will loop through what i get from POST and will get each array's key. And then i will give the resultant to my Write Method
$this->data['params'] = $this->parameter_m->get();
/*Getting the parameters to display on view*/
$this->data['parameters'] = parse_ini_file($path.$filename,true);
while (current($this->data['parameters']) )
{
$param_set = current($this->data['parameters']);
$param_type = key($this->data['parameters']);
foreach ($param_set as $key =>$value)
{
$this->data['parameters'][$param_type][$key] = $this->input->post($key);
}
next($this->data['parameters']);
}
$this->load->helper('file');
$this->load->library('ini');
$file = $path.$filename;
$ini = new INI($file);
$ini->read($file);
$ini->write($file, $this->data['parameters']);
I am trying to read a csv file line by line and save its content in an array. I then parse the array using foreach to print each line.
However, when i try to send the variable(which according to me should be a string) to the deleteInstance method it prints as an array and not plain string.
I have issue sending this to Softlayer API since it throw me an error saying string expected but array given ? I am not sure what is wrong
a.csv
7381838
7381840
7381842
php
<?PHP
require_once dirname(__FILE__) . '/SoftLayer/SoapClient.class.php';
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
// Set path to CSV file
$csvFile = 'a.csv';
$csv = readCSV($csvFile);
foreach ($csv as $value) {
var_dump($value);
print_r($value);
deleteInstance($value);
}
function deleteInstance($ccid){
$apiUsername = 'xxxxx';
$apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$cancelRightNow = true; //or false if you want to wait till the billing cycle ends
$cloudComputingInstanceId = $ccid;
print_r($cloudComputingInstanceId);
var_dump($cloudComputingInstanceId);
$client = SoftLayer_SoapClient::getClient('SoftLayer_Virtual_Guest', $cloudComputingInstanceId, $apiUsername, $apiKey);
$objectMask = new SoftLayer_ObjectMask();
$objectMask->billingItem;
$client->setObjectMask($objectMask);
$cci = $client->getObject();
$client = SoftLayer_SoapClient::getClient('SoftLayer_Billing_Item', $cci->billingItem->id, $apiUsername, $apiKey);
$billingItem = $client->getObject();
if ($billingItem != null) {
if ($cancelRightNow) {
$client->cancelService();
} else {
$client->cancelServiceOnAnniversaryDate();
}
}
}
?>
The problem is your argument to deleteInstance is an array... It looks like this:
$csv = Array(
0 => Array(0 => '7381838'),
1 => Array (0 => '7381840'),
2 => Array(0 => '7381842')
)
This is because you are parsing it as CSV which splits each line into an array based on a delimiter. This is not what you want. Instead use file to read each line into an array:
function readCSV($csvFile){
return file($csvFile);
}
$csv = readCSV('a.csv');
foreach ($csv as $value) {
// your value is now the line of the file like '7381838'
deleteInstance($value);
}
Try this and see what happens
foreach ($csv as $value) {
$svalue = $value[0];
var_dump($svalue);
print_r($svalue);
deleteInstance($svalue);
}
I have created this test script to get data from the twitter usertimeline which I'm sure was previously working however now it returns nothing. Is there something I am missing here? (To test simply amend the constants at the top)
define('CONSUMER_KEY', '');
define('CONSUMER_SECRET', '');
define('OAUTH_TOKEN','');
define('OAUTH_SECRET','');
define('USER_ID','');
function generateSignature($oauth,$fullurl,$http_method){
// Take params from url
$main_url = explode('?',$fullurl);
$urls = explode('&',$main_url[1]);
foreach ($urls as $param){
$bits = explode('=',$param);
if (strlen($bits[0])){
$oauth[$bits[0]] = rawurlencode($bits[1]);
}
}
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.urlencode($main_url[0]).'&'.urlencode(urldecode($string));
$sign_str = CONSUMER_SECRET.'&'.OAUTH_SECRET;
return urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_str,true)));
}
function random($len,$use_chars = false,$numU = false){
$num = range(0,9);
$letu = range('A','Z');
$letl = range('a','z');
$chars = array("!","*","£","$","^","(",")","_","+");
if ($use_chars){
$arr = array_merge($num,$letu,$letl,$chars);
} else {
$arr = array_merge($num,$letu,$letl);
}
// Shuffling - new addition 11/9 to make order actually random!
shuffle($arr);
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
return implode('',$out);
}
$method = 'GET';
// Twitter still uses Oauth1 (which is a pain)
$oauth = array(
'oauth_consumer_key'=>CONSUMER_KEY,
'oauth_nonce'=>random(32),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>OAUTH_TOKEN,
'oauth_version'=>'1.0',
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=".USER_ID;
$oauth['oauth_signature'] = generateSignature($oauth,$url,$method,'');
ksort($oauth);
foreach ($oauth as $k=>$v){
$auths[] = $k.'="'.$v.'"';
}
$stream = array('http' =>
array(
'method' => $method,
// ignore_errors should be true
'ignore_errors'=>true, // http://php.net/manual/en/context.http.php - otherwise browser returns error not error content
'follow_location'=>false,
'max_redirects'=>0,
'header'=> array(
'Authorization: OAuth '.implode(', ',$auths),
'Connection: close'
)
)
);
echo $url;
$response = file_get_contents($url, false, stream_context_create($stream));
print'<pre>';print_r($stream);print'</pre>';
print'<pre>[';print_r($reponse);print']</pre>';
I found this:
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
I am not completly sure, but i think there shouldn't be a } after if ($numU){ $arr = $num;
I think it should be a open bracket. {
I found one more thing:
print'<pre>[';print_r($reponse);print']</pre>';
Here at the bottom of the code, you wrote "$reponse" instead of "$response"
I hope it helped! If it did, give it a upvote and choose as best answer!