PHP preg_match_all/preg_match - php

I am trying to create a report function for our firewall.
The firewall rules are stored in json format.
Here is a sample of the string.
[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]
And the preg_match_all filter i have:
preg_match_all('/\"description":"(.*?)\","matchers"/',$str,$description);
preg_match_all('/\"id":(.*?)\,"/',$str,$id);
preg_match_all('/\"ruleId":(.*?)\,"/',$str,$rule_id);
preg_match_all('/\"enabled":(.*?)\,"description"/',$str,$enable);
preg_match_all('/\"block":(.*?)\,"/',$str,$block);
preg_match_all('/\"log":(.*?)\}/',$str,$log);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_ADDR"/',$str,$dest_add);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_PORT"/',$str,$dest_port);
preg_match_all('/\"value":"(.*?)\","matcherType":"DST_INTF"/',$str,$dest_int);
preg_match_all('/\"value":"(.*?)\,","matcherType":"SRC_ADDR"/',$str,$src_add);
preg_match_all('/\"value":"(.*?)\","matcherType":"SRC_INTF"/',$str,$src_int);
preg_match_all('/\"value":"(.*?)\","matcherType":"PROTOCOL"/',$str,$protocol);
preg_match_all('/\"value":"(.*?)\","matcherType":"DIRECTORY_CONNECTOR_USERNAME"/',$str,$user);
preg_match_all('/\"value":"(.*?)\","matcherType":"DIRECTORY_CONNECTOR_GROUP"/',$str,$group);
What happens is that the start for evry matcher is VALUE":" when i print $dest_port i get "1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80" instead of just 80.
Any one that have a preg_match_all to find the matchertype first and then read backwords to the "value":"?
Any help would be fantastic!

$xyz = <<<EOX
[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]
EOX;
var_dump(json_decode($xyz)); //execute other operations, iteration etc here
This works much better than regex. Returns structured data, you can iterate through.

Ended up using with json_decode.
sample:
$jsondata ='[{"id":1,"enabled":true,"description":"TEMP","matchers":{"javaClass":"java.util.LinkedList","list":[{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1.1.1.1","matcherType":"DST_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"80","matcherType":"DST_PORT"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,3,2","matcherType":"DST_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"2.2.2.2","matcherType":"SRC_ADDR"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"1,2,wan","matcherType":"SRC_INTF"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"UDP,TCP,any","matcherType":"PROTOCOL"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"svrbjgu","matcherType":"DIRECTORY_CONNECTOR_USERNAME"},{"invert":false,"javaClass":"com.untangle.node.firewall.FirewallRuleMatcher","value":"intern-it","matcherType":"DIRECTORY_CONNECTOR_GROUP"}]},"ruleId":5001,"javaClass":"com.untangle.node.firewall.FirewallRule","block":false,"log":true}]';
$data = json_decode($jsondata,true);
echo '<table><tr><th WIDTH="10">Nr.</th><th WIDTH="10">RuleID</th><th WIDTH="150">Description</th><th WIDTH="100">Protocol</th><th WIDTH="75">Src Int</th><th WIDTH="150">Src Address</th><th WIDTH="100">Src Port</th><th WIDTH="75">Dest. Int</th><th WIDTH="150">Dest Address</th><th WIDTH="100">Dest. Port</th><th WIDTH="50">Action</th><th WIDTH="50">Log</th><th WIDTH="50">Enabled</th></tr>';
echo "<tr><td>test.</td><td> {$data[0]['ruleId']} </td><td>{$data[0]['description']}</td><td>{$data[0]['enabled']}</td></tr>" ;

Related

Cannot Parse Paypal "notify_url" Data Into an Associative Array (PHP)

I am setting up a Paypal sandbox. Everything works fine. When the transaction is done, paypal POSTS some data to my "notify_url" page (which I've named process-payment.php).
Now, when I post:
$array = $_POST;
$encodedString = json_decode($array);
Now, I can PUT that encoded string in the database, and it looks like:
{"mc_gross":"10.00","protection_eligibility":"Eligible",
"address_status":"confirmed","payer_id"}
Now, my big question is, how can I get THAT (^^^) into an associative array, where I can store those values in a database that records the transaction? Thank you so much for your help in advance! I've already tried:
$pp_array = file_get_contents('php://input');
$arrayDump = json_encode($pp_array);
$pp_array = json_decode($pp_array, true);
Which, obviously, didn't work. So, kinda hoping someone can give me a little tutelage here!
You are trying to use json_decode on an bad array because your payer_id is NULL. Consider filling or removing it. This is a working example with a filled payer_id:
$json = '{"mc_gross":"10.00","protection_eligibility":"Eligible", "address_status":"confirmed","payer_id":"2"}';
$json_asoc = (json_decode($json, true));
print $json_asoc['mc_gross']; // 10
For details see here
So, turns out that the code I used to make it work was this:
$array = $_POST;
$arrayDump = json_encode($array);
file_put_contents('payment-record.txt', $arrayDump);
$fileContents = file_get_contents('payment-record.txt');
$pp_array = json_decode($fileContents, true);
That gave me a workable array. Not sure why I had to write it first, but there you go.

How can I sanitise the explode() function to extract only the marker I require?

I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012

How to use loop in comment section

I have used foreach loop to extract multiple value of user_phone between tab but it will produce error.I dont what is exact formate.
$result = $Admin->select($Admin->newsletter_subscribers,'',"");
print_r($result['user_phone']);
$data="<message-submit-request>
<username>#######</username>
<password>#######</password>
<sender-id>$$$$$$</sender-id>".
foreach($result as $row)
{
"<to>".$row['user_phone']."</to>"
}."<MType></MType>
<message-text>
<text>hi test message 1</text>
</message-text>
</message-submit-request>";
Try this:
$result = $Admin->select($Admin->newsletter_subscribers,'',"");
print_r($result['user_phone']);
$data = "<message-submit-request>
<username>#######</username>
<password>#######</password>
<sender-id>$$$$$$</sender-id>";
foreach($result as $row)
{
$data .= "<to>".$row['user_phone']."</to>";
}
$data .= "<MType></MType>
<message-text>
<text>hi test message 1</text>
</message-text>
</message-submit-request>";
The exact format for string concatenation is shown in the PHP manual under string operators. However I won't elaborate on these directly becasue cerating XML by concatenating strings is a bad idea. For example having characters like <, > and & in your input, you'll run into many problems.
For your use-case SimpleXMLElement is a handy object that allows you to do the same in a much more consisted manner:
// create XML document based on boilerplate
$xml = new SimpleXMLElement('
<message-submit-request>
<username>#######</username>
<password>#######</password>
<sender-id>$$$$$$</sender-id>
<MType></MType>
<message-text>
<text>hi test message 1</text>
</message-text>
</message-submit-request>
');
// add elements where appropriate
foreach($result as $row)
{
$xml->addChild('to', $row['user_phone']);
}
This will ensure that all values are properly encoded. Additionally this can have a magnitude on benefits when you further process the data, e.g. outputting it.
However you haven't shown in your question what follows up with $data so you need to know how to obtain the XML from the SimpleXMLElement as string to make the example complete. Here it is:
$data = $xml->asXML();
See as well the SimpleXML Basic Usage guide in the manual if you'd like to learn more.

json encode using php not able to get [] brackets

here is my code
<?
include '../dbConnect.php';
$amp=trim($_POST['amp']);
//$amp='AMP8';
//$sql=mysql_query("select tblRepairQueue.ackNo,tblRepairQueue.repairStatus,tblRepairQueue.savedAt from tblRepairQueue,AMPcustomers where AMPcustomers.phone1=tblRepairQueue.phoneNo and AMPcustomers.id='".$amp."'");
$sql=mysql_query("select phone1 from AMPcustomers where id='".$amp."'");
$response = array();
while($row=mysql_fetch_array($sql))
{
$sql_query=mysql_query("select ackNo,repairStatus,savedAt from tblRepairQueue where phoneNo='".$row['phone1']."'");
while($row1=mysql_fetch_array($sql_query)){
$ackNo=$row1['ackNo'];
$repairStatus=$row1['repairStatus'];
$savedAt=$row1['savedAt'];
$response[]=array('ackNo'=>$ackNo,'repairStatus'=>$repairStatus,'savedAt'=>$savedAt);
}}
print json_encode($response);
?>
output m getting as
{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
but i want the output to look like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
Can anyone plz help in finding the mistake or what has to be done to get square brackets at the end
This is a bit strange because I have this code:
<?php
$array = array();
$array[] = array("ackNo"=>"26101211236759","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 00:55:25");
$array[] = array("ackNo"=>"26101211236780","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 10:55:25");
echo json_encode($array);
?>
And I get this correct form:
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"26101211236780","repairStatus":"Closed and Complete","savedAt":"2012-10-26 10:55:25"}]
This code should indeed output [{...},...]. So we can't really tell you what went wrong on your side. check the structure of the $response variable before the conversion to Json to see what went wrong.
Note that the code allows SQL injection. You must change it so that the parameters $amp and $row['phone1'] are escaped in the SQL queries. Even if you're relying on magic qoutes now, this solution is not future-proof (now-proof really) as support for this is was removed in PHP 5.4.
What you have written should work:
http://ideone.com/ErV9fr
// How many to add
$response_count=3;
// Your response, just templated
$response_template=array(
'response_number'=>0,
'ackNo'=>'dffdgd',
'repairStatus'=>'$repairStatus',
'savedAt'=>'$savedAt'
);
// Your empty response array
$response = array();
for($i=0;$i<$response_count;$i++) {
$response_template['response_number'] = $i; // Set the 'response number' to the itteration.
$response[]= $response_template; // Add the template to the collection
}
print json_encode($response);
Result:
[{"response_number":0,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":1,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":2,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"}]
In addition to this, you should sanitize your $amp variable. In it's current form it would be trivial for a user to escape your query and execute an arbitrary query against your DB.
http://www.php.net/manual/en/mysqli.real-escape-string.php
Please recheck it can not give you the output like that {"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
as it is creating an array of array so it can not print like that.
It will always print like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]

Parsing JSON with PHP and displaying contents

I am having issues with this code
This is my PHP that worked with other projects...
$gas = file_get_contents('http://api.mygasfeed.com/stations/loadbygeo/47.9494949/120.23423432/reg|mid|pre|diesel/'. $api . '.json?callback=?');
$json_output = json_decode(utf8_decode($gas));
$location= $json_output->geoLocation->city_id;
This is the JSON result
?({"status":{"error":"NO","code":200,"description":"none","message":"Request ok"},"geoLocation":{"city_id":"13123","city_long":"Hulunber","region_short":"Nei Mongol","region_long":"Nei Mongol","country_long":"China","country_id":"49","region_id":"6010"},"stations":[]})
This code is returning a blank result.
You need to remove the ?( and the ). See WP:JSONP.
One could use substr() for that, or better yet a regex to assert and remove only the desired garbage:
$json = preg_replace("/ ^[?\w(]+ | [)]+\s*$ /x", "", $jsonp);
Would remove arbitrary callbackFnNames( but also your strange ?( pseudo function call.

Categories