e4effect
e4effect

Reputation: 29

file_get_contents replace declared variables

I need to open a file which contains php and html code and change some declared variables to user selected values:

The file begins:

<?php mb_internal_encoding("UTF-8"); ?>
<div class="redshop_product td"><!-- for <?php echo basename(__FILE__, '.php')?> //-->

<!-- REDshop entry for A Bigger Bundle /title --> <?php $outofstock=1; $explanation="Expected back in stock 12 June"; ?> 
AND THEN LOTS OF HTML AND JAVASCRIPT WHICH MAKES UP THE ITEM DISPLAY

I need to open the file, check the value of $outofstock and $explanation and replace them with whatever the user has selected and then save the file with the new values. I have a function

function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}

which I use to select strings from the file and works perfectly well for normal html and javascript. For example

get_string_between($contents, "<!-- REDshop entry for ", " /title");

would give you "A Bigger Bundle". However I can't work out how to get it to work with the php declaration. So

$outofstock=get_string_between($contents, '<?php $outofstock=', ';');

returns nothing (should be 1)

Here is the section of code in question:

 $contents = strstr(file_get_contents("products/".$_POST['StockToggle'].".php"), ' -->', true);     
 $outofstock=get_string_between($contents, '<?php $outofstock=', ';');  $explanation=get_string_between($contents, '$explanation="', '";');     
 $productname=get_string_between($contents, "<!-- REDshop entry for ", " /title");

Any ideas how I achieve what I want?

Upvotes: 1

Views: 775

Answers (2)

EdgeCaseBerg
EdgeCaseBerg

Reputation: 2841

The reason outofstock is empty is because it does not exist in $contents. Go ahead and print out $contents you'll notice it is:

<?php mb_internal_encoding("UTF-8"); ?>
<div class="redshop_product td"><!-- for <?php echo basename(__FILE__,'.php')?> //

This is because you used strstr on the result of file_get_contents and only returned the contents of the file up until the first "-->", which is after that first echo and basename business.

To fix it you should load the full file and not use strstr

Upvotes: 1

Dimi
Dimi

Reputation: 1267

your current implementation is not suitable for this sort of operation. Just use a database and store all variables there. If you do not have a database server then use SQLite. If you cannot use SQLite, then you can create two files, named 1.dat and 2.dat and store all of your variables there, then just read things from them into your variables.

Upvotes: 0

Related Questions