I hit a strange problem with PHP and its require_once language construct.
I require file called EN-en.php. It contains the English language for my website, I wrote it like this:
....
$lang['header']['loginbox']['menu'][1] = "contacts" ;
$lang['header']['loginbox']['menu'][2] = "settings" ;
....
Then I user this code to include my file in the whole site
require_once $langFile ;
Very easy I think, $langFile is = "/var/www/webstite/langs/EN-en.php". But here's come the strange part.
When I use
echo $lang['header']['loginbox']['menu'][1];
It prints something like "Gontacts" ... I can't understand why, and it's not the only case.. Please someone can help me with this issue?.
You are probably overwriting your own values in the array.
See this simple example:
$test = "some text";
$test['menu'] = 'extra';
var_dump($test);
// produces: string(9) "eome text"
// the first character - $test[0] - gets overwritten
Related
I have a PHP file as seen below that is a config file.
When I use return in my code and var_dump(include 'config.php');
I see an array, but when I delete return the result is
int 1
Does include work like a function in this case? And why I have to use return here?
<?php
return array(
'database'=>array(
'host'=>'localhost',
'prefix'=>'cshop_',
'database'=>'finalcshop',
'username'=>'root',
'password'=>'',
),
'site'=>array(
'path'=>'/CshopWorking',
)
);
The return value of includeis either "true"(1) or "false". If you put a return statement in the included file, the return value will be whatever you return. You can then do
$config = include config.php';
and $configwill then contain the values of the array you returned in config.php.
An include fetches PHP-code from another page and pastes it into the current page. It does not run the code, until your current page is run.
Use it like this:
config.php
$config = array(
'database'=>array(
'host'=>'localhost',
'prefix'=>'cshop_',
'database'=>'finalcshop',
'username'=>'root',
'password'=>'',
),
'site'=>array(
'path'=>'/CshopWorking',
)
);
And in your file, say index.php
include( 'config.php' );
$db = new mysqli(
$config['database']['host'],
$config['database']['username'],
$config['database']['password'],
$config['database']['database'] );
This way, you do not need to write all that stuff into every file and it is easy to change!
Here are some statements with similarities:
include - insert the file contents at that point and run it as if it were a part of the code. If the file does not exist, it will throw a warning.
require - same as include, but if the file is not found an error is thrown and the script stops
include_once - same as include, but if the file has been included before, it will not do so again. This prevents a function declared in the included file to be declared again, throwing an error.
require_once - same as include_once, but throws an eeror if the file was not found.
First off, include is not a function; it is a language construct. What that means is something you should Google for yourself.
Back to your question: what include 'foo.php does is literally insert the content of 'foo.php' into your script at that exact point.
An example to demonstrate: say you have two files, foo.php and bar.php. They look as follows:
foo.php:
<?php
echo "<br>my foo code";
include 'bar.php';
$temp = MyFunction();
bar.php:
<?php
echo "<br>my bar code";
function MyFunction()
{
echo "<br>yes I did this!";
}
This would work, because after evaluating the include statement, your foo.php looks like this (for your PHP server):
<?php
echo "<br>my foo code";
echo "<br>my bar code";
function MyFunction()
{
echo "<br>yes I did this!";
}
$temp = MyFunction();
So your output would be:
my foo code
my bar code
yes I did this!
EDIT: to clarify further, if you create variables, functions, GLOBAL defines, etc. in a file, these will ALL be available in any file in which you include that file, as if you wrote them there (because as I just explained, that is basically what PHP does).
I have a file like this
**buffer.php**
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
ob_end_flush();
Everything inside the buffer is dynamically made with data from the database.
And inserting php into the database is not an option.
The issue is, I got my output buffer and i want to replace '{replace}' with a working php include, which includes a file that also has some html/php.
So my actual question is: How do i replace a string with working php-code in a output-buffer?
I hope you can help, have used way to much time on this.
Best regards - user2453885
EDIT - 25/11/14
I know wordpress or joomla is using some similar functions, you can write {rate} in your post, and it replaces it with a rating system(some rate-plugin). This is the secret knowledge I desire.
You can use preg_replace_callback and let the callback include the file you want to include and return the output. Or you could replace the placeholders with textual includes, save that as a file and include that file (sort of compile the thing)
For simple text you could do explode (though it's probably not the most efficient for large blocks of text):
function StringSwap($text ="", $rootdir ="", $begin = "{", $end = "}") {
// Explode beginning
$go = explode($begin,$text);
// Loop through the array
if(is_array($go)) {
foreach($go as $value) {
// Split ends if available
$value = explode($end,$value);
// If there is an end, key 0 should be the replacement
if(count($value) > 1) {
// Check if the file exists based on your root
if(is_file($rootdir . $value[0])) {
// If it is a real file, mark it and remove it
$new[]['file'] = $rootdir . $value[0];
unset($value[0]);
}
// All others set as text
$new[]['txt'] = implode($value);
}
else
// If not an array, not a file, just assign as text
$new[]['txt'] = $value;
}
}
// Loop through new array and handle each block as text or include
foreach($new as $block) {
if(isset($block['txt'])) {
echo (is_array($block['txt']))? implode(" ",$block['txt']): $block['txt']." ";
}
elseif(isset($block['file'])) {
include_once($block['file']);
}
}
}
// To use, drop your text in here as a string
// You need to set a root directory so it can map properly
StringSwap($text);
I might be misunderstanding something here, but something simple like this might work?
<?php
# Main page (retrieved from the database or wherever into a variable - output buffer example shown)
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
$main = ob_get_clean();
# Replacement
ob_start();
include 'whatever.php';
$replacement = ob_get_clean();
echo str_replace('{replace_me_with_working_php_include}', $replacement, $main);
You can also use a return statement from within an include file if you wish to remove the output buffer from that task too.
Good luck!
Ty all for some lovely input.
I will try and anwser my own question as clear as I can.
problem: I first thought that I wanted to implement a php-function or include inside a buffer. This however is not what I wanted, and is not intended.
Solution: Callback function with my desired content. By using the function preg_replace_callback(), I could find the text I wanted to replace in my buffer and then replace it with whatever the callback(function) would return.
The callback then included the necessary files/.classes and used the functions with written content in it.
Tell me if you did not understand, or want to elaborate/tell more about my solution.
I have a php page that is reading from a file:
$name = "World";
$file = file_get_contents('html.txt', true);
$file = file_get_contents('html.txt', FILE_USE_INCLUDE_PATH);
echo $file;
In the html.txt I have the following:
Hello $name!
When I go to the site, I get "Hello $name!" and not Hello World!
Is there a way to get var's in the txt file to output their value and not their name?
Thanks,
Brian
The second param of file_get_contents has nothing to do with how to interpret the file - it's about which pathes to check when looking for that file.
The result, however, will always be a complete string, and you can only "reinterpolate" it with evial.
What might be a better idea is using the combination of include and output control functions:
Main file:
<?php
$name = "World";
ob_start();
include('html.tpl');
$file = ob_get_clean();
echo $file;
html.tpl:
Hello <?= $name ?>
Note that php tags (<?= ... ?>) in the text ('.tpl') file - without it $name will not be parsed as a variable name.
One possible approach with predefined values (instead of all variables in scope):
$name = "World";
$name2 = "John";
$template = file_get_contents ('html_templates/template.html');
$replace_array = array(
':name' => $name,
':name2' => $name2,
...
);
$final_html = strtr($template, $replace_array);
And in the template.html you would have something like this:
<div>Hello :name!</div>
<div>And also hi to you, :name2!</div>
To specifically answer your question, you'll need to use the 'eval' function in php.
http://php.net/manual/en/function.eval.php
But from a development perspective, I would consider if there was a better way to do that, either by storing $name somewhere more accessible or by re-evaluating your process. Using things like the eval function can introduce some serious security risks.
When we are using HTML + PHP, say we want to output something like "Skill5" where "5" is load from php variable $number, we can do the following thing:
Skills<?php echo $number;?>
However, right now I want to do the same thing in PHP, I have a sentence like the following:
if($skills and $skills->skill5){
}
Where I want to load the number 5 from $variable $number too.
So I tried the following thing:
if($skills and $skills->skill.$number){
}
However, this is not working. this $number is working as "null" here even it's set to 5.
Any ideas?
Thank you very much!
Lets say $skills->skill = foo and $number = 5;
$skills->skill.$number
Would return foo5
Do it like this instead:
$pubVar = 'skill' . $number;
$skills->$pubVar
So you actually pull the skill5 public var.
Depending on the current page, I would like to change the css of the chosen menu module and make others different, etc. All that while building dynamically the page before loading.
My problem is that I have a serie of variables going by this structure :
$css_(NAME_OF_MODULE)
To know what variable must be set , I have another variable I received in parameters of this functions, called
$chosen_menu
Say $chosen_Menu = "C1", I would like to add content to $css_C1. Thus, what I want is to create a variable name out of 2 variables, named $css_C1
I have tried :
${$css_.$chosen_menu} = "value";
But it doesnt seem to work. Any clue ?
That probably won't just work. PHP supports full indirection though, so something like this will work.
$varName = $css."_".$chosen_menu;
$$varName = "value";
If not, it will probably be attempting to interpret $css_ as a variable name in your second code sample, so just change that to $css."_".$chosen_menu.
$nr = 1;
${'name' . $nr} = 20 ;
var_dump($name1);
Check out http://php.net/manual/en/language.variables.php
You should be able to use:
$menu = $css . '_' .$chosen_menu;
$$menu = 'some value';
or
${$menu} = 'some value';
I'm not sure if I get you right, but how about this:
${$css."_".$chosen_menu} = "value";