I have a php file that contains an array.
//config.php
return [
'name' => 'XXXX',
'phone' => '000',
'email' => 'YYYY',
...
];
now i want to override config.php file and change email values to ZZZZ from another php file like index.php
If XXXX is going to be a placeholder, you could do:
$file_contents = file_get_contents("path/to/file");
$new_file_contents = str_replace("XXXX","ZZZZ", $file_contents);
file_put_contents("path/to/file", $new_file_contents);
PHP files are not supposed to be changed on-the-fly like this. It is technically possible, but that does not mean you should do it.
A decent solution that does not go around changing your code nilly-willy would be to create another file that modifies the configuration file and then returns it again:
// config-filtered.php
$config = include 'config.php';
$config['email'] = 'ZZZZ'; // Or = $_SESSION['user_email']; for example
return $config;
// index.php
$config = include 'config-filtered.php';
echo "Hello {$config['name']}, your email is {$config['email']}";
Related
I would like to create a file based on template Twig (and one parameter).
My file generated correctly with replace variable with my data. But if I change data my controller symfony generated always the same file with the same content.
My varDumper content (the text/plain character represent file) is good. It's change always with change variable content. But the writing file always generate the same content...
PHP seems do not caching with fwrite ou file_put_contents function but my content never change. I also disable caching for twigEngine but same result.
Can you help me to writing file with good last content.
All code is in a controller symfony. I keep comment code for your understanding all my test :
public function createEntityAction()
{
$rootDir = $this->getParameter('kernel.root_dir');
$templateDir = $rootDir . '/../src/CmsBundle/Resources/views/Entity/templateFile/';
$filename = 'test.php';
$pathFile = $templateDir . $filename;
$twigEngine = $this->get('twig');
$twigEngine->setCache(false);
$twigEngine->disableAutoReload();
// $loader = new Twig_Loader_Filesystem($templateDir);
// $twig = new Twig_Environment($loader, [
// 'cache' => '/path/to/compilation_cache',
// 'cache' => false,
// ]);
$baseTemplate = $twigEngine->loadTemplate('#Cms/Entity/templateFile/baseEntity.html.twig');
$script = $baseTemplate->render(['slug' => 'product-333']);
\Symfony\Component\VarDumper\VarDumper::dump($script);
if (file_exists($pathFile))
{
clearstatcache(true);
$ret = unlink($pathFile);
\Symfony\Component\VarDumper\VarDumper::dump($ret);
}
$file = fopen($pathFile, 'w+');
fwrite($file, $script);
fclose($file);
// file_put_contents($pathFile, $script);
return $this->render('#Cms/Entity/create.html.twig', []);
}
The final file content is always the same if I change the "slug" variable.
It looks to me like you're missing a variable in your controller. There should be something like this createEntityAction($slug), then this line should be $baseTemplate->render(['slug' => $slug); Right now it is doing exactly what you are telling it, you have a hard coded string for the slug...
If you post your controller definition it would help (annotations or yaml)
Perhaps I'm going about this the wrong way, but I have a Configuration file that I'm trying to pass through a parameter, the reason I'm doing this is because I'm experimenting with what I call a ("Core"/"Client") structure, probably not the correct name, but basically whatever I edit on the "Core" is updated to all of the "Client" subdomains, which will respectively call code such as
include '/path/to/core/index.php';
generateIndex($Param, $Param);
So, Basically, here's what I have, on the "Clients" side I have a Configuration file, called "Configuration.php" this holds all of the static variables pertaining to the Clients database. Example below:
<?php
$SQL_HOST = "";
$SQL_DATBASE = "";
$SQL_ACCOUNT_TABLE = "";
$SQL_DATA_TABLE = "";
$SQL_REWARDS_TABLE = "";
$SQL_USERNAME = "";
$SQL_PASSWORD = "";
?>
So, Basically, I'm trying to do this,
generateIndex($SQLConnection, $Configuration);
However, It's not allowing me to do so and presenting me with this error.
Notice: Undefined variable: Configuration in /opt/lampp/htdocs/client/index.php on line 16
Respectively, Line 16 is the line above containing "generateIndex"
Now, on the "Core" side what I'm trying to do is the following to get data.
function generateIndex($SQLConnection, $SQLConfig) {
...
$SQLConfig->TBL_NAME
...
}
Which I don't know if it throws an error yet, because I can't pass $Configuation to the function.
Your can user return context for get variable from file.
As example:
File db_config.php:
<?php
return array(
'NAME' => 'foo_bar',
'USER' => 'qwerty',
'PASS' => '12345',
// Any parameters
);
You another file with include configuration:
<?php
// Code here...
$dbConfig = include 'db_config';
// Code here
If file have a return statement, then your can get this values with = operator and include file.
Read the file before putting it in the function.
generateIndex($SQLConnection, file("configuration.php"));
file 1:
function test() {
global $Configuration;
echo $Configuration
}
file 2 (perhaps config)
$Configuration = "Hi!";
i have two php files config.php look like this:
config.php :
<?php
return array(
'name' => 'Demo',
'age' => 21,
'job' => 'Coder'
);
?>
in file index.php, i using file_get_contents for get data of file config.php
index.php:
$config = file_get_contents('config.php');
echo $config['name'];
but this is not working. somebody can help me?
You include code and not its output.
$config = file_get_contents('config.php');
Sends your file to PHP and generates the output and then sends it back to you, which is not what you have to do for code. You have to do
$config = include('config.php'); // or require / require_once / include_once
The function file_get_contents(file) reads the entire file into a string. That means that it will return a string represntation of the content of the file and NOT source code that you can just use in your main script.
Note: If the path to file is an absolute path, file_get_contents() will execute the php first and return the rendered output of the php file.
Since you want the source of 'config.php' to be available in 'index.php', you have to include it.
Just use include() or include_once().
config.php :
<?
$config = array(
'name' => 'Demo',
'age' => 21,
'job' => 'Coder'
);
?>
index.php:
include('config.php');//or include_once('config.php');
//include makes the content of 'config.php' available exactly as if it was written inside of the document iteself.
echo $config['name'];
Hope this helps!
I've been creating a small number of libraries / classes from scratch in php. I come from a codeigniter background, and I'm trying to make some libraries with similar functionality. I keep running into issues regarding objects.
Is the best way to create a super object $this somehow? My main issue is that I've created a view object and I run a function called load which looks like so:
class View {
public function __construct() {
}
public function load($file = NULL, $data = array()) {
if($file) {
$file .= '.php';
if(file_exists($file)) {
// Extract variables BEFORE including the file
extract($data);
include $file;
return TRUE;
} else {
echo 'View not found';
return FALSE;
}
} else {
return FALSE;
}
}
}
Then in my php file, I have at the top include 'libraries.php'; which looks like:
include 'database.php';
include 'view.php';
include 'input.php';
include 'form.php';
$config = array(
'host' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'database'
);
$database = new Database($config);
$view = new View();
$input = new Input();
$form = new Form();
From the file which I included the libraries, I am able to write something like $form->value('name'); without errors. However, if I do something like this:
$view->load('folder/index', array('var_name' => 'var_value')); then from the folder/index.php file I can access $var_name just fine, but not $form->value('name');. I get errors such as Call to a member function value() on a non-object in ...
My question is how can I organize my libraries and classes in a way that will be reusable. I don't want to use a front loader (an index.php file that everything runs through first). This may be an issue with the way I wrote my classes, but I imagine it's a larger issue regarding where things are located etc.
Put your library/class files in a common directory. Something like:
www
|_includes
| |_classes
| | |_view.php
| |_config
| |_database.php
|_other_folder
|_index.php
You can then set a common include path in your .htaccess file to this "includes" directory:
php_value include_path .:/path/to/www/includes
Then the other_folder/index.php file just needs something like:
require_once('config/database.php');
require_once('classes/view.php');
I have a library in code igniter that looks like class MyClass($options = array())
The file is Myclass.php
I have a file (config/Myclass.php) that looks like
$Myclass = array(
'something' => 'value',
'another' => 'value'
);
Which I thought should pass the $Myclass array in when I initialize my class, but apparently not?
What do I need to do to fix it?
AH I found the answer,
The array inside your config file must be called $config.
The name of the file must also be a lower case representation of the library file name.
e.g
LIB FILE: Somelibrary.php
LIB CONTENTS: class Somelibrary($options = array()){...
CONF FILE: somelibrary.php
CONF CONTENTS: $config = array('something' => 'value');
The way this usually works is that you pass in an array of options you wish to override, or pass in nothing to use the defaults.
var myObject = new MyClass(); // default settings
var myObject = new MyClass(array('something' => 'value2')); // override only "something"
Honestly, I wouldn't create your own file in config without a good reason; instead, just put the defaults in your class definition, and then override in your constructor:
class MyClass {
var $default_options = array(
'something' => 'value',
'another' => 'value',
);
var $options = array();
function MyClass($override_options = array())
{
$this->options = array_merge($this->default_options, $override_options);
// your code here...
}
}
Fast-forward to 2013, someone is still having problems with this. So my situation was the same but slightly different, so I thought I'd try to save someone else some time.
I was naming my config file after my extended class, that was wrong. The Config file should always be form_validation.php, (this is because eventually it is handed to the CI_Form_validation class and that's what it expects)
Thanks to the folks who answered this question above, I realized that I had to pass the config to the parent class and using codeigniter v2.1.3 I did it as follows:
public function __construct( $config = array() )
{
parent::__construct($config);
}