Everyone, hello!
I'm currently trying to write to an .ini file from PHP, and I'm using Teoman Soygul's answer and code from here: How to read and write to an ini file with PHP
This works out great, although, when I save the data to it, it shows up strange in my .ini:
[Server] = ""
p_ip = "192.168.10.100"
p_port = 80
p_password = 1234
[Variable] = ""
string1_find = "Caution"
Most notably it also seems to see attempt to give the categories Server and Variable an empty value. Also, sometimes it saves the variable between consistency and sometimes not. How come there is no consistency here?
The code I'm using to find/post in PHP is this:
...
$a=array("[Server]"=>'',"p_ip"=>$_POST['pip'],"p_port"=>$_POST['pport'], "p_password"=>$_POST['pass'],
"[Variable]"=>'',"string1_find"=>$_POST['string1_find'],
...
If anyone could point me into the right direction, that would really be appreciated. Thank you!
You are not using right, you should be passing a multidimentional array instead:
$data = array(
'Server' => array(
'p_ip' => '192.168.10.100',
'p_port' => 80,
'p_password' => 1234,
),
'Variable' => array(
'string1_find' => 'Caution'
)
);
//now call the ini function from Soygul's answer
write_php_ini($data, 'file.ini');
Here is my output:
[Server]
p_ip = "192.168.10.100"
p_port = 80
p_password = 1234
[Variable]
string1_find = "Caution"
Notice that you need to create an extra array per new section and then you can start listing your custom definitions.
Related
I am using a PHP script (this one) to generate a JSON file for a Google Map.
this is the PHP code (note: I am using Laravel):
<?php
$query = "SELECT id, info, lat, lng FROM places";
$results = DB::select($query);
$myLocations = array();
$i = 0;
$testLoc = array('loc95' => array( 'lat' => 15, 'lng' => 144.9634 ));
foreach ($results as $result)
{
$myLocation = array(
'loc'.++$i => array(
'lat' => round((float)$result->lat, 4),
'lng' => round((float)$result->lng, 4)
));
$myLocations += $myLocation;
}
$myLocations += $testLoc;
echo json_encode($myLocations);
?>
and this is the output:
{"loc1":{"lat":45.4833,"lng":9.1854},"loc2":{"lat":45.4867,"lng":9.1648},"loc3":{"lat":45.4239,"lng":9.1652},"loc95":{"lat":15,"lng":144.9634}}
ok. the script I use to put the JSON data in a Google Map, unfortunately, keeps ignoring any data coming from the MySQL database, and shows only the test data place(s). I have tried to swap data, to put in test data the same info found in database... nothing, I keep seeing only the test data.
but, really: I cannot figure out why. What am I missing... ?
You wrote that you're using another script and that the other script only shows the testlocations on google maps.
My guess is that you didn't update the other script to your needs, specifically my crystal ball is telling me that you still have this line in there:
setMarkers(locs);//Create markers from the initial dataset served with the document.
In your question you only showed the part which worked and I agree, but you only mentioned that "something else" isn't working. If you want an answer for that part, try reprashing your question and include the parts which cause you problems.
I am primarily a PHP developer and have limited experience with Perl.
I was tasked with writing a queue script in Perl which checks against a database, and that is all working out great.
The problem I have is that in the Perl script I need to include a database hostname and password.
Right now I have them hard coded, which works fine, but my PHP application uses a global PHP array which holds the database hostname and password.I'd like to be able to use this PHP array in my Perl script.
Here is my PHP array
<?php
return array(
'database' => array(
'master' => array(
'hostname' => 'fd35:4776:6804:2:a::1',
'password' => 'password'
),
'slave' => array(
'hostname' => 'fd35:4776:6804:2:2::2',
'password' => 'password',
'profile' => true
)
)
);
I've tried searching with Google and have read many random posts on line, but I have yet been able to come up with a solution.
Does anyone have any ideas which I could try? If I'm missing any additional input, let me know and I can provide it.
Edit
Hopefully I worded this properly. How would I go about including this PHP array file so that I can manipulate it with Perl?
Alternative solutions are welcome too!
You've discovered one of the many reasons why code makes for bad config files. You should move the information to an actual config file, and access that file from both that .php file and from Perl.
JSON would make a decent file format here.
{
"database": {
"master": {
"hostname": "fd35:4776:6804:2:a::1",
"password": "password"
},
"slave": {
"hostname": "fd35:4776:6804:2:2::2",
"password": "password",
"profile": true
}
}
}
The Perl code would be
use JSON::XS qw( decode_json );
open (my $fh, '<:raw', $config_path)
or die("Can't open config file $config_path: $!\n");
my $file; { local $/; $file = <$fh>; }
my $config = decode_json($file);
On the PHP side, just replace the contents of the file you showed in your post with code to read the config file. I don't know PHP, but it should be quite simple. A quick search shows it might be
return json_decode(file_get_contents($config_path));
It would be simple to provide a short PHP program that dumps the array to a file in JSON format. That file can then be read from Perl using the JSON module.
This is all that is necessary.
<?php
$array = include 'array.php';
$fh = fopen('array.json', 'w');
fwrite($fh, json_encode($array));
fclose($fh);
?>
The resultant JSON file can then be read in a Perl program, like so:
use strict;
use warnings;
use JSON 'from_json';
my $data = do {
open my $fh, '<', 'array.json' or die $!;
local $/;
from_json(<$fh>);
};
use Data::Dump;
dd $data;
output
{
database => {
master => { hostname => "fd35:4776:6804:2:a::1", password => "password" },
slave => {
hostname => "fd35:4776:6804:2:2::2",
password => "password",
profile => bless(do{\(my $o = 1)}, "JSON::XS::Boolean"),
},
},
}
There is PHP::Include, which uses a source filter to let you have PHP blocks in your Perl code to declare variables. It also has a read_file() function that applies such a filter to a single PHP file.
But it seems to expect that your PHP has assignments (e.g. $config = array('database' => array(...) and changes those to Perl variable declarations.
In a few minutes of playing with it, I couldn't get it to do anything useful with your PHP code that uses return.
If you want a more "native Perl" solution, you can pretty much* just search and replace all your "array(" and their matching ")" to "{" and "}". That'll give you a perl datastructure called a "hash of hashes" (note: Unlike PHP, Perl refers to arrays with integer indicies as arrays (and uses the # sigil to denote variables containing them), but refers to array-like things with string indicies as "hashes" (and uses the % sigil to denote variables containing them)). The Perl keywords/concepts you probably want to read up on are:
Perl Data Structures: http://perldoc.perl.org/perldsc.html
and specifically the Hash Of Hashes section: http://perldoc.perl.org/perldsc.html#HASHES-OF-HASHES
and if you dont understand what $hashref = \%hash and %hash{key} and $hashref->{key} mean in Perl, you'd want to read http://perldoc.perl.org/perlref.html
Example code (note how similar the getConfig subroutine is to your PHP code):
#!/usr/bin/perl
use strict;
use warnings;
my $config=getConfig();
print "Database master host = " . $config->{database}{master}{hostname};
print "\n";
print "Database master password = " . $config->{database}{master}{password};
print "\n";
print "Database slave profile = " . $config->{database}{slave}{profile};
print "\n";
sub getConfig{
return {
'database' => {
'master' => {
'hostname' => 'fd35:4776:6804:2:a::1',
'password' => 'password'
},
'slave' => {
'hostname' => 'fd35:4776:6804:2:2::2',
'password' => 'password',
'profile' => 'true'
}
}
};
}
I said "pretty much", because your sample data used the bare word 'true' for the slave->profile value - that's a syntax error in Perl - you can change it to a bare 1, or quote the value as "true" to make it work. In Perl, the digit zero, the string "0" or the empty/nul string "" all evaluate to "false" in a boolean context, anything else evaluates to "true". Take care if you choose to automate PHP to Perl translation, there may be other PHP-isms which could catch you out like that.
So much good information here and it helped me out quite a bit to come up with a working solution.
Here is the perl script I've got working:
#!/usr/bin/perl
use PHP::Include;
include_php_vars( 'config.local.php' );
my $test = \%config;
print $test->{'database'}->{'master'}->{'hostname'};
I also took the PHP array and changed it so that it no longer return array() but $config = array() and then return $config;
This did the trick for me. Thank you!
I am converting a php program over to VBScript for ASP. I am stuck trying to find a way to structure a multi-dimensional array and could use some help.
Here is how it sets up in the php version:
// $_SESSION[model name][level name][menu name] => [state]
$_SESSION[$model] = array('level_name' => array('menu_name' => array()));
and then here is how I set a value later on
$_SESSION[$model][$level_name][$menu_name] = array('menu_state' => 'UNCHECKED');
Here is what I tried in VBScript that doesn't work
Session(model).Add "level_name", Array()
Session(model)("level_name").Add "menu_name", Array()
Session(model)("level_name")("menu_name").Add "menu_state", Array()
and then try to set the value
Session(model)(level_name)(menu_name)("menu_state") = "UNCHECKED"
but I end up with the very helpful 500 Server Error.
Any ideas?
You need a Dictionary of Dictionaries:
Dim dicX : Set dicX = CreateObject("Scripting.Dictionary")
Set dicX("A") = CreateObject("Scripting.Dictionary")
Set dicX("A")("B") = CreateObject("Scripting.Dictionary")
Set dicX("A")("B")("C") = CreateObject("Scripting.Dictionary")
dicX("A")("B")("C")("D") = "WhatEver"
WScript.Echo dicX("A")("B")("C")("D")
I am creating a 3D Secure PHP Project. I am having a rather bizzare issue in that the "MD" code is going missing when re-submitting the Array of data
My code is as follows :
$paRes = $_REQUEST['PaRes'];
$md = $_REQUEST['MD'];
require "payment_method_3d.php";
x_load('cart','crypt','order','payment','tests');
/*
* For Debugging Purposes
* Only.
echo "The Value Of PaRes is : ";
echo $paRes;
*/
$soapClient = new SoapClient("https://www.secpay.com/java-bin/services/SECCardService?wsdl");
$params = array (
'mid' => '',
'vpn_pswd' => '',
'trans_id' => 'TRAN0095', // Transaction ID MUST match what was sent in payment_cc_new file
'md' => $md,
'paRes' => $paRes,
'options' => ''
);
It seems that the $_REQUEST['MD'] string seems to go missing AFTER the soap call. Although I am having difficulty print this out to the screen. The strange thing is the $paRes variable works without issue.
Any ideas why this would be the case?
Check your case. PHP array keys are case sensitive. From this little bit of code it looks as if the request variable may be 'md' instead of 'MD'.
Try $md = $_REQUEST['md'];
PHP array statements are case sensitive, so this should work:....
$md = $_REQUEST['md'];
Thanks for your responses guys.
What was happening was the include page was sitting in front of the request methods and causing issues loading the REQUEST methods to the page.
I'm building my own personal CMS right now with PHP and MySql and I'm not sure of the best way to store site-wide variables such as the site name. What would be the proper way? (If you could provide a brief explanation that would be really nice too. ;)
EDIT: The variables would need to be editable from within the CMS.
In my opinion the best way is to store it in a config file (I use .ini files, but you could easily use a file like below).
I prefer this to storing it in a MySQL database, as it allows you to still get variables (like site name, or admin email address) even if the database is down
<?php
define('SITE_NAME','My CMS');
define('SITE_URL','http://www.example.com');
define('ADMIN_EMAIL','admin#example.com');
?>
EDIT:
Create a table like this
id key value
-------------------
1 name My Cms
2 url http://www.example.com
And access it like this (at the top of every page)
<?php
$config = array();
$query = mysql_query('SELECT * FROM config');
while ($row = mysql_fetch_row($query)) {
$key = $row['key'];
$value = $row['value'];
$config[$key] = $value;
}
echo $config['name'];
?>
There is no "best" sollution for all purposes.
Here are some examples how you can do this:
Simple PHP file:
This sollution is very simple but not very flexible:
you just 'define' constants:
define('SITE_NAME', 'all about Foo');
define ('ADMIN_NAME', 'The Dude');
define ('ADMIN_MAIL', 'dude#foo.com');
Pro: very very simple.
Cons: changes require that you edit the code. Only flat keys (no tree/registry)
ini File
PHP comes with functions to parse ini files. Here is an example rom the php manual:
; This is a sample configuration file
; Comments start with ';', as in php.ini
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"
you can parse this in a multi dimensional array:
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
Will output:
Array
(
[first_section] => Array
(
[one] => 1
[five] => 5
[animal] => Dodo bird
)
[second_section] => Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
[third_section] => Array
(
[phpversion] => Array
(
[0] => 5.0
[1] => 5.1
[2] => 5.2
[3] => 5.3
)
)
)
Pros: lexible. A well known standart syntax.
Cons: Hard to edit in backend
See: http://php.net/manual/de/function.parse-ini-file.php
Simple SQL
Another simple aproach, but this uses a database to store the conig keys.
The table structure is:
config{config_name UNIQUE KEY VARCHAR[64] ; config_value VARCHAR[128]}
This is only pseudo code and i you need more information about PHP and SQL feel free to google it.
SQL Tree
Allows you to create a tree like structure. To archive this you use the same table structure but include '/' in your key names:
admin/name | 'The Dude'
admin/mail | 'dude#foo.com'
Then you load your COMPLETE config in an array and parse it:
function parseRawConfig($rawConfig){
$result = array();
foreach($rawConfig as $key => $value){
$nodeNames = explode('/',$key);
$nodeCount = count($nodes);
$node = $result;
for($i=1;$i<$nodeCount;$i++){
if(!array_key_exists($nodeNames[$i],$node)){
$node[$nodeNames[$i]] = array();
}
}
$node[$nodeNames[$nodeCount-1]] = $value;
}
return $result;
}
Then you can access your keys like this:
echo $config['admin']['mail'];
This makes it easy to generate a nice tree view for your backend, but to save the changes you will have to 'reconstruct' the original path.
Pro: structured hierarchical data.
Con: Complicated, hard to implement, requires db connection
XML
Write all your conig settings in a xml file.
You can either use a app specific xml or a generic registry like style:
<cmsConf>
<site>all about foo</site>
<admin>
<name>The Dude</name>
<mail>dude#foo.com</mail>
</admin>
</cmsConf>
<reg>
<key name="site">all about foo</key>
<node name="admin">
<key name="name">The Dude</key>
<key name="mail">dude#foo.com</key>
</node>
</reg>
PHP provides plenty of classes and functions for reading/writting xml, and using xml makes it really easy to create interfaces to other applications.
The pros/cons of xml are a huge topic. To huge to sum them up in a few sentences.
IMPORTANT
These are just some very simple examples and if you choose one I recommend you dig deeper into the topic!
My fav is XML ;)
a configuration file in whatever format you like.
I usually create one table with all config variables. Every column will get a clear name of what its setting means. Then I use the following query to store it in a single array for easy use.
<?php
$result = mysql_query("SELECT * FROM configtable WHERE siteID=$siteID LIMIT 1");
$siteConfig = mysql_fetch_assoc($result);
?>
This way it is very easy to add new config parameters, you only need to add a column to the configtable and you can directly use the value in your site. Plus you only have one variable so an accidental reuse of a config variable wont happen.