Get section name by key name of an ini file in php - php

I have an ini file which looks like this:
[236a4e392b6dd0a8409bb91c664ab6468be32555]
76561197961658420=DaRoL
76561197962180350=Spow
76561197962376928=Kolma
[efd3dd758092ad90e35fb634a203c41b90da6333]
76561197964385070=Kelininkas
76561199641652847=Kelininkas
How is it possible in PHP to return the section name by searching with a key name (or optional key value).
e.g. 76561197964385070 -> efd3dd758092ad90e35fb634a203c41b90da6333 and optional
Kelininkas -> efd3dd758092ad90e35fb634a203c41b90da6333
I imported the ini file into an array and I'm able to find the key and item.
But not the key name of the superordinate key.
<?php
header('Content-type: text/plain');
$ini_array = (parse_ini_file("BannedHWs.ini",true));
$steamid="76561197962180330";
function find($item, $key)
{
global $steamid;
if ($key == $steamid)
echo "$key FOUND $item\n";
}
array_walk_recursive($ini_array, 'find');
echo "\n";
print_r ($ini_array); // SHOW ARRAY
?>
Result:
76561197962180330 FOUND Spow
Array
(
[236a4e392b6dd0a8409bb91c664ab6468be32d15] => Array
(
[76561197961658460] => DaRoL
[76561197962180330] => Spow
[76561197962376938] => Kolma
)
[efd3dd758092ad90e35fb634a203c41b90da6895] => Array
(
[76561197964385060] => Kelininkas
[76561199641652827] => Kelininkas
)
)
Thanks in advance

If you are on a linux machine, this might help you. This is not a solution, but a path where you can go further.
$ cat some_config_ini.txt
[efd3dd758092ad90e35fb634a203c41b90da6333]
76561197964385070=Kelininkas
76561199641652847=Kelininkas
$ cat some_config_ini.txt | grep Kelininkas -B 1 | head -1
[efd3dd758092ad90e35fb634a203c41b90da6333]
Above commands will not work with your original file.
$ cat som_config_ini.txt | grep Spow -B 1 | head -1
76561197961658420=DaRoL
However if you know know the key&values under a block, you can try this.
$ cat som_config_ini.txt | grep Spow -B 2 | head -1
[236a4e392b6dd0a8409bb91c664ab6468be32555]
$ cat som_config_ini.txt | grep Kolma -B 3 | head -1
[236a4e392b6dd0a8409bb91c664ab6468be32555]
Be aware of the arguments passed to grep [-B 1/2/3].
I can offer ruby&python solutions if you prefer.

Found my own solution:
<?php
header('Content-type: text/plain');
$ini_array = (parse_ini_file("BannedHWs.ini",true));
$steamid="76561199641652827";
function findID(array $array, $path = null) {
global $steamid;
foreach ($array as $k => $v) {
if (!is_array($v)) {
if ($k == $steamid){
echo "HWID: $path\n";
}
}
else {
findID($v, $path.$k);
}
}
}
findID($ini_array);
//echo "\n";
//print_r ($ini_array); // SHOW ARRAY
?>
Based on:
get parent array name after array_walk_recursive function

Related

What is the equivalent "grep" command in php?

Please bear with me since I'm still really new in PHP. So I have a config file like this:
profile 'axisssh2'
server '110.251.223.161'
source_update 'http://myweb.com:81/profile'
file_config 'udp.group-1194-exp11nov.ovpn'
use_config 'yes'
ssh_account 'sgdo.ssh'
I want to create a PHP variable named $currentprofile with the value of axisssh2, the value keeps changing. With grep in bash I can just do
currentprofile=$(cat config | grep ^profile | awk -F "'" '{print $2}')
But I have no idea how to do that with PHP. Please kindy help me how to do that, thank you.
UPDATE:
So I tried preg_match like this but it only shows the value of 1
$config=file_get_contents('/root/config');
$currentprofile=preg_match('/^profile /', $config);
echo "Current Profile: ".$currentprofile;
Please tell me what's wrong.
I'm going out on a limb to answer a question that you didn't ask. You'd be better off using parse_ini_string() or fgetcsv(). The .ini file would need the following format profile='axisssh2', so replace the space:
$array = parse_ini_string(str_replace(' ', '=', file_get_contents($file)));
print_r($array);
Yields:
Array
(
[profile] => axisssh2
[server] => 110.251.223.161
[source_update] => http://myweb.com:81/profile
[file_config] => udp.group-1194-exp11nov.ovpn
[use_config] => yes
[ssh_account] => sgdo.ssh
)
So just:
echo $array['profile'];
But the answer to your question would be:
preg_grep()
preg_match()
preg_match returns the number of matches (which is why you get 1) but you can get the actual matches with a capture group which will populate the third argument:
$config = file_get_contents('/root/config');
$currentprofile = preg_match("/^profile '(.*)'/", $config, $matches);
echo $matches[1];

How to get values for a dynamically generated array in php

I am generating a dictionary in PHP where key and values are added to the dictionary.
But I am not able to fetch the values back. I am using following code:
//some code here
while (($line = fgets($fileServices)) !== false) {
//echo $line.'....................';
if (strpos($line,'header') == false){
$serviceName=explode(",", $line)[0];
$RestartData=explode(",", $line)[1];
$StatusData=explode(",", $line)[2];
$serviceRestartMappingdict[$totalServices]= $serviceName.':'.$RestartData;
$serviceStatusMappingdict[$totalServices]= $serviceName.'_'.$StatusData;
$totalServices = $totalServices+1;
}
}
$counter=0;
//echo $serviceStatusMappingdict[0];
fclose($fileServices);
$counter=0;
for ($i = 0; $i < count($serviceStatusMappingdict); ++$i){
echo '<<<<<<<<<<<<<<<<<<<<<<<'.$serviceStatusMappingdict[$i].'>>>>>>>>>>>>>>>>>>>>>>>>>>>';
}
If I do an echo like echo $serviceStatusMappingdict[0];, I get the value but when I use a loop to access the data I do not get any value.
[EDIT] The problem is coming because of the '<' character. Get rid of them and it will work straight away
To answer the following comments that have appeared, the characters '<' and '>' in combination in html refer to an opening and closure of a tag. ex: <div>
The problem comes because the browser is trying intrepreting it as an unknow element and does not know what to do with it. If you inspect the html code of the page you'll be able to see that the information is actually there, just not properly rendered.
[EDIT] Following Umpert parial answer, I tried this and it does the expected behavior. Can we have more informations on why it does not work in your case :
<?php
$array = array( '0' => "kakfa_ps -ef | grep kafka | grep server.properties",
'1' => "zookeeper_ps -ef | grep zookeeper | grep zookeeper.properties",
'2' => "schemaregistry_ps -ef | grep schema-registry | grep java",
'3' => "influx_/sbin/service influxdb status | grep active | grep running",
'4' => "mysql_/sbin/service mysql status | grep active | grep running",
'5' => "cassandra_/sbin/service cassandra status | grep active | grep exited",
'6' => "aerospike_/sbin/service aerospike status | grep active | grep running");
for($i=0;$i<count($array);++$i){
echo '<<<<<<<<<<<<<<<<<<<<<<<'.$array[$i].'>>>>>>>>>>>>>>>>>>>>>>>>>>>';
}
?>
Same amount of '<' and '>' as in your OP. Just to make sure.

Pass BASH associative arrays to PHP script

Is it possible to pass BASH associative arrays as argv to PHP scripts?
I have a bash script, that collects some variables to a bash associative array like this. After that, I need to send it to PHP script:
typeset -A DATA
DATA[foo]=$(some_bash_function "param1" "param2")
DATA[bar]=$(some_other_bash_function)
php script.php --data ${DATA[#]}
From PHP script, i need to access the array in following manner:
<?php
$vars = getopt("",array(
"data:"
));
$data = $vars['data'];
foreach ($data as $k=>$v) {
echo "$k is $v";
}
?>
What I've tried
Weird syntax around the --data parameter follows advice from a great post about bash arrays from Norbert Kéri how to force passed parameter as an array:
You have no way of signaling to the function that you are passing an array. You get N positional parameters, with no information about the datatypes of each.
However this sollution still does not work for associative arrays - only values are passed to the function. Norbert Kéri made a follow up article about that, however its eval based solution does not work for me, as I need to pass the actual array as a parameter.
Is the thing I'm trying to achieve impossible or is there some way? Thank you!
Update: What I am trying to accomplish
I have a few PHP configuration files of following structure:
<?php
return array(
'option1' => 'foo',
'option2' => 'bar'
)
My bash script collects data from user input (through bash read function) and stores them into bash associative array. This array should be later passed as an argument to PHP script.
php script.php --file "config/config.php" --data $BASH_ASSOC_ARRAY
So instead of complicated seds functions etc. I can do simple:
<?php
$bash_input = getopt('',array('file:,data:'));
$data = $bash_input['data'];
$config = require($config_file);
$config['option1'] = $data['option1'];
$config['option2'] = $data['option2'];
// or
foreach ($data as $k=>$v) {
$config[$k] = $v;
}
// print to config file
file_put_contents($file, "<?php \n \n return ".var_export($config,true).";");
?>
This is used for configuring Laravel config files
Different Approach to #will's
Your bash script:
typeset -A DATA
foo=$(some_bash_function "param1" "param2")
bar=$(some_other_bash_function)
php script.php "{'data': '$foo', 'data2': '$bar'}"
PHP Script
<?php
$vars = json_decode($argv[1]);
$data = $vars['data'];
foreach ($data as $k=>$v) {
echo "$k is $v";
}
?>
EDIT (better approach) Credit to #will
typeset -A DATA
DATA[foo]=$(some_bash_function "param1" "param2")
DATA[bar]=$(some_other_bash_function)
php script.php echo -n "{"; for key in ${!DATA[#]}; do echo - "'$key'":"'${DATA[$key]}'", | sed 's/ /,/g' ; done; echo -n "}"
this does what you want (i think) all in one bash script. You can obviously move the php file out though.
declare -A assoc_array=([key1]=value1 [key2]=value2 [key3]=value3 [key4]=value4)
#These don't come out necesarily ordered
echo ${assoc_array[#]} #echos values
echo ${!assoc_array[#]} #echos keys
echo "" > tmp
for key in ${!assoc_array[#]}
do
echo $key:${assoc_array[$key]} >> tmp # Use some delimeter here to split the keys from the values
done
cat > file.php << EOF
<?php
\$fileArray = explode("\n", file_get_contents("tmp"));
\$data = array();
foreach(\$fileArray as \$line){
\$entry = explode(":", \$line);
\$data[\$entry[0]] = \$entry[1];
}
var_dump(\$data);
?>
EOF
php file.php
the escaping is necessary in the cat block annoyingly.

How can i fix the output of this recursion function

function my_recurse($id,$tree=array())
{
$hols = array();
$overall = array();
$asd = $this->db->get_where('story', array('story_id'=>$id))->row_array();
if(isset($asd['story_id'])){
$preds = explode(',',$asd['story_pred']);
if($preds[0] != 0)
{
$hols[] = $preds[0];
$hols = array_merge($tree, $hols);
$this->my_recurse($preds[0],$hols);
}
}
print_r($hols);
}
say for example i have this tree
story1 NULL
story2 story1
story3 story2
story4 story3
and when i enter story4 as my id in the function it always returns the story3 and not story1,story2 and story3. dont know why it reverses the output after the recursion happens. any suggestions would be appreciated
It's hard to say if this will be easy or possible without knowing your database structure, but you don't need recursion to find the path of a tree node to the root - you can do this with a self join. Also, you should avoid making a query in a recursive function. If you can describe your table structure I can attempt to show you how to get a result set that is the tree path in order.
The problem with your code is that its passing the current preds up to the parent hence the reverse tree. Instead it should be getting the preds from the parent
This should work if I understood your requirements clearly
<?php
function my_recurse($id) {
$hols = array();
$overall = array();
$asd = getFromDB($id);
if(isset($asd['story_id'])){
$preds = explode(',',$asd['story_pred']);
if($preds[0] != 0) {
$hols[] = $preds[0];
$hols = array_merge(my_recurse($preds[0]), $hols);
} else {
return $hols;
}
print "preds of {$id} : ";
print implode(', ', $hols) . "\n";
return $hols;
}
}
function getFromDB($id) {
$data = array(1 => array('story_id'=>1, 'story_pred' => '0'),
2 => array('story_id'=>2, 'story_pred' => '1'),
3 => array('story_id'=>3, 'story_pred' => '2'),
4 => array('story_id'=>4, 'story_pred' => '3'),
);
return $data[$id];
}
my_recurse(4);
Running the script above..
$ /usr/bin/php recurse.php
preds of 2 : 1
preds of 3 : 1, 2
preds of 4 : 1, 2, 3
PS: Please add your sample input, output and expected output. It took me 15 minutes to try understanding your problem.

Parse JSON Freebase results in PHP

I'm really sorry if this is too basic, but I really don't know how to do this.
I'm using this jquery Autocomplete plugin: http://devthought.com/wp-content/projects/jquery/textboxlist/Demo/
EDIT: This is the jquery code i use for the autocomplete:
$(function() {
var t = new $.TextboxList('#form_topick_tags', {unique: true, plugins: {autocomplete: {
minLength: 2,
queryRemote: true,
remote: {url: 'autocomplete2.php'}
}}});
The plugin uses a PHP for autocomplete, this is an example, it returns this output: "id, text, null (html I don't need), some html"
$response = array();
$names = array('Abraham Lincoln', 'Adolf Hitler', 'Agent Smith', 'Agnus', 'Etc');
// make sure they're sorted alphabetically, for binary search tests
sort($names);
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
foreach ($names as $i => $name)
{
if (!preg_match("/^$search/i", $name)) continue;
$filename = str_replace(' ', '', strtolower($name));
$response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);
}
header('Content-type: application/json');
echo json_encode($response);
I need a similar PHP to process this results: http://www.freebase.com/private/suggest?prefix=beatles&type_strict=any&category=object&all_types=false&start=0&limit=10&callback=
...being "beatles" the $search value, and getting this output:
guid,"name",null,"name<span>n:type name</span>"
So, the first result would be:
0,"The Beatles",null,"The Beatles<span>Band</span>"
Of course I would need to query freebase.com from that PHP. I mean:
+---------------+ +-----------+ +------------+
| | | | | |
| TextboxList +-------->| PHP +------->| Freebase |
| | | | | |
+---------------+ +-----------+ +------+-----+
|
JSON JSON |
TextboxList <--------+ freebase <----------+
Is this possible? Thanks!
Try this:
$response = array();
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$myJSON = file_get_contents('http://www.freebase.com/private/suggest?prefix=' . urlencode($search));
$musicObj = json_decode($myJSON); // Need to get $myJSON from somewhere like file_get_contents()
foreach ($musicObj->result as $item)
{
$response[] = array($item->guid, $item->name, null, $item->name . '<span>'.$item->{'n:type'}->name.'</span>');
}
header('Content-type: application/json');
echo json_encode($response);
The first JSON-escaped result then gives:
["#9202a8c04000641f800000000003ac10","The Beatles",null,"The Beatles<span>Band<\/span>"]
But despite all this, you really don't need to use PHP at all to do this. You can do this all from JavaScript and avoid an extra trip to your server. If you supply the callback argument to freebase, it can create JSONP (which is JSON wrapped in a call to a function, using a function name of your choice) which you can obtain in jQuery and then manipulate further in JavaScript to your liking. But the above is per your original approach in using PHP.

Categories