I wonder what ist he best way to do the following.
I am creating a webseite CMS. Through CMS I am creating new folders with index.php files in them. For example I have created folder with the site new_folder_name/index.php
I wonder what ist the best way to make an interaction between the created index.php files and database. For example I am creating the php file with another php file
<?php
$dir = "../new_folder_name";
$file_to_write = "index.php";
$content_to_write = '
<?php
//// php code
$foo=‘3‘:
?>
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
fwrite($file, $content_to_write);
fclose($file);
include $dir . '/' . $file_to_write;
?>
I am putting a variable $foo that needs to be changed with every new php file created. I could create $foo=GET(´SOEMTHING´) but this GET is making problems since this variable needs to be changed, and only for this file a unique value. I do not know if I explained it properly but I hope I did. In which way can I create a php file with specific $foo value or change the created file with php in order to get the $foo value which I want.
you can do
$content_to_write = '
<?php
//// php code
$foo=\'$_GET[\'something\']\';
?>';
this is make your new script to read $_GET['something']
OR
this example, read this script's $_GET['something'] and put it's value in script...
$content_to_write = '
<?php
//// php code
$foo=\''.$_GET['something'].'\';
?>';
since you use single quote $_GET didn't get parse with original script. If you want to use that simply concatenate it. Alternatively you can concatinate '$' in between string to make variable just variables.
Related
Good Day All
I have a .php file which I want to edit via fopen() and file_get_content() functions. However, my file contains some php codes as well and I managed to get the content out of my file but without the php part. Also, I have tried the eval() (I know it's not suggested!) function with same results. I was wondering if there could be a way to get whatever is inside that file regardless wether it's text or codes.
Thanks
Here is the code I used:
public function editwarning()
{
$filename = "http://www.parkho.ir/admin/templates/pm/email_warning.php";
$content = file_get_contents($filename);
echo $content;
}
You have two options:
1) pass the file PATH to the $filename var:
$filename = "/var/www/app/email_warning.php"; // <--- replace /var/www/app for your path
2) Or You need to use htmlentities():
<?php
$content = htmlentities(file_get_contents($filename));
echo $data;
I am trying to include a file if it exists, if the file doesn't exist i would like it to include another file instead.
I have the following code which seems to work correctly, The only problem with my code is if the file does exist then it displays them both.
I would like to only include
include/article.php
if
include/'.$future.'.php
doesn't exist.
if
include/'.$future.'.php
exists i don't want to include
include/article.php
<?php
$page = $_GET['include'];
if (file_exists('include/'.$future.'.php')){
include('include/'.$future.'.php');
}
else{
include('include/article.php');
}
?>
Your variable $future was never even defined, so how is it ever being included? I think you meant for $page and $future to be the same variable. Also including a file specified by the user in a get request doesn't make much sense to begin with, but is probably also a security risk.
Perhaps this is what you need?
Make sure any variable you're going to use IS defined before you'll
use the variable...
<?php
$page = ''; // show emptyness is there is nothing dome below
$page = isset($_GET['include']); // Do you have a variable in your URL that IS called "include" and is the include variable set? for example: http://www.example.com/index.php?include=....... you might want to check for empty value and write a default value as well but I didn't here ;)
// REMEMBER: $future must be defined BEFORE this line!
if (file_exists('include/' . $future . '.php') && is_file('include/' . $future . '.php')){ // file exists on server: true/false and is it a file or a directory? If Directory it will NOT be included as I used is_file()!
include('include/' . $future . '.php');
}elseif{
(file_exists('include/article.php') && is_file('include/article.php')){
include 'include/article.php';
}else{
echo 'WOW, No article found! You just found a error...<br />We will repair all errors ASAP! Thank you for visiting us...';
}
?>
I have a small app I am working on that generates configuration files. Because it may be used to generate a few different variants of configurations, I gather the variable values from the user, and then read in a template configuration from a file. That file has the names of the variables in it (i.e. $ip_address) at the proper positions. I have set those variables in my php code before reading and the printing out the files. However, the variable names are printed out, not the values of the variables:
$hostname = $_POST['username'] . "_891";
$domain = $_POST['username'] . ".local";
$routerFile = "891.txt";
$file_handle = fopen($routerFile, "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
print $line . "<br />";
}
Output example:
hostname $hostname
ip domain-name $domain
How do I get php to replace the variables names with their stored values?
I would go this way:
Create a template with hostname = <?php echo $hostname; ?> lines like so:
hostname <?php echo $hostname; ?>
ip domain-name <?php echo $domain; ?>
Then in PHP creating a template You would do:
ob_start();
include_once($routerFile);
$file_output = ob_get_clean();
Now You have the file template filled with the appropriate variables and You can save that file:
file_put_contents('my_new_router_file.txt', $file_output);
And You should be done.
You could use eval(), but that's not very safe, so I'd write a super simple regex replace.
$replaced = preg_replace_callback("/\b$\w+\b/",
function($match) use $hostname, $domain {
return $$match
},
$line);
However, I'd place the terms that need to be replaced inside of an associative array, otherwise your list of use will become a nightmare.
If you really want those files to be treated as PHP files and there is no security risk with them (they didn't come from an untrusted source) just include them.
I second alex answer.
Another possibility is to ditch the txt file, replace it with a php file and just include that.
When using the PHP include, how can I find out which file is calling the include? In short, what is the parent's file filename?
An easy way is to assign a variable in the parent file (before the inclue), then reference that variable in the included file.
Parent File:
$myvar_not_replicated = __FILE__; // Make sure nothing else is going to overwrite
include 'other_file.php';
Included File:
if (isset($myvar_not_replicated)) echo "{$myvar_not_replicated} included me";
else echo "Unknown file included me";
You could also mess around with get_included_files() or debug_backtrace() and find the event when and where the file got included, but that can get a little messy and complicated.
$fileList = get_included_files();
$topMost = $fileList[0];
if ($topMost == __FILE__) echo 'no parents';
else echo "parent is $topMost";
I think this should give the right result when there's a single parent.
By that I mean the situation where the parent is not a required or an included file itself.
Late answer, but ...
I check the running parent filename by using:
$_SERVER["SCRIPT_NAME"] // or
$_SERVER["REQUEST_URI"] // (with query string)
You could use debug_backtrace() directly with no additional changes from within the included file:
$including_filename = pathinfo(debug_backtrace()[0]['file'])['basename'];
This will give you the name of the file that's including you.
To see everything you have access to from within the included file, run this from within it:
print_r(debug_backtrace());
You will get something like:
Array
(
[0] => Array
(
[file] => /var/folder/folder/folder/file.php
[line] => 554
[function] => include
)
)
Got this from here: https://stackoverflow.com/a/35622743/9270227
echo "Parent full URL: ";
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';
I was searching same information on web for complement my online course about php and found two ways. The first was
$file = baseline($_SERVER['PHP_SELF']);
echo $file; //that outputs file name
BUT, in include or require cases it gets the final file that it's included or required.
Also found this, the second
$file = __FILE__;
echo $file; //that outputs the absolute way from file
BUT i just was looking for the file name.
So... I mix it up and it worths well!
$file = basename(__FILE__);
echo $file; //that outputs the file name itself (no include/require problems)
In the parent file, add this line before including the child file:
$_SESSION['parent_file'] = $_SERVER['PHP_SELF'];
And then in the child file, read the session variable:
$parent_file = $_SESSION['parent_file']
I have a config.inc file in a web application that I am building. It contains an array with configuration values for things like the MySQL database, etc. I would like these to be entered by using a simple form, that asks for the server, login/password for the database, etc, then these get written to the configuration file.
Is there a preferred method of doing this? I am not sure how to write to a file, and update an array.
You just want writing, correct? Is it a serialized array or is it parsed?
One way to read a config file is parse_ini_file(). I wouldn't necessarily call it preferred, but it's a method. You'd still need to write the file.
Another way would to write a "config.inc.php" and just include it in, to write it you'd just output actual PHP code (e.g. $var = "myval";).
This is a way you could write a simple "output" function that took an array of configuration values and output them as name=value, assuming $config was an associative array.
foreach ($config as $name => $value) {
$output .= $name . '=' . $value . "\n";
}
if (!file_put_contents($filename, $output)) {
die("Error writing config file.");
}
There's a lot of decent ways to do it. It's really based on your requirements. Does it need to be in a specific format or do you have leeway?
It is not recommended to modify PHP configuration files via your application, you should use CSV files or a database table.
In case you want to save it in a CSV file then I suggest you keep a CSV file for each configuration type (e.g CSV file for database configurations) and always overwrite the previous one using file_put_contents
Save data example:
$csvStructure = array("dbUser","dbPassword","dbHostname","dbPort"); // array used for both loading data and saving it
$csvData = array();
foreach ($csvStructure as $field) {
$csvData[] = $_POST[$field]; // so it'd get $_POST["dbUser"],$_POST["dbPasword"], etc..
}
file_put_contents("filename",implode("\t",$csvData));
Load data example:
$csvStructure = array("dbUser","dbPassword","dbHostname","dbPort"); // array used for both loading data and saving it
$dbConfig = array();
$csvData = explode("\t",file_get_contents("filename"));
foreach ($csvStructure as $key => $field) { // $key would have the location of the requested field in our CSV data (0,1,2, etc..).
$dbConfig[$field] = $csvData[$key]; // populate $dbConfig["dbUser"],$dbConfig["dbPasword"], etc..
}
I believe using an ini file is a wise option, because user, password, schema, paths, etc. are things that usually will be modified by hand, so using var_export isn't because modifying it by hand it's not so clean and may crash your application if you make a mistake in the PHP syntax.
But parsing big ini files can be expensive, so it would be OK to cache the ini with var_export() or serlialize(). It's a better choice, I think, and read the ini only when the cache file doesn't exists.
PHP has a dedicated function for this, its called var_export();
Just do:
file_put_contents("config.php",var_export($config,true));
Well, to write a file, fwrite() php function does exactly what you want. From its PHP.NET documentation page (see example below).
Now, on the question as to what to output to that file - I'm assuming that file will have to be included as a configuration .php file into the rest of the project. I'm imagining you'll do something like this - where you're creating strings with PHP code on the fly, based on the submitted form:
$strDatabaseConfig = "\$databaseConfig = array('" . $_POST['login'] . "," . $_POST['password'] . "');";
And here's the snippet for fwrite:
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
Here's one way: wp-admin/setup-config.php from WordPress.
I prefer to have a file with a bunch of define statements.
These are constants globally available (and of course immutable) which is what you need for configuration settings.
Constants offer better memory management and efficiency in reading as they don't need the extra memory required by a variable so that it can be changed.
Let's say your config.inc file looks like this:
$config = array(
'blah' => 'mmm',
'blah2' => 'www',
//...
);
You want to update it, so you create a simple form, fill text fields with current values. PHP script that overwrites current configuration could looks like this:
$newConfig = ...; // data from form - of course validate it first
$config = ...; // data from config.inc
$config = array_merge($config, $newConfig);
file_put_contents('config.inc', '<?php $config = ' . var_export($config, true));
And you're done.