Duncan Palmer
Duncan Palmer

Reputation: 2913

writing to a .php file?

Hey i'm trying to write to my "config.php" file but it just won't work. I am using the code below. using this code it doesn't come up with any errors it just doesn't write the string.

 $myFile = "config.php";
      $fh = fopen($myFile, 'w') or die("can't open file");
      $stringData = "<?php\n";
      fwrite($fh, $stringData);
      $stringData = "$db_user = '{$dbuser}';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_pass = '{$dbpass}';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_name = '{$dbname}';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'localhost';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'mysql_connect($db_host, $db_user, $db_pass) or die(mysq_error());\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'mysql_select_db($db_name) or die(mysql_error());\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'function protect($str) {\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = '   return mysql_real_escape_string(urldecode($str));\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = '}\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = '?>\n";
      fwrite($fh, $stringData);
      fclose($fh);

What am i doing wrong?

Upvotes: 1

Views: 651

Answers (3)

symcbean
symcbean

Reputation: 48357

What am i doing wrong?

The big thing you are doing wrong is confusing code and data. Having self-modifying code on a webserver is a recipe for disaster.

But assuming you actually want your application to be hacked and destroyed...You need to escape references to variables to avoid them being interpolated. i.e.

fwrite($fh, '$db_user = ' . "'{$dbuser}';\n");

You should also provide meaningful explanations of why your code is not behaving as you expect (a bit more information than "it just won't work"). Assuming the file is not being written / amended and the script is bombing out with "can't open file", it's probably a permissions problem - but since you've provided no details of which OS this is, we can't tell you how to fix that.

Also you're quoting function names - does that mean you are using eval to ivoke the self-modified coe at runtime? OMG!

Upvotes: 1

undone
undone

Reputation: 7888

look! if you want to write something to file like:

$stringData = "$db_host = 'localhost';\n";


you should escape it!

$stringData = "\$db_host = 'localhost';\n";

and

  $stringData = "$db_host = 'mysql_connect($db_host, $db_user, $db_pass) or die(mysq_error());\n";

why you quoted mysql function????

Upvotes: 1

JRL
JRL

Reputation: 77993

You need to properly escape the $ characters when you want them to be output, like so:

$stringData = "\$db_user = '{$dbuser}';\n";

Upvotes: 2

Related Questions