PHP Include an Array - php

I am creating a flat file login system for a client (as their IT team does not want to give us a database)
I have worked off this:Easy login script without database which works perfect however...
I need to add a large list of logins and wanted to include them in a septrate file rather than in that script.
I have something like this:
<?php
session_start();
// this replaces the array area of the link above
includes('users.php');
//and some more stuff
?>
And in the users file I have
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
However it just literally outputs the text from that file. Is there a way I can include it so it just runs like it was in the main script?
Cheers :)

Include in PHP works simply like a reference to other piece of code AND any other content. So you should enclose the contents of the file in the <?php tags so it would be parsed as PHP.
You may as well return anything from an included file (I mention this as this in your case is the best solution):
mainfile.php
<?php
session_start();
// this replaces the array area of the link above
$userinfo = include('users.php');
users.php
return array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);

The statement name is actually include, and not includes.
Try the following:
include 'users.php';
And if your code is getting outputted as text, then it's probably because you've missed the opening <?php tags. Make sure they're present.
users.php should look something like this:
<?php
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
However, the closing tag is not a requirement and your code will work fine without it.

In Yii framework (configs for exmaple) it's done like this
$users = include('users.php');
users.php:
<?php
return array(
'user1' => array(...),
'user2' => array(...),
);

Make sure you have an opening PHP tag in the included file:
<?php
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);

users.php :
<?php
function getUsers(){
return array(
'user1' => array(...),
'user2' => array(...),
);
}
Some bootstrap file
include('users.php');
$myUsers = getUsers();

Related

change variable value in a file in php

I have a file which is a small place_config.php file.
Take this as an example where i am setting my variables
<?php
//config file
$place_config = array(
'credentials' => array(
'sid' => 'some_value',
'token' => 'some_token'
)
?>
I want to change the sid and token from the admin panel of the user for the ease. How can i effectively achieve this. One solution which i understand is to make the content of the file in a string with the variables of $_REQUEST placed after the post request write that whole string to the file? Is it a effective approach?
Submit a form with the proper inputs and when submitted call update_place_config():
function update_place_config() {
include('place_config.php');
$place_config['credentials']['sid'] = $_POST['sid'];
$place_config['credentials']['token'] = $_POST['token'];
$output = '<?php $place_config = ' . var_export($place_config, true) . '; ?>';
file_put_contents('place_config.php', $output);
return $place_config; //if you want to get the new config
}
Another option:
$content = file_get_contents('place_config.php');
$content = preg_replace("/('sid' =>) '[^']+'/", "$1 '{$_POST['sid']}'", $content);
file_put_contents('place_config.php', $content);
I personally would store in a database or use JSON if it needs to be a file.
Instead of storing the configuration data in a php file, I'll recommend storing them in a json file which can be easily read/edited through php.
Create a json file, let's say config.json. Then you can load the configuration using $conf = json_decode(file_get_contents("config.json")). You can make changes to the $conf object and save back the configurations as file_put_contents("config.json", json_encode($conf)).

Does include work like a function in php?

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).

Is it possible rewrite php file using fwrite without removing php comments?

I have some php file and it contains some comments.
<?php
$test = array(
'LBL_TEXT' => 'text',//test comment
'LBL_FOO' => 'foo'
);
Now I need to update 'LBL_TEXT' value(text) above file without removing comment('//test comment'). Is it possible using fwrite() or some other way.
So you will need something like
<?php
$data = file_get_contents("foo.php");
$data = so something clever to automatically change string as desired;
file_put_contents("foo.php",$data);
?>

A template which is filled up by some variables (in PHP Web Forms)

How can I have a template which is filled by some variables in Web Forms?
I already coded MVC applications; but now I have a project which is not MVC (it is just a web form); in MVC I could do the following for a template which is filled by some variables; can I do the sam ein web forms too?
My code in MVC Codeigniter is as following;here my email_tempale file is a temple in which I get my variables which are; I'm looking for the equivalent in PHP Web Forms:
$mailData = array
(
'firtName' => $firtName,
'lastName' => $lastName,
);
$msg = $this->load->view('email_template', $mailData, TRUE);
Many thanks in advance!
I suggest you have a template file too, so I think you can try this :
$mailData = array
(
'firtName' => $firtName,
'lastName' => $lastName,
);
require_once "your template file path";
Then in your template file, put following lines in right place :
<?php echo $mailData['firstName']; ?>
<?php echo $mailData['lastName']; ?>
If you want to get the content of your template with rendered variables instead of its output, you can try this -
ob_start();
require_once "your template file path";
$msg = ob_get_contents ();
ob_end_clean ();
It could work, but I never tested it.

Strange behavior when returning a value from an include

I am having a strange issue with getting an array returned from an include. The example taken from the manual shows the behavior I am expecting:
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
// This is the expected behavior.
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
My usage scnario gives different result. I load Zend_Config by calling it with a simple include that returns an array() :
config.php
<?php
/*
* Configuration options loaded in Zend_Config
*/
return array(
'localDB' => array('serverName' => 'TESTDB',
'uid' => 'TESTUSER',
'pwd' => 'TESTPW',
'DB' => 'TESTDB'
),
);
// in the app I can call Zend_config somewhat like this ...
$configfile = 'config.php';
// zend_config takes an array as parameter, returned by the included file...
$config = Zend_config(include $config);
All is fine. Except now I want to overide this array for test configuration, without changing the file, so I do this:
testConfig.php
$testsettings = include_once 'config.php';
// override the array
$testsettings['localDB']['serverName'] = "TEST";
//return the overriden array
return $testsettings;
Now, the weird part. It all works fine when I execute php -f testConfig.php and var_dump() $testsettings.
But if I include this file in a testcase to have orverriden settings value, the result is always a (bool) true, like the example include shown at top with no return value set.
I have thought of a few workarounds for this, but was wondering out of curiosity if anyone had a clue as to why it does this.
include_once returns true every time after the first one. So the line
$testsettings = include_once 'config.php';
sets $testsettings to true if you've included config.php anywhere in earlier code.
Perhaps it is not a bool, but a count of the array.
It's in the docs. Check out the section on Handling Returns - http://us2.php.net/manual/en/function.include.php. But basically - don't do this.

Categories