PHP - fwrite PHP Data With Set Variables - php

I am trying to figure out how to fwrite into a .php file with variables given through $_POST, or $_GET, supplied by the user to set variables and such. So, how would I go about getting the below code to work so that instead of fwriting the code, insert a $_GET variable for example, or in the below description, being $derp.
<?php
$derp = "working!";
$something = '<?php echo "Well Thats {$derp}' ?>';
$file = fopen("worked.php","w");
if (fwrite($file,$something) > 0) {
echo "Fwrite Successful!";
}
fclose($file);
?>

Although this use case looks very weird the following should work:
$data = array('<?php');
foreach ($_REQUEST as $key => $value) {
$data[] = "\$$key = \"$value\";";
}
$data[] = '?>';
$data = join("\n", $data);
file_put_contents('/path/to/file.php', $data);
Beware: This code imposes several security risks.
WTF is going on here?
The above code iterates through all array elements of $_GET and $_POST, combined.
By that it creates an array of lines to be written to a file.
This array will then be join()ed into a string by using the NEWLINE ascii character as the glue.
Assuming this script is called with the following query string:
?foo=bar&bar=baz
The file /path/to/file.php will then contain (file_put_contents):
<?php
$foo = "bar";
$bar = "baz";
?>
The example above does not support nested query parameters like foo[bar]=baz.

Related

edit a php file array variable from another

i am trying to create some switches saved in other files, already tried to make it turn a text file into array but it didnt worked well since itdoesnt seem to even read the file properly and dont get anything from inside of it. now i got the idea of having php files that have the arrays and it can be changed by a main php file
this will be the entire switch file:
<?php
function getarray(){
$a = array(
'name_on' => 0,
'picture_on' = 0,
'custom_styling_on' = 0
);
return $a;
}
?>
and i would like to edit the values of the array from the main file, but i dont know exactly how.
but if someone know how to create an array from a text file it will work, but just remember i tried what the answer of other questions said to and didnt worked
as ADyson said
a json for an array will be way more useful, i have changed my code to,so if i press a button it will change the value:
<?php
function getvalues(){
$json = file_get_contents(__DIR__."\switch.json");
$arr = json_decode($json,true);
return $arr;
}
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['btn']))
{
setval('name',0);
}
function setval($key,$value){
$json = file_get_contents(__DIR__."\switch.json");
$arr = json_decode($json,true);
$arr[$key] = $value;
$jarr = json_encode($arr);
file_put_contents("switch.json",$jarr);
}
?>

PHP include HTML and echo out variable

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

How can I replace braces with <?php ?> in php file?

I wanna replace braces with <?php ?> in a file with php extension.
I have a class as a library and in this class I have three function like these:
function replace_left_delimeter($buffer)
{
return($this->replace_right_delimeter(str_replace("{", "<?php echo $", $buffer)));
}
function replace_right_delimeter($buffer)
{
return(str_replace("}", "; ?> ", $buffer));
}
function parser($view,$data)
{
ob_start(array($this,"replace_left_delimeter"));
include APP_DIR.DS.'view'.DS.$view.'.php';
ob_end_flush();
}
and I have a view file with php extension like this:
{tmp} tmpstr
in output I save just tmpstr and in source code in browser I get
<?php echo $tmp; ?>
tmpstr
In include file <? shown as <!--? and be comment. Why?
What you're trying to do here won't work. The replacements carried out by the output buffering callback occur after PHP code has already been parsed and executed. Introducing new PHP code tags at this stage won't cause them to be executed.
You will need to instead preprocess the PHP source file before evaluating it, e.g.
$tp = file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$tp = str_replace("{", "<?php echo \$", $tp);
$tp = str_replace("}", "; ?>", $tp);
eval($tp);
However, I'd strongly recommend using an existing template engine; this approach will be inefficient and limited. You might want to give Twig a shot, for instance.
do this:
function parser($view,$data)
{
$data=array("data"=>$data);
$template=file_get_contents(APP_DIR.DS.'view'.DS.$view.'.php');
$replace = array();
foreach ($data as $key => $value) {
#if $data is array...
$replace = array_merge(
$replace,array("{".$key."}"=>$value)
);
}
$template=strtr($template,$replace);
echo $template;
}
and ignore other two functions.
How does this work:
process.php:
<?php
$contents = file_get_contents('php://stdin');
$contents = preg_replace('/\{([a-zA-Z_][a-zA-Z_0-9]*)\}/', '<?php echo $\1; ?>', $contents);
echo $contents;
bash script:
process.php < my_file.php
Note that the above works by doing a one-off search and replace. You can easily modify the script if you want to do this on the fly.
Note also, that modifying PHP code from within PHP code is a bad idea. Self-modifying code can lead to hard-to-find bugs, and is often associated with malicious software. If you explain what you are trying to achieve - your purpose - you might get a better response.

Formatting XML in to JSON with PHP

I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:
<?php
$url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';
if(!$xml = simplexml_load_file($url))
{
die("No xml for you");
}
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
echo $line->Line['Name'];
echo $line->Status['Description'];
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));
?>
The problem is that you're not storing the name and description into the array.
Try this:
foreach ($xml->LineStatus as $line)
{
$linestatus[] = array('name' => $line->Line['Name']);
$linestatus[] = array('description' => $line->Line['Description']);
}
Demo!
The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.
$linestatus[] = array(
"name" => $line->Line['Name'],
"description" => $line->Status['Description']
);
You also need to use echo instead of print_r to actually emit the JSON.
You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:
$linestatus = array();
foreach ($xml->LineStatus as $line)
{
$linestatus[] = $line->Line;
}
header('Content-Type: application/json');
print_r(json_encode($linestatus));

Save output of $_SERVER to file

I use this :
<?php
foreach($_SERVER as $key => $value){
echo "<b>$key:</b> $value<br>\n";
}
?>
Which outputs in browser. Is there anyway to redirect output to file and hide it from the browser page ?
I would suggest something like:
<?php
foreach($_SERVER as $key => $value)
{
file_put_contents('the_file.txt', "<b>$key:</b> $value<br>\n", FILE_APPEND);
}
?>
Make sure that the_file.txt has write permissions.
Instead of echoing build an output to put in your file:
<?php
$in='';
foreach($_SERVER as $key => $value){
$in .= $key.' - '.$value.PHP_EOL;
}
//save it
file_put_contents('_SERVER.txt', $in);
?>
Also, Your not going to want to add any html tags.
To write a file you would want to use file_put_contents(). To generate a (human) readable representation of the contents of $_SERVER you should look into print_r() or var_export().
file_put_contents("/tmp/exported-server.txt", print_r($_SERVER, true));
using $s = print_r($_SERVER), $s = var_export($_SERVER) or even ob_start(); var_dump($_SERVER); $s = ob_get_clean(); makes sure you get a proper visualization of any value type. Your approach only works well for strings and numbers, but fails for arrays, objects, …

Categories