Parse array from php file - php

The .php file contains code like:
<?php
return array(
// commments...
'some_item' => 'abc',
// commments...
'some_other_item' => array(1, 2, 3),
...
);
What's the best way to "parse" this file somehow from within my PHP application, and be able to update data in it, without breaking formatting, code etc. ?

$content = require($file); will get the file's content (beware of relative paths and requirevs include semantics).
file_put_contents($file, '<?php return ' . var_export($content, true) . ';'); will write the content back to the file, but formatting will change. If you really need to keep the formatting, you could look into PHP Beautifier. It's not a perfect solution though.

simply include() the file:
$my_array = include 'myarray.php';
See example #4 at http://php.net/manual/en/function.include.php and http://php.net/manual/en/function.return.php

The best way is to include it; yes, include returns a value!
$data = include 'someData.php';

Assuming that your array has only two items
<?php
$myArray=include 'data.php';
$myArray[count($myArray)]='Item-3';
echo $myArray[2]; // Item-3
?>

Are you trying to load filenames which are contained in an array? If so:
$array_of_files = array('header.php','database.php','../inc/other_stuff.php');
foreach($array_of_files as $file)
{
include $file;
}

Related

I need to include file in array

I tried to include the php file in array like that but it is not working
username.php file is : "mohammed", "ahmed", "hafian", "gimmy", "osama"
and the main file is : $usernames = array(include 'usernames.php');
In usernames.php do:
<?php
return ["mohammed", "ahmed", "hafian", "gimmy", "osama"];
In foo.php do:
$usernames = include 'usernames.php';
RTM: https://www.php.net/manual/en/function.include.php#example-145
You will need to open and read the file, you can't just include and expect it to parse the file and store into your array. Also, can you make usernames.php a text file and not PHP code? You don't want to be parsing PHP code. I think you'll need to approach it like this:
`<?php
$fn = fopen("usernames.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
# parse line and append to array
}
fclose($fn);
?>`

Accessing variables in PHP files

Is there anyway to access variables of one php file into another?
- I am trying to validate a form. I need to access variables from the validationConditions.php file in form.php file.
I have tried creating sessions but they are error prone.
I am using the latest version of dreamweaver.
Is it possible to use $_POST to achieve the results?
Any example will be welcome...
Thanks a lot in advance.
The easiest would be to use session variables. In the first page you could set the values like this
session_start();
$_SESSION['myvar'] = 'My Data';
Then in the second page you can retrieve the data like this...
session_start();
$myvar = $_SESSION['myvar'];
Which in turn sets $myvar to "My Data"
You can read a php file with another php file. Assume that we have 2 php files.
new.php
<?php
$a="something";
?>
serach.php ---> search in new.php
<?php
// What to look for
$search = '$a'; //WE are searching $a
$lines = file('new.php'); // in new.php
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
?>
Something like that. You have to edit this file.
A somehow devious solution:
ob_start();
$request = array(
"_id"=>"0815",
"user"=>"john",
"email"=>"john#dunbar.com",
"phone"=>NULL
); // Don't know. Just how u need your request to look like.
include('validationConditions.php');
$response = getValidationConditions($request); // Function in 'validationConditions.php' that responds an array or a JSON
$out = ob_get_clean();
echo json_encode($out);

include if value in array defined on included file

I want to check if the page name is a value in an array defined on the included file and, if so, include it.
<?php
// parent page that includes the files
$pageLabel = 'three';
if (in_array('pageLabel', $multicats)) {
include $filename;
}
?>
<?php
// example for a file to be included
$multicats = array('one', 'three', 'five');
$filename = $_SERVER['PHP_SELF'];
echo 'Hello World of one, three and five';
?>
However an error says it expects $multicats to be an array, which it is, meaning it doesn't check the included file for it.
What to do?
You have to have array of multicats somewhere in parent page before condition. If you have it in included file, it's init after using in condition. Or you can check if it exist with isset, as Captain Crunch said.
Note: in condition in_array you have string 'pageLabel' and not var $pageLabel, is it correct?
first, you should pass: $pageLabel var, and not 'pageLabel' string (see line 4 in your code).
second, i advise you use "isset":
if ( isset($multicats) && isset($multicats[$pageLabel]) && isset($filename) )
include $filename;

PHP - Executing PHP from a string

This one is a bit of a weird one. Ive created a function designed to select a template and either include it or parse the %0, %1,%3 etc. variables. This is the current function:
if(!fopen($tf,"r")){
$this->template("error",array("404"));
}
$th = fopen($tf,"r");
$t = fread($th, filesize($tf) );
$i=0;
for($i;$i<count($params);$i++){
$i2 = '%' . $i;
$t = str_replace($i2,$params[$i],$t);
}
echo $t . "\n";
fclose($th);
Where $th is the relative directory to my template file. My issue is, I need to execute the PHP inside of these files whilst at the same tme being able to replace the string variables %0 %1 etc.
How could I go about attempting this?
Like I said in my comment I think a template engine like Smarty would probably serve you better but here's how I'd do it with output buffering rather than eval()
Something like this
ob_start();
include "your_template_file.php";
$contents = ob_get_contents(); // will contain the output of the PHP in the file
ob_end_clean();
// process your str_replace() variables out of $contents

How to save php config?

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.

Categories