This is a simple problem but one of those that eats at your brains the more you think of it. I basically want to write a a variable to a php file ( the variable name itself not the contents ).

The code i have below.

// we will asssume this variables value is '1'
$status   = $_POST['status'];

$filename = "example.php"; 

$hc1 = " <?php $site_status = '"; 
$hc2 = "'; ?>";

$fp = fopen ($filename, "w");
if ($fp) {

fwrite ($fp, $hc1);
fwrite ($fp, $status);
fwrite ($fp, $hc2);

fclose ($fp);

// more code follows on but is useless to this example and
// i dont want to fill the page!

It works fine with no errors or warnings however.. the output is wrong.

i wish for the contents of 'example.php' to be

<?php $website_status = '1' ?>

but it ends up like

<?php = '1' ?>

missing out the '$website_status'.

I am guessing its because its trying to print the contents of '$website_status' to 'example.php'( printing nothing beacause $website_status doesent exist ).

I just need it to write to the file as seen.

Please help!!

Recommended Answers

All 3 Replies

Try enclosing line 6 in single quotes rather than double. Your line would then look something like:

$hc1 = ' <?php $site_status = \'';

Single quotes tell PHP not to interpret what is between the quotes whereas it does try to interpret what is between double quotes (finding $site_status to be an empty value in your case).

commented: Very helpful +3
Member Avatar for P0lT10n

It is bad because all the time you call fwrite will re-write what it has... you should save in 1 variable all the entire code to "save" and then do fwrite and put it there...

Try enclosing line 6 in single quotes rather than double. Your line would then look something like:

$hc1 = ' <?php $site_status = \'';

Single quotes tell PHP not to interpret what is between the quotes whereas it does try to interpret what is between double quotes (finding $site_status to be an empty value in your case).

Works perfectly! I was beggining to pull my hair out on this one. I tryed many optional solutions before posting bar yours.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.