Editing a PHP File, with another php file, using Fwrite - php

My last question wasn't explained very well.
What I'm trying to do here is insert data into a PHP File, Using the fwrite feature on another .php file.
To keep this simple, I'm labelling the one I want data inserted as file.php and the one I'm using fwrite to execute on, is edit.php
Now, I got the writing thing down, what my problem is, is I need to INSERT that data, Before the closing php tag on file.php.
What I tried doing was, deleting the closing php tag, writing the data, and then rewriting the tag.
Here is my source code for that:
<?php
$rows = file("file.php");
$tagremove = "?>";
foreach($rows as $key => $row) {
if(preg_match("/($tagremove)/", $row)) {
unset($rows[$key]);
}
}
file_put_contents("file.php", implode("", $rows));
$User = $_GET["user"];
$File = "file.php";
$Handle = fopen($File, "a");
fwrite($Handle, "");
fwrite($Handle, $User);
fwrite($Handle, "\r\n");
fwrite($Handle, "?>");
print "Data Written";
fclose($Handle);
?>
When I run this on Edit.php, it inserts that data into the file, but its only writing to the first line, and replacing whatever is already there. (In my case its the opening php tag). I don't know what I'm doing wrong, or if there is another way to do this, but any assistance would be appreciated.
Edit: this is again for a chat client.
I'm having a file, that sends a message into a .txt file that the client then reads.
And that file is reading file.php (staff.php) to check if the user submitting is a staff member.
If it comes up true that the user is a staff member, then it changes the username variable in the send.php.
And so far, the send.php has only sucessfully, included the Staff.php, I've tried staff.txt, and the reason is, php code is in the staff.php.

Try this:
$data="echo 'hello world!';";
$filecontent=file_get_contents('file.php');
// position of "?>"
$pos=strpos($filecontent, '?>');
$filecontent=substr($filecontent, 0, $pos)."\r\n".$data."\r\n".substr($filecontent, $pos);
file_put_contents("file.php", $filecontent);
Please don't forget, that you need to check data from user.

Ok much better alternative use a data file. Ill use json because its easy to use an very easy to parse by human eyes as well:
// read file
$data = file_get_contents('data.json');
$json = json_decode($data, true);
// manipulate data
$json['users'][] = $_GET['user'];
// write out file
$dataNew = json_encode($json);
file_put_contents('data.json', $dataNew);
the reason is, php code is in the staff.php
Well this isnt something you workaround. You should be writing/reading this kind of information form a data stor - that could be a file or a database... but not an actual script.

Related

php - Pass contents of file to function that's expecting a filename

I have the contents of a file in a string. I need to pass this file to a function where the function is expecting the parameter to be the name of the file, not the contents. The obvious and probably simplest way to do this would be to write the contents to a temp file, then pass that file name to the function, and unlink the file once I'm finished.
However, I'm looking for a solution that doesn't involve writing the file out to the file system and then reading it back in. I've had a need for this in multiple cases, so I'm not looking for a work-around to a specific function, but more of a generic method that will work for any function expecting a file name (like file_get_contents(), for instance).
Here are some thoughts, but not sure how to pursue these yet:
Is it possible to write the contents somewhere in memory, and then
pass that to the function as a filename? Perhaps something using
php://memory.
Is it possible to write the contents to a pipe, then pass the name of the
pipe to the function?
I did a short proof-of-concept trying with php://memory as follows, but no luck:
$data = "This is some file data.\n";
file_put_contents( 'php://memory', $data );
echo file_get_contents( 'php://memory' );
Would be interested in knowing of good ways to address this. Googling hasn't come up with anything for me.
It mainly depends on what the target function does with the file name. If you're lucky, you can register your own stream wrapper:
stream_wrapper_register('demo', 'DemoStream');
$data = "This is some file data.\n";
$filename = 'demo://foo';
file_put_contents($filename, $data );
echo file_get_contents($filename);
Why not use a file in the /tmp/ directory? Like this:
<?php
$filename = '/tmp/mytmpfile';
$data = "This is some file.\n";
file_put_contents($filename, $data);
$result = file_get_contents($filename);
var_dump($result);
Well, as you say you don't want to use a file, you shouldn't use file_get_contents().
But you can achieve the same result by using stream_get_contents(), like this:
<?php
$data = "This is some file data.\n";
$handle = fopen('php://memory', 'r+'); // open an r/w handle to memory
fputs($handle, $data); // write the data
rewind($handle); // rewind the pointer
echo stream_get_contents($handle); // retrieve the contents

php User registration system without mysql database

I want to create a registration system on my site where only limited users will be able to create their account. I want to use a .txt file for storing usernames and passwords.
I have the following code so far :
$uname=$_POST['usr'];
$pass=$_POST['pwd'];
if(empty($_POST["ok"])){echo "Could not insert data!";}
else
{$file=fopen("user.txt","w");
echo fwrite($file,$uname);
fclose($file);}
This receives the user data from a form and puts it in user.txt file.
My problem is that when new data is inserted to txt file the old data get deleted.
I want to keep the data in txt file like
foo:12345~bar:1111
username and password are seprated by : and new user is seprated by ~ ,later I will use regex to get the data from txt file.
How can i correct my code to keep both new and old data?
You need to open file in append mode
http://php.net/manual/en/function.fopen.php
<?php
$uname = $_POST['usr'];
$pass = $_POST['pwd'];
if (empty($_POST["ok"])) {
echo "Could not insert data!";
} else {
$file = fopen("user.txt", "a");
$srt="foo:".$uname."~bar:".$pass;// create your string
echo fwrite($file, $srt);
fclose($file);
}
If we want to add on to a file we need to open it up in append mode.
So you need to change from write only mode to append mode.
$file=fopen("user.txt","a");
To answer your question: you have to explicitly pass $mode argument to fopen() function equals to 'a'.
However, it looks like a bad idea to use plain files for this task. Mainly because of concurent writes troubles.
This is really a bad choice: there are a lot of drawbacks for security, for read/write times, for concurrent requests and a lot more.
Using a database isn't difficult, so my suggestion is to use one.
Anyway, your question is asked yet here: php create or write/append in text file
Simple way to append to a file:
file_put_contents("C:/file.txt", "this is a text line" . PHP_EOL, FILE_APPEND | LOCK_EX);

Php problem eval/html/php

I've been writing a php/html page encoder/decoder... I know it already exists but it's a university project so go on XDDD
I encode the pages that I want to protect let's say hypothetically with base64_encode and when I receive a request of any pages I have a loader that reads the coded page, decrypts it and with eval executes it. The real problems arise when I try to decrypt and execute a mixed php/html page. Obviously eval can't execute html code so my question is do I really become crazy about splitting the page executing the php code and print the html? And also if I include an encoded php or php/html page do I really have to reuse the method up here?
I hope someone can really help me because i have a week left before the deadline and I can't change the project at this point.
chris here the function and the fisrt calling in $param[0] i've got the filename called
function MyInclude($filename)
{
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($temp_filename , 'w+');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
$tmp=file_get_contents($filename);
$data=MCrypt_Decode($tmp,'PFL_EPU_V100_mia');
fwrite($handle,$data );
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
}
MyInclude($param[0]);
the $param[0] file here
<?php
session_start();
$_SESSION['title']='Home';
MyInclude("header.php");
?>
<body>
sono il body <?php echo APP_PATH; ?>
</body>
<?
echo "boss";
MyInclude("footer.php");
?>
any idea about it??? or you need some other code??? let me know T_T
Mike
You can eval() a string that contains mixed html and php, just so long as the tags are included.
http://php.net/manual/en/function.eval.php
When eval() encounters a php close tag (?>), it will stop trying to treat it as php code and just echo everything out until it comes to a php open tag.
The typical solution to your problem is something like this:
$file = ... //Your decoded php/html code here
$file = '?>' . $file; //Add a close tag to the beginning;
ob_start();
eval($file);
$output = ob_get_clean();
echo $output; //Or do something else with it... really, if you're
//just going to be echoing it you can skip the output buffering
Is it possible to decrypt the page, write it to a file, then include it? That would let the PHP interpreter do what it does best - interpret PHP documents. That will include HTML/PHP combinations without relying on eval.
The outline of that would be:
// create the temp file
$temp_filename = "tmp.php";
$handle = fopen($filename , 'w');
if (!$handle)
die('Error creating temp file');
// write the decrypted data, close the handle
fwrite($handle, $decrypted_data);
fclose($handle);
// start output buffering to contain any output the script creates
ob_start();
try {
include_once($temp_filename);
} catch (Exception $e) {
die('There was an error in the encrypted file, cannot process');
}
// get the output, clear the buffer
$output = ob_get_contents();
ob_end_clean();
//destroy the temp file
unlink($temp_filename);
// now you can output the buffer, if desired:
echo $output;
Function references
fopen: http://us2.php.net/manual/en/function.fopen.php
fwrite: http://us2.php.net/manual/en/function.fwrite.php
fclose: http://us2.php.net/manual/en/function.fclose.php
ob_start: http://us2.php.net/manual/en/function.ob-start.php
ob_get_contents: http://us2.php.net/manual/en/function.ob-get-contents.php
ob_end_clean: http://us2.php.net/manual/en/function.ob-end-clean.php
unlink: http://www.php.net/manual/en/function.unlink.php
You will need dump the decoded file to another file and include(); it. The eval approach will not work because it will exit with a parse error if the first item in the file is not either an opening <?php tag, or a valid bit of PHP code.
More than this, you will need to find/replace any occurences of include(), require(), include_once(), and require_once() within the encrypted file with a different function, to ensure you don't try to execute another encrypted file before it has been decrypted. You could do this at execution (ie decryption) time, but it would be much better to it a encryption time, to minimise the time required to pre-fetch the code before it is executed.
You can define these customised functions to decrypt a file and include/require it in your loader script.
Your problem description is a bit vague however your problem seems to be solvable with output buffering.
Have you tried decrypting the page, then parsing the text to split out anything between and then only executing that code?

PHP: Is there a correct method for saving configuration data?

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.

php Logging Issues

Code works fine, except for the fact that there is a problem here:
//Log Events
function logEvent($newinput) {
if ($newinput !== NULL) {
// Add a timestamp to the start of the $message
$newinput = date("Y/m/d H:i:s").': '.$newinput;
$fp = fopen('log.txt', 'w');
fwrite($fp, $newinput."\n");
fclose($fp);
}
}
//Problem writing these two lines to log.txt?
//The bad, the two lines below are not on the log.txt
logEvent('Selection'.$selections[$selection]);
logEvent('Change' . $change. 'cents.');
//This line is written to a text file (log.txt), okay that's good.
logEvent('Input' . $newinput);
i think you're not appending to the file, you're rewriting it. try fopen with 'a' instead of 'w'.
You need to use the append modifier when opening the file, you've gone
fopen('log.txt', 'w');
this means that every time you call that function, the log file is getting blown out and recreated, if you instead used
fopen('log.txt', 'a');
then your new log entries will append to the file instead.
You could also look into keeping the file open for later inserts too, but there may be issues with multiple updates in other requests.

Categories