How to insert template in php file - php

I 've used the following code to create PHP file dynamically
$value = 5;
$file = $compname.'.php';
$file_pointer = fopen( $file, 'w' );
$string = '<?php $var = '. $value .' ?>';
fwrite( $file_pointer, $string );
fclose($file_pointer);
include($file);
echo $var;
Is it possible to insert template in that php file and the file name conatins spaces is it possible to remove those space and add "-"

As #ianhales mentioned, you can use str_replace() for replacing white-spaces in the name. If I understand your question correctly, you want to use a template file to generate the contents of the PHP file. To do that, I would do the following.
Create template.txt file
<?php
$var = #THEVAR#;
?>
Then you use the template:
<?php
...
$value = 5;
$template = file_get_contents('template.txt');
$template = str_replace("#THEVAR#", $value, $template);
$newFile = fopen($compname.'.php', 'w');
fwrite($newFile, $template);
fclose($newFile);
...

str_replace( ) will do your ' ' to '-' replacement. The rest of your question I don't understand.

Do you mean you want to have a pre made PHP file and change some stuff there?
You can use placeholders, for instance.
example
PHP FILE
<?php
$var = '[%%VAR1%%]';
?>
file editor:
//Change filename
str_replace(' ', '-', $compname);
//File "template editor"
$value = 5;
$file = file_get_contents($compname.'.php');
str_replace('[%%VAR1%%]',$value, $file);
file_put_contents($compname.'.php', $file);

You did not mention if you want your template file to be PHP parsed first. This method could do (or not):
function getTemplateContent($includeFile, $parsePhp = TRUE) {
$cont = '';
if ($parsePhp) {
try {
ob_start();
require($includeFile);
$cont = ob_get_contents();
ob_end_clean();
} catch (Exception $ex) {
$cont = '';
}
} else {
$cont = file_get_contents($includeFile); #
}
return $cont;
}
To include the template contents in the written file could be done like e.g.
$string = '<?php $var = '. $value . ';' . getTemplateContent($templateFile, TRUE/FALSE) . ' ?>'

Related

TXT file search and delete

A (simple) question.
I have a TXT file search script in PHP.
$search = $_GET["search"];
$logfile = $_GET['logfile'];
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
fclose($file);
Now what I want to do is delete all the text it finds in the TXT file.
I tried doing a str_replace but it didn't work.
Thanks for helping!
I think this will do the magic:
$file->ftruncate($file->ftell());
You need to gather the lines which doesn't contain the search term and you need to save the text in an array.
When you're done with the listing, you need to open the file in write mode (which will empty the file) and then write the text you gathered in the file.
Here's the code:
<?php
$search = isset($_GET["search"]) ? $_GET["search"] : '';
$logfile = isset($_GET['logfile']) ? $_GET['logfile'] : '';
$text_without_term_arr = array();
if(!empty($logfile) && !empty($search)){
// Read from file
$file = fopen($logfile, "r");
echo ' <head>
<title>Searching: ' . $search . '</title>
</head>';
while(($line = fgets($file))!== false){
if(stristr($line, $search)){
// Case insensitive search
echo '<font face="Arial">' . $line . '</font><hr/>';
} else {
// Search term not found in these lines
array_push($text_without_term_arr, $line);
}
}
fclose($file);
// Empty the file and write the text again without the search term
if(!empty($text_without_term_arr)){
$new_file = fopen($logfile, "w");
$content = implode("\n", $text_without_term_arr);
fwrite($new_file, $content);
fclose($new_file);
}
}
?>
You need another file handle to write the result out to:
$tempname=tmpname('/tmp','result');
$outfile=fopen($tempname,'w');
Next, use str_ireplace to remove the found text in each line:
$newline=str_ireplace($search, '', $line);
Then write the new line out to the out file:
fputs($outfile,$newline); // May need to send PHP_EOL too
Close the file off:
fclose($outfile);
And then rename the new file to the old filename:
rename($tempname,$logfile);

decoding eval(base64_decode))

I am trying to decode this code.
I know it can be done by changing eval to echo. But in this case its not working. Is i am making any mistake. This is my encoded_file.php code:
i have tried to change eval to echo but its not working file.
I also tried this decoder:
<?php
// Open and read the content of the encoded file into a variable
$file = file_get_contents('encoded_file.php');
// Strip php tags
$file = str_replace('<?php', "", $file);
$file = str_replace('<?', "", $file);
// Make sure to get rid of short tags....
$file = str_replace('?>', "", $file);
// Strip new lines
$file = str_replace("\n", "", $file);
// Add semi colon to get around a parsing issue.
$file = $file.';';
// Change the Eval function
$file = str_replace('eval', 'echo ', $file);
// Function to eval the new string
function deval()
{
global $file;
ob_start();
eval($file);
$contents = ob_get_contents();
ob_end_clean();
return($contents);
}
// Run the code thru once
$file = deval();
// Counter
$cnt = 1;
// Loop it till it's decoded
while(preg_match('/^\?><\?php eval/', $file))
{
$file = str_replace('?><?php eval', 'echo', $file);
$file = str_replace('?><?', "", $file);
$file = deval();
$cnt;
}
//clean up some tags
$file = str_replace('?><?php', "", $file);
$file = str_replace('?><?', "", $file);
echo $cnt,' iterations<br/><br/>';
echo $file;
?>
but it also not working well. Any solution how to decode it or what's wrong in my decoder code.
Here are the steps which are needed to decode this (note - I've renamed variables/functions for clarity):
1. We see that this script reads content of itself, so we can assume - we cannot change this file
so lets create new file with this content and change this file:
$encoded=file('another_file.txt');
2. Then we can change first eval to echo and all other evals should be commented:
here is first line:
echo base64_decode("aWYoIWZ1bmN0aW9uX2V4aXN0cygiWWl1bklVWTc2YkJodWhOWUlPOCIpKXtmdW5jdGlvbiBZaXVuSVVZNzZiQmh1aE5ZSU84KCRnLCRiPTApeyRhPWltcGxvZGUoIlxuIiwkZyk7JGQ9YXJyYXkoNjU1LDIzNiw0MCk7aWYoJGI9PTApICRmPXN1YnN0cigkYSwkZFswXSwkZFsxXSk7ZWxzZWlmKCRiPT0xKSAkZj1zdWJzdHIoJGEsJGRbMF0rJGRbMV0sJGRbMl0pO2Vsc2UgJGY9dHJpbShzdWJzdHIoJGEsJGRbMF0rJGRbMV0rJGRbMl0pKTtyZXR1cm4oJGYpO319");
this will give us:
if(!function_exists("getSubString"))
{
function getSubString($g,$b=0)
{
$a=implode("\n",$g);
$d=array(655,236,40);
if($b==0) $f=substr($a,$d[0],$d[1]);
elseif($b==1) $f=substr($a,$d[0]+$d[1],$d[2]);
else $f=trim(substr($a,$d[0]+$d[1]+$d[2]));
return $f;
}
}
3. Now we can remove first echo/eval and go to 2nd one:
here is 2nd line:
echo base64_decode(getSubString($encoded));
give us:
if(!function_exists("decodeCode"))
{
function decodeCode($a,$h)
{
if($h==sha1($a))
{
return(gzinflate(base64_decode($a)));
}
else
{
echo("Error: File Modified");
}
}
}
4. we can remove it and go to last eval:
here is it:
echo decodeCode(getSubString($encoded,2),getSubString($encoded,1));
and we see final code:
/**
* #site #####
* #copyright 2010
*/
include 'config.php';
$id=$_GET['id'];
if(isset($id))
{
header("Content-type: image/jpeg");
$url='http://#####/siteuploads/thumb/'.$id;
$path=pathinfo($url);
header('Content-Disposition: attachment; filename="'.$path['basename'].'"');
$img=imagecreatefromjpeg($url);
$red=imagecolorallocate($img,255,155,255);
imagestring($img,2,1,2,$site,$red);
echo imagejpeg($img);
}

Text file contents will echo but not return php

I've been working o this for the last few weeks and can't find an alternate route. What I need to do is return the contents of a text file after the file has been read. I have two different logs that use text files to log errors. The first log returns the correct variable that I ask for but for some reason, even though I use the exact same methods to call the variable, it doesn't return anything. If I echo the variable then the correct string is displayed but the variable returns nothing. Here is the function:
function GetNoticeLog($strDate){
$logdate = preg_replace("/[^0-9]/", "_", $strDate );
$strFileName = realpath('debuglogs/enotice_logs').'/ENOTICELOG_' . $logdate . '.txt';
if(is_readable($strFileName)){
$file = fopen($strFileName,"r");
$contents = fread($file, filesize($strFileName));
$fclose($file);
return nl2br($contents);
}
else if(!is_readable($strFileName)){
echo $strFileName." is unreadable";
}
}
Why does this function return the necessary string when executed in one function but has to be echoed to see content in the other is my question.
Try changing
$fclose($file);
to this
fclose($file);
I was able to get the code to work on my server. The only change I made here is the path to the file which is in the same directory as the PHP script.
<?php
function GetNoticeLog($strDate){
$logdate = preg_replace("/[^0-9]/", "_", $strDate );
//$strFileName = realpath('debuglogs/enotice_logs').'/ENOTICELOG_' . $logdate . '.txt';
$strFileName = "blah.txt";
if(is_readable($strFileName)){
$file = fopen($strFileName,"r");
$contents = fread($file, filesize($strFileName));
fclose($file);
return nl2br($contents);
}
else if(!is_readable($strFileName)){
echo $strFileName." is unreadable";
}
}
$stuff = GetNoticeLog("whatever");
echo $stuff;
?>

File manupulation search and replace csv php

I need a script that is finding and then replacing a sertain line in a CSV like file.
The file looks like this:
18:110327,98414,127500,114185,121701,89379,89385,89382,92223,89388,89366,89362,89372,89369
21:82297,79292,89359,89382,83486,99100
98:110327,98414,127500,114185,121701
24:82297,79292,89359,89382,83486,99100
Now i need to change the line 21.
This is wat i got so far.
The first 2 to 4 digits folowed by : ar a catergory number. Every number after this(followed by a ,) is a id of a page.
I acces te id's i want (i.e. 82297 and so on) from database.
//test 2
$sQry = "SELECT * FROM artikelen WHERE adviesprijs <>''";
$rQuery = mysql_query ($sQry);
if ( $rQuery === false )
{
echo mysql_error ();
exit ;
}
$aResult = array ();
while ( $r = mysql_fetch_assoc ($rQuery) )
{
$aResult[] = $r['artikelid'];
}
$replace_val_dirty = join(",",$aResult);
$replace_val= "21:".$replace_val_dirty;
// file location
$file='../../data/articles/index.lst';
// read the file index.lst
$file1 = file_get_contents($file);
//strip eerde artikel id van index.lst
$file3='../../data/articles/index_grp21.lst';
$file3_contents = file_get_contents($file3);
$file2 = str_replace($file3_contents, $replace_val, $file1);
if (file_exists($file)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
if (file_exists($file3)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
// replace the data
$file_val = $file2;
// write the file
file_put_contents($file, $file_val);
//write index_grp98.lst
file_put_contents($file3, $replace_val);
mail('info#', 'Aanbieding catergorie geupdate', 'Aanbieding catergorie geupdate');
Can anyone point me in the right direction to do this?
Any help would be appreciated.
You need to open the original file and go through each line. When you find the line to be changed, change that line.
As you can not edit the file while you do that, you write a temporary file while doing this, so you copy over line-by-line and in case the line needs a change, you change that line.
When you're done with the whole file, you copy over the temporary file to the original file.
Example Code:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
This part is just setting up the basics: The category, the IDs of the articles and then building the related strings.
Now opening the file to change the line in:
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
The file is locked so that no other process can edit the file while it gets changed. Next to that file, the temporary file is needed, too:
$temp = new SplTempFileObject(4096);
After setting up the two files, let's go over each line in $file and compare if it needs to be replaced:
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
Now the $temporary file contains already the changed line. Take note that I used UNIX type of EOF (End Of Line) character (\n), depending on your concrete file-type this may vary.
So now, the temporary file needs to be copied over to the original file. Let's rewind the file, truncate it and then write all lines again:
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
And finally you need to lift the lock:
$file->flock(LOCK_UN);
And that's it, in $file, the line has been replaced.
Example at once:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
$temp = new SplTempFileObject(4096);
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
$file->flock(LOCK_UN);
Should work with PHP 5.2 and above, I use PHP 5.4 array syntax, you can replace [111182297, ...] with array(111182297, ...) in case you're using PHP 5.2 / 5.3.

Byte Order Mark causing session errors

I have an PHP app with houndreds of files. The problem is that one or several files apparently have a BOM in them, so including them causes error when creating the session... Is there a way how to reconfigure PHP or the server or how can I get rid of the BOM? Or at least identify the source? I would prefer a PHP solution if available
The real solution of course is to fix your editor settings (and the other team members as well) to not store files with UTF byte order mark. Read on here: https://stackoverflow.com/a/2558793/43959
You could use this function to "transparently" remove the BOM before including another PHP file.
Note: I really recommend you to fix your editor(s) / files instead of doing nasty things with eval() which i demonstrate here.
This is just a proof of concept:
bom_test.php:
<?php
function bom_safe_include($file) {
$fd = fopen($file, "r");
// read 3 bytes to detect BOM. file read pointer is now behind BOM
$possible_bom = fread($fd, 3);
// if the file has no BOM, reset pointer to beginning file (0)
if ($possible_bom !== "\xEF\xBB\xBF") {
fseek($fd, 0);
}
$content = stream_get_contents($fd);
fclose($fd);
// execute (partial) script (without BOM) using eval
eval ("?>$content");
// export global vars
$GLOBALS += get_defined_vars();
}
// include a file
bom_safe_include("test_include.php");
// test function and variable from include
test_function($test);
test_include.php, with BOM at beginning
test
<?php
$test = "Hello World!";
function test_function ($text) {
echo $text, PHP_EOL;
}
OUTPUT:
kaii#test$ php bom_test.php
test
Hello World!
I have been able to identify the files that carried BOM inside them with this script, maybe it helps someone else with the same problem in the future. Works without eval().
function fopen_utf8 ($filename) {
$file = #fopen($filename, "r");
$bom = fread($file, 3);
if ($bom != b"\xEF\xBB\xBF")
{
return false;
}
else
{
return true;
}
}
function file_array($path, $exclude = ".|..|libraries", $recursive = true) {
$path = rtrim($path, "/") . "/";
$folder_handle = opendir($path);
$exclude_array = explode("|", $exclude);
$result = array();
while(false !== ($filename = readdir($folder_handle))) {
if(!in_array(strtolower($filename), $exclude_array)) {
if(is_dir($path . $filename . "/")) {
// Need to include full "path" or it's an infinite loop
if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);
} else {
if ( fopen_utf8($path . $filename) )
{
//$result[] = $filename;
echo ($path . $filename . "<br>");
}
}
}
}
return $result;
}
$files = file_array(".");
vim $(find . -name \*.php)
once inside vim:
:argdo :set nobomb | :w

Categories