how to creat php function to edit config.php - php

In a project, I need to load some basic config without database query, how to creat a function to edit this file.
config.php may like this:
<?php
define(DEBUG, TRUE);
define (LANG, 'en');
define(THEME, 'joy');
define(DB_NAME, 'cms');
define(DB_USER, 'root');
define(DB_PASSWORD, '000');
define(DB_HOST, 'localhost');
define(CACHE, '3600');
define(CLOSE, TRUE);
.....
ajax.php
$key = $_POST['key'];
$value = $_POST['value'];
function change_config($key,$value){
// how ?
}
if I want to change cache time, I can run change_config('CACHE','1800')
if I want to change debug value, I can run change_config('DEBUG',false)

You could always take the easy route and use runkit_constant_redefine
runkit_constant_redefine($key, $value);
But of course, constants were built to be static. Editing that file directly means properly sanitizing input, and rewriting the file from the top to bottom every time. If the file size doesn't change and nor does the constant value's length, then you can use fwrite to write at the exact block where it exists, but that's generally not a solution. That said, use a database. they're not hard to learn.
Edit
When I was referring to using a database, I was implying the settings other than the DB connection, which should be static, or should change using something like Environment Variables, not being edited manually.

You could do something like this:
<?php
$key = $_POST['key'];
$value = $_POST['value'];
require_once 'config.php';
function change_config($key,$value){
$newContent = "<?php \n
define(DEBUG, " . ($key == "DEBUG"?$value:DEBUG) . "); \n
define(LANG, '" . ($key == "LANG"?$value:LANG) . "'); \n
define(THEME, '" . ($key == "THEME"?$value:THEME) . "'); \n";
file_put_contents('config.php', $newContent);
}
Your overwriting the file with the new content. We create an string wich will hold the content of the NEW config.php file. The \n are for new lines.
Then we go past all the define lines and put them in the string. For the value we use an Ternary Operator. Simply said, that's an if statement which will check if the key is corresponding the define where building. If so we will put the new value in it. If not, we will enter the OLD CONFIG.php value.

Related

PHP creating folder with two variables gives wrong foldername

I'm trying to create a random foldername for upload of files.
The folderpath shall be like "receivedfiles/$name$date/". Instead i get this: "receivedfiles/ . 13.06.2016/". I really don't know what is wrong...
The variable $name is user input and can be e.g. "Simon" or "Simon Jensen" depending on what the user wants.
$d = date('d.m.y');
$varfoldername = "../receivedfiles/. $name . $d ./";
mkdir($varfoldername , 0777 , true);
$upload_folder = $varfoldername;
Thanks to great help i have removed the dots from code above, please see code below which only name the folder with the date.
$name = $_POST['name'];
$d = date('d.m.y');
$varfoldername = "../receivedfiles/$name$d/";
mkdir($varfoldername , 0777 , true);
$upload_folder = $varfoldername;
Solution: $name was first specified later in script. Moving that atop solved part of the problem. Changed folder path as above solved the rest - thank you all :)
. The problem was that this is code from send email form. The email is composed below and fileupload is above. So of course the variable wasn't know at that line. 
Extraordinarily, you've written the solution in the question
$varfoldername = "../receivedfiles/$name$date/";
since it's double-quoted php interprets $.. as variable and print its content
by the way, print $varfoldername to see what is the output
Well, the extra dots are there because you are not concatenating correctly. The 2nd line should be something like
$varfoldername = "../receivedfiles/" . $name . $d . "/";
or you could remove the dots inside your string since you are using double quotes for your folder name value.
First of all, you need to check whether the $name variable is not empty.
Then, use sprintf for creating the path. It provides more flexible formatting and helps you to get rid of redundant spaces/dots/etc. Try this:
$varfoldername = sprintf('../receivedfiles/%s%s/', $name, $d);

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

i need to get the name of a variable from a file

As the title said i need a way to set the variable name depending of what the name of the picture is (i got over 100 different pictures)
Since i got custom classes in another php file for each picture (like tags) like for example:
$picture1 = "hillside sunset";
$picture2 = "beach cyprus";
and so on, so i need to fetch each variable for each picture
Heres the current loop where the div class is going to be each pictures name ($PICTURENAME is just to define where this code goes and is irelevant codewise):
<?php
foreach (glob("img/*.jpg") as $filename)
{
$path = $filename;
$file = basename($path);
$file = basename($path, ".jpg");
echo '<div class="'.$PICTURENAME.'" id="'.$file.'"><img src="'.$filename.'"> '.$file.' </div>';
}
?>
Don't use 100+ variables. Using a database would make far more sense, but if you don't want to get into learning that (you should, though), using a data structure would still make far more sense.
You could create one array (and use it as a map), and have the filename as the key, and the value would be the tags.
In PHP, you can address a variable using another variable:
$name = "foo";
${$name} = "bar";
echo $foo; // prints "bar"
echo ${$name}; // the same as above
However, as Kitsune already recommended, you are better off using something else, e.g., an array.

How to save php config?

I have a standard config file: $variable = 'value';, but at the last moment came up to use the web interface to configure it. So what is the best way to read the file, find the value of variables and then resave the file again?
At the moment I have 2 ideas:
1) RegExp
2) Keep somewhere array example
Store all config values in an associative array like so:
$config = array(
'variable' => 'value'
);
For the web interface, you can easily loop over the entire array:
foreach($config as $key=>$value) { ... }
After making changes, loop over the array and write it back to the file. (You really should be using a DB for this, though).
When you include the file, you can either use it like this:
include('config.php');
echo $config['variable']
// or
extract($config);
echo $variable;
Note: If you extract, it will overwrite any variables by the same name you might have defined before extracting.
PS - To make it easier to read and write to and from a file, I would just use json encoding to serialize the array.
Use a db
If your config is user defined - it would be better to store the config in a database. Otherwise you have this "novel" problem to solve but also potentially introduce security problems. I.e. for any one user to be able to edit your config files - they must be writeable to the webserver user. That opens the door to injecting malicious code into this file from a web exploit - or simply someone with direct access to your server (shared host?) finding this writeable file and updating it to their liking (e.g. putting "<?php header('Location: my site'); die;" in it).
One config variable
If you must manage it with a config file, include the file to read it, and var_export the variables to write it. That's easiest to do if there is only one config variable, that is an array. e.g.:
function writeConfig($config = array()) {
$arrayAsString = var_export($config, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Allow partial updates
If you are changing only some variables - just include the config file before rewriting it:
function writeConfig($edits = array()) {
require 'config.php';
$edits += $config;
$arrayAsString = var_export($edits, true);
$string = "<?php\n";
$string .= "\$config = $arrayAsString;\n";
file_put_contents('config.php', $string);
}
Multiple config variables
If you have more than one variable in your config file, make use of get defined vars and loop on them to write the file back:
function writeConfig($_name = '', $_value) {
require 'config.php';
$$_name = $_value; // This is a variable variable
unset($_name, $_value);
$string = "<?php\n";
foreach(get_defined_vars() as $name => $value) {
$valueAsString = var_export($value, true);
$string .= "\$$name = $valueAsString;\n";
file_put_contents('config.php', $string);
}
}
The above code makes use of variable variables, to overwrite once of the variables in the config file. Each of these last two examples can easily be adapted to update multiple variables at the same time.

run php script and return data as a string

My php script needs to load contents from another file and then replace certain commands. Using the following code works on static pages:
$pageName = 'pages/' . $_REQUEST['url'] . '.php';
$pageContents = file_get_contents($pageName);
$IDCODE = $_SESSION['IDCODE'];
$sql = "SELECT * FROM members WHERE IDCODE = '$IDCODE'";
$qry = mysql_query($sql);
$OK = $qry ? true : false;
$arr = mysql_fetch_array($qry);
foreach ($arr AS $key => $val) {
$pageContents = str_replace('{' . $key . '}', $val, $pageContents);
}
however, what if the file to be processed was dynamic? IE it populates some text from the mysql database.
Will file_get_contents run the file or just read whats in it as a string?
If you run the link to the file via a webserver, it will be processed. If you link it directly, you will get the exact contents of the file.
Rather messy code.
$pageName = 'pages/' . $_REQUEST['url'] . '.php';
$pageContents = file_get_contents($pageName);
local file inclusion vulnerability here.
$OK = $qry ? true : false;
Why? Anywere you use the value of $OK you could equally use $qry. And you never use $OK again in the code shown.
There's no error checking, no comments in the code.
what if the file to be processed was dynamic?
WTF? Do you mean you want to re-process the output as PHP? Then you could 'eval($pageContents);' but beware of code injection vulnerabilities.
Or you want to apply your script to the output of a PHP scrpt? Then just pass the URL as the argument to file_get_contents() e.g.
file_get_contents('http://localhost/path/'
. basename($_REQUEST['url'] . '.php');
But really the invocation should be controlled better than this. Both are messy solutions - a templating solution should be just that. Go have a long hard look at (e.g.) smarty

Categories