From wp-config.php file I need to get DB name, username, password values without including the wp-config file and assign them to three separate variable for further use.
define('DB_NAME', 'somedb');
define('DB_USER', 'someuser');
define('DB_PASSWORD', 'somepass');
my script will be in the same folder. No I don't want to use any WordPress functions.
If you really don't want to include the file, as mentioned in the comments already,
we can read the file contents into an array with file().
The iterate over each line and apply some cleanup, until we get to a format we can work with:
<?php
$config = file('wp-config.php');
$dbLines = [];
foreach($config as $line){
if (stristr($line,"define('DB_")!==FALSE){
$dbLines[] = $line;
}
}
array_walk($dbLines, 'cleanup');
// apply the cleanup() function to all members of the array, basically to each line
function cleanup(&$value){
// replace the leading 'define(' and trailing closing bracket
$value = str_replace(
array("define(",");"),'',$value
);
$value = preg_replace('#\s+//(.*)#','',$value); // remove the comments
}
// at this point we have a csv structure with a single quote as the delimiter
// comma+space as a separator
$dbConfig = [];
foreach ($dbLines as $dbline){
// read the line into separate variables and build an array
list($key,$value) = (str_getcsv($dbline,', ',"'"));
$dbConfig[$key] = $value;
}
print_r($dbConfig);
This will output
Array
(
[DB_NAME] => putyourdbnamehere
[DB_USER] => usernamehere
[DB_PASSWORD] => yourpasswordhere
[DB_HOST] => localhost
[DB_CHARSET] => utf8
[DB_COLLATE] =>
)
If you want to access a single element from the array, just
print $dbConfig['DB_HOST'];
Related
I am having one file which contains some stuff. I want to use first column of the file and than make an array of that column. Now when i use grep in PHP to find the associated row from main file as per made array value the script just hangs produce no output.
Below is my code-:
<?php
$temp=exec("wc -l /root/live/lastDateTemplate-28-11-2013.csv");
$removeHeading=$temp -1;
$getNewsletterNameFile=exec("awk 'BEGIN { FS = \",\" } ; { print $1 }' /root/live/lastDateTemplate-28-11-2013.csv | tail -$removeHeading > /root/live/demoFile.txt");
$fp=fopen('/root/live/demoFile.txt', 'r');
while (!feof($fp))
{
$getNewsletter=fgets($fp);
$getNewsletter=trim($getNewsletter);
$newsLetterName[]=$getNewsletter;
}
fclose($fp);
$lenOfNewsletterFile=count($newsLetterName);
$requiredLength=$lenOfNewsletterFile - 1;
$current_day_csvFile ="/root/live/lastDateTemplate-28-11-2013.csv";
for($i=0;$i<=$requiredLength;$i++)
{
$getRow=exec("grep ".$newsLetterName[$i]." ".$current_day_csvFile);
}
?>
If I understand the question correctly, you'd like to create an assoc array from a csv where the key is the first column and the values are arrays containing the other columns. If that's so I'd reckon you should remove the awk/grep subshells as they're doing redundant work, a single pass of php alone would suffice. Here is a what I'd do:
$file = '/root/live/lastDateTemplate-28-11-2013.csv';
$rows = array();
# read the file line by line:
foreach (file($file) as $line) {
# split the first column from the others:
list($title, $csv_attributes) = explode(',', $line, 2);
# split the attributes into an array:
$attributes = explode(',', $csv_attributes);
$rows[$title] = $attributes;
}
# remove the first row, the header line:
array_shift($rows);
PHP has many powerful string/array functions that make these sorts of problems a breeze, I'd suggest you check them out, they'll make your life easier!
http://www.php.net/manual/en/ref.strings.php
http://us3.php.net/manual/en/ref.array.php
I am using the following code to initiate a python script and pass a php variable to it.
$tmp = exec("python path/to/pythonfile.py $myVariable $mySecondVariable", $output);
This works very well, my issue is that I will need to pass 100+ variables to the python script. I don't want this exec line to become extremely long and unmanageable. I have also explored passing a php array instead of a variable with the following code:
$checked = array(
"key1" => "1"
"key2" => "1"
"key3" => "1"
);
$checkedJson = json_encode($checked);
$tmp = exec("python path/to/pythonfile.py $myVariable $checkedJson", $output);
With this I have been unable to decode the JSON on the python side. I have been able to do a basic print of the array variable(undecoded) in python, but it gives every individual character as a new array value. ie [0] = k, [1] = e, [2] = y, [3] = 1, etc...
Any help is greatly appreciated.
Just to be clear,I am looking for a simpler method than encoding and decoding an array. Is there a way I can format the exec line to allow for multiple variables.
Store your PHP variables within a temporary text file then use python to read that file.
Simple and effective.
Assuming Scripts are in the same directory
PHP Portion
long version (self contained script - skip to the short version below if you only want the code snippet)
<?php
#Establish an array with all parameters you'd like to pass.
#Either fill it manually or with a loop, ie:
#Loop below creates 100 dummy variables with this pattern.
#You'd need to come up with a way yourself to fill a single array to pass
#$variable1 = '1';
#$variable2 = '2';
#$variable3 = '3';
#....
#$variableN = 'N';
#...
for ($i=1; $i<=100; $i++) {
${'variable'.$i} = $i;
}
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
#let's say N=100
for ($i=1; $i<=100; $i++) {
#for custom keys
$keyname = 'Key'.$i;
# using a variable variable here to grab $variable1 ... $variable2 ... $variableN ... $variable100
$phpVariablesToPass[$keyname] = ${'variable'.$i} + 1000;
}
#phpVariablesToPass looks like this:
# [Key1] => 1001 [Key2] => 1002 [Key3] => 1003 [KeyN] = > (1000+N)
#now write to the file for each value.
#You could modify the fwrite string to whatever you'd like
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
#close the file
fclose($fh);
?>
or in short, assuming $phpVariablesToPass is an array filled with your values:
#Create/Open a file and prepare it for writing
$tempFile = "temp.dat";
$fh = fopen($tempFile, 'w') or die("can't open file");
foreach ($phpVariablesToPass as $key=>$value) {
fwrite($fh, $value."\n");
}
fclose($fh);
Python Snippet to Grab the Data
lines = [line.strip() for line in open('temp.dat')]
the variable lines now contains all of your php data as a python list.
I have a standard config file: $variable = 'value';, but at the last moment came up to use the web interface to configure it. So what is the best way to read the file, find the value of variables and then resave the file again?
At the moment I have 2 ideas:
1) RegExp
2) Keep somewhere array example
Store all config values in an associative array like so:
$config = array(
'variable' => 'value'
);
For the web interface, you can easily loop over the entire array:
foreach($config as $key=>$value) { ... }
After making changes, loop over the array and write it back to the file. (You really should be using a DB for this, though).
When you include the file, you can either use it like this:
include('config.php');
echo $config['variable']
// or
extract($config);
echo $variable;
Note: If you extract, it will overwrite any variables by the same name you might have defined before extracting.
PS - To make it easier to read and write to and from a file, I would just use json encoding to serialize the array.
Use a db
If your config is user defined - it would be better to store the config in a database. Otherwise you have this "novel" problem to solve but also potentially introduce security problems. I.e. for any one user to be able to edit your config files - they must be writeable to the webserver user. That opens the door to injecting malicious code into this file from a web exploit - or simply someone with direct access to your server (shared host?) finding this writeable file and updating it to their liking (e.g. putting "<?php header('Location: my site'); die;" in it).
One config variable
If you must manage it with a config file, include the file to read it, and var_export the variables to write it. That's easiest to do if there is only one config variable, that is an array. e.g.:
function writeConfig($config = array()) {
$arrayAsString = var_export($config, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Allow partial updates
If you are changing only some variables - just include the config file before rewriting it:
function writeConfig($edits = array()) {
require 'config.php';
$edits += $config;
$arrayAsString = var_export($edits, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Multiple config variables
If you have more than one variable in your config file, make use of get defined vars and loop on them to write the file back:
function writeConfig($_name = '', $_value) {
require 'config.php';
$$_name = $_value; // This is a variable variable
unset($_name, $_value);
$string = "<?php\n";
foreach(get_defined_vars() as $name => $value) {
$valueAsString = var_export($value, true);
$string .= "\$$name = $valueAsString;\n";
file_put_contents('config.php', $string);
}
}
The above code makes use of variable variables, to overwrite once of the variables in the config file. Each of these last two examples can easily be adapted to update multiple variables at the same time.
I have a csv file I need to cleanup. It contains 13 fields, but I only need 7 (Business, Address, City, St, Zip, Phone, Email)
I need to run through all of the records and create a new output of just the records with email addresses.
In nutshell... I load the original file, run the for loop, explode the results, then look for the records where the $tmp[10] index is not null. I then get the rest of the rest of required fields, and do a foreach loop and fwrite the results to a new csv file.
Depending on how I tweak the code, I get either...
A text file of just email addresses.
or
A text file of just the last record with an email address.
I have been working on this too long and I just need a fresh set of eyes to point out the problem. I am new to php, and want to make this work. Thanks on advance.
<?php
// See if file exists and is readable
$file = 'uploads/AK_Accountants.csv';
$newfile = basename($file,".csv");
$newfile = $newfile.Date("Ymd").".csw";
$fileNew = fopen('uploads/AK_'.Date("Ymd").'.csv','w+');
// Read the file into an array called $sourcefile
$sourcefile = file($file);
// Loop through the array and process each line
for ($i = 0; $i < count($sourcefile); $i++) {
// Separate each element and store in a temp array
$tmp = explode('","', $sourcefile[$i]);
// Assign each element of the temp array to a named array key
if ($tmp[10] != "") {
$sourcefile[$i] = array('Business_Name' => $tmp[1], 'Address' => $tmp[3], 'City' => $tmp[4], 'State' => $tmp[5], 'Zip' => $tmp[6], 'Phone' => $tmp[7], 'Email' => $tmp[10]);
foreach($sourcefile[$i] as $key => $value);
fwrite($fileNew, $value);
}
}
?>
From a quick glance:
foreach($sourcefile[$i] as $key => $value);
fwrite($fileNew, $value);
should be
foreach($sourcefile[$i] as $key => $value){
fwrite($fileNew, $value);
}
Also, you have
$newfile = $newfile.Date("Ymd").".csw";
rather than what I assume should be
$newfile = $newfile.Date("Ymd").".csv";
Your last foreach statement is terminated by a ';' and has no code block. Once the foreach statement has finished iterating you'll get the last value written to file i.e. just the email address.
You currently have
foreach (... ) ;
fwrite(...);.
but you probably mean
foreach( ... ) {
fwrite(...) ;
}
Been there, done that :)
HTH
Am developing an admin center where I can edit configuration files (written in PHP). I do NOT want to store these values in a mySQL table (for various reasons). So say my config.php has contents like:
<?php
$option1 = 1;
$option2 = 2;
$option4 = 5;
$option7 = array('test','a','b',c');
?>
Now say in one of the admin pages I will only be changing a few values like option2 or option4 etc. Any ideas on what would be the best way to go about this.
I know one option is to read the PHP file completely and write parts of it using REGEX. Any way to make this more efficent? I don't want the config.php file to break because of some error on the user's end. Any ideas on how to ensure that it works?
If you have some liberty about the way you store configuration values, you may use ini files.
All you have to do is load the content of the ini file in an array with parse_ini_file, then modify values in that array and finally overwrite the file with new values, as described in this comment.
For obvious security reasons it's a good idea to place those files out of your document root.
sample content of ini file :
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
sample code (using safefilewrite function) :
<?php
$ini_file = '/path/to/file.ini';
$ini_array = parse_ini_file($ini_file);
$ini_array['animal'] = 'CAT';
safefilerewrite($file, implode("\r\n", $ini_array));
?>
var_export() is probably the function you're looking for.
You can write/read the settings to a file using the following code:
$content = array();
//fill your array with settings;
$fh = fopen ( $bashfile, 'w' ) or die ( "can't open file" );
fwrite ( $fh, $content );
fclose ( $fh );
to read it you use:
file_get_contents() //this will return a string value
OR
Line by line:
$lines = file('file.txt');
//loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
print "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}