user2615859
user2615859

Reputation: 37

change part of a php file using php

how can I change only a part of php file. Actually add a variable or change a single variable in already existing php file. I have tried as follows but this erases everything and echoes only the text "I love PHP".

$myFile = '../new_folder_name/index.php'; 
$myContent = 'I love PHP'; 

file_put_contents($myFile, utf8_encode($myContent));

I want to add for example a variable named $test that equals 10. $test="10"; or change already existing variable $test to 10.

Upvotes: 0

Views: 107

Answers (2)

user2533777
user2533777

Reputation:

Try this for adding new content

$myFile = '../new_folder_name/index.php'; 
$myContent = 'I love PHP';
$file=fopen($myFile,"a");
fputs($file,$myContent);
fclose($file);

For playing with variables we need to handle an php file as an normal text file here you go

function get_str_btwn($string, $start, $end)//an function to get string between two string in an string
{
    $string = " " . $string;
    $ini    = strpos($string, $start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
$file=file_get_contents($myFile);
if(substr_count($file,"$myContent"))
$file=str_ireplace(get_str_btwn($file,"$myContent =",";"),"I love PHP",$file);//Assuming format of php file is $myContent is initialized like $myContent="something"; 
else
$file=str_ireplace("<?php","<?php $myContent = 'I love PHP';",$file);

Please note this code is very sensitive and may result in errors in php file generated and is not recommended for regular use unless you are sure format of php file.

Upvotes: 0

Ivan Han&#225;k
Ivan Han&#225;k

Reputation: 2306

I am creating php file with php file

<?php
$dir = "../new_folder_name";

$file_to_write = "index.php";

$content_to_write = '


PHP CODE COMES HERE
$test= GET ('SOMETHING')


';

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 want everyfile to have a different value of a $test variable. I wanted after a file creation to be able to change the value of the variable in the created file

Upvotes: 1

Related Questions