I currently have an existing code in bash that greps a keyword from a config file:
[USER1]
usrcid = 5654654654
usrsid = XDFDFSAS22
usrmid = COMPANYNAME1
usrsrt = secret1
urlenc = http://www.url1.com
[USER2]
usrcid = 5654654667
usrsid = XDFDFSAS45
usrmid = COMPANYNAME2
usrsrt = secret2
urlenc = http://www.url2.com
I store it as a variable and use it for processing the rest of the script. What I want to achieve is to convert the behavior from bash to php and do a curl:
F1=/etc/config/file.txt
CID=`grep "\[USER1\]" -A 5 $F1 | grep usrcid | awk {'print$3'}`
SID=`grep "\[USER1\]" -A 5 $F1 | grep usrsid | awk {'print$3'}`
MID=`grep "\[USER1\]" -A 5 $F1 | grep usrmid | awk {'print$3'}`
SRT=`grep "\[USER1\]" -A 5 $F1 | grep usrsrt | awk {'print$3'}`
URI=`grep "\[USER1\]" -A 5 $F1 | grep urlenc | awk {'print$3'}`
echo $CID $SID $MID $SRT $URI
I’m really not a php guru so please excuse the code below but from a general perspective, the below code is my understanding of what I want to achieve:
<?php
include "/etc/config/file.txt"
// *** the equivalent code grep? ***
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
// *** i'm not sure if this one is correct? ***
$returned_content = get_data('$URI/cid=$CID&sid=$SID&mid=$MID&srt=$SRT')
echo $returned_content;
?>
This is my first time to ask in stackoverflow so I would like to thank you in advance!
Include doesn’t do what you think it’s doing. It won’t get the variables you set in the text-file. If it were PHP code in the file you included, it would evaluate that, but in this case, it’s only text. See the Manual
What you need is to use the parse_ini_file() function. It takes the config file as first argument, and a boolean flag as the second. The second argument is used to let the function know that you should use sections in your config file, which you do.
Example:
file.txt:
test.php:
(See the manual for
parse_ini_file())This will load the config file to the
$configvariable, and it will contain the following:Now, to construct an URL you could use:
Or construct a dynamic way of iterating through the array given in the $config variable, to account for several sections. This URL you can run through the cURL function you got.