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!
Related
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']}";
I want a simple method to include some html text with php functions. Like creating a simple array with functions like: Ex. "about_us_text => About us text example etc.." . Which will be the easiest way to do this ? And how will I include the two files to work as one? Thanks.
$lang = array_merge($lang, array(
'ADD_ATTACHMENT' => 'Upload attachment',
'ADD_ATTACHMENT_EXPLAIN' => 'If you wish to attach one or more files enter the details below.',
'ADD_FILE' => 'Add the file',
'ADD_POLL' => 'Poll creation',
This code will automatically replace {ADD_ATTACHMENT} with Upload attachment
<?php
include 'lang.php';
ob_start();
include ('page_to_display.php');
$html=ob_get_clean();
for ($lang as $k=>$v)
$html=str_replace('{'.$k.'}',$v,$html);
echo $html();
?>
If you have a lengthy html text it is better to put it in its own file and define that file as a translations/constants file. Include that php file in your function/array. keeps it clean
http://php.net/manual/en/language.constants.php
Your constants file lang_constants_en.php might by like
<?php
define('ABOUT_US', '<p>About Us</p>');`
in your function called dump_html()
<?php
include('lang_constants_en.php');
function dump_html(){
echo "Other header html" . ABOUT_US;
}
dump_html();
I just want to use like phpbb3 !
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'ACTION' => 'Action',
'ACTION_NOTE' => 'Action/Note',
And they use {ACTION} for text. That is what I want... not html dump and other things....
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 want to use a new file containing constants in Codeigniter so I created the file /config/labels.php
When I try to load it in my controller using $this->config->load('labels'); and it throws
application/config/labels.php file does not appear to contain a valid configuration array.
However when I put the code in the constants.php file everything works well.
labels.php
<?php
define('CLI_CIVILITE','Civilité');
define('CLI_NOM','Nom');
define('CLI_PRENOM','Prenom');
The config file should contain an array $config
Thats why it throws the error.
When the config class loads the config file, it checks if $config was set.
If not it will throw an error.
As far as I know there is no feature to load your own file with custom constants.
As of now you will have to add those constants to application/config/constants.php
In the constants file, define a variable like below:
$ORDER_STATUS = array(
'0' => 'In Progress',
'1' => 'On Hold',
'2' => 'Awaiting Review',
'3' => 'Completed',
'4' => 'Refund Requested',
'5' => 'Refunded');
Then, in the controller:
function __construct()
{
$this->config->load('$ORDER_STATUS');
}
write in your config example and save as banned_idcard.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config ['banned_idcard'] = array (
'23104013',
'2010201103',
'11106062',
);
And in ur Controoler
<?php
function __construct () {
$banned_idcards = $this->config->load('banned_idcard');
}
in your config /config/labels.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
'CLI_CIVILITE' => 'Civilité',
'CLI_NOM' => 'Nom',
'CLI_PRENOM' => 'Prenom'
);
in your controller:
$this->config->load('labels');
var_dump((array)$this->config); //show all the configs including those in the labels.php
I'm writing a simple templating layer in PHP but I've got myself a little stuck. Here's how it works at the moment:
Firstly I use fetch_template to load the template contents from the database - this works (and I collect all the templates at startup if you're interested).
I use PHP variables in my template code and in the logic - e.g.:
// PHP:
$name = 'Ross';
// Tpl:
<p>Hello, my name is $name.</p>
I then use output_template (below) to parse through the variables in the template and replace them. Previously I was using template tags with a glorified str_replace template class but it was too inefficient.
/**
* Returns a template after evaluating it
* #param string $template Template contents
* #return string Template output
*/
function output_template($template) {
eval('return "' . $template . '";');
}
My problem, if you haven't already guessed, is that the variables are not declared inside the function - therefore the function can't parse them in $template unless I put them in the global scope - which I'm not sure I want to do. That or have an array of variables as a parameter in the function (which sounds even more tedious but possible).
Does anyone have any solutions other than using the code from the function (it is only a one-liner) in my code, rather than using the function?
Thanks,
Ross
P.s. I know about Smarty and the vast range of templating engines out there - I'm not looking to use them so please don't suggest them. Thanks!
Rather than run through your loop you can use include($template_name).
Or, if you want the content of the output from the template, you can do something like this:
$template_name = 'template.php';
// import the contents into this template
ob_start();
include($template_name);
$content = ob_get_clean();
// do something with $content now ...
And remember, in your template, you can use the often overlooked PHP syntax:
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Alternative syntax is available for if, while, for, foreach and switch ... perfect for manipulating the data in your template. See "Alternative syntax for control structures" for more details.
I'd pass an associative array with variables to replace, then extract() them.
Then you could also pass $_GLOBALS to achieve the same result.
function output_template($template, $vars) {
extract($vars);
eval('return "' . $template . '";');
}
Edit: you might also want to consider string subtitution instead of eval, depending on who's allowed to write your templates and on who specifies which template to load. Then there might be a problem with escaping, too...
Also, expanding on davev's comment eval is a bit ugly.
If you can do something like
function inc_scope( $file , $vars )
{
extract($vars);
ob_start();
require($file);
return ob_get_clean();
}
Then you get to use plain-old-php as your templating language, and you don't get any evil-evals, and "extract" + buffering merely limits the visible scope of the php code in the require.
Create file
config.php
index.php
Create folder
inc
template/default/controller/ main files here home.php, login.php, register.php, contact.php, product.php ...
headet.tpl and footer.tpl include home.php file.
main dir /template/default
config.php code here
/* semu design */
// HTTP URL
define('HTTP_SERVER', 'http://localhost/1/');
// HTTPS URL DISABLE
// define('HTTPS_SERVER', 'http://localhost/1/');
// DİZİNLER
define('DIR_INC', 'C:\wamp\www\1/inc/');
define('DIR_TEMLATE', 'C:\wamp\www\1/template/default/');
define('DIR_MODULES', 'C:\wamp\www\1/template/default/module/');
define('DIR_IMAGE', 'C:\wamp\www\1/image/');
define('DIR_CACHE', 'cache'); // [php cache system turkish coder][1]
// DB
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '123');
define('DB_DATABASE', 'default');
define('DB_PREFIX', '');
index.php code here
<?php
// Version
define('VERSION', '1.0');
// Config file
if (file_exists('config.php')) {
require_once('config.php');
}
// Moduller
require_once(DIR_INC . 'startup.php'); // mysql.php db engine, cache.php, functions.php, mail.php ... vs require_once code
// Cache System
//$sCache = new sCache();
/*$options = array(
'time' => 120,
'buffer' => true,
'load' => false,
//'external'=>array('nocache.php','nocache2.php'), // no cache file
);
$sCache = new sCache($options);*/
// page
$page = isset($_GET['page']) ? trim(strtolower($_GET['page'])) : "home";
$allowedPages = array(
'home' => DIR_TEMPLATE.'controller/home.php',
'login' => DIR_TEMPLATE.'controller/login.php',
'register' => DIR_TEMPLATE.'controller/register.php',
'contact' => DIR_TEMPLATE.'controller/contact.php'
);
include( isset($allowedPages[$page]) ? $allowedPages[$page] : $allowedPages["home"] );
?>
index.php?page=home
index.php?page=login ...
Active class code
<ul>
<li <?php if ( $page == 'home' ) echo 'class="active"'; ?> Home </li>
<li <?php if ( $page == 'login' ) echo 'class="active"'; ?> Login </li>
</ul>
And Token system coming :
index.php?page=home&token=Co54wEHHdvUt4QzjEUyMRQOc9N1bJaeS
Regards.