Alex Groves
Alex Groves

Reputation: 37

How could I write PHP code into a file created by PHP?

The title is self-explanatory. Within PHP, I create a PHP file, add some PHP and HTML code to it, then close it. The problem is that PHP files take all PHP code found and converts it to emptiness. Here's the last thing I tried.

$phpfile=fopen('backupfile.php',"r");
$phptext=fgets($phpfile);
  if(stristr($link, 'http://') === FALSE) {
  fwrite($file2,$phptext."<meta http-equiv='refresh' content='0; URL=http://".$link." '/>");


  }else{
  fwrite($file2,$phptext."<meta http-equiv='refresh' content='0; URL=".$link." '/>");

  }

phpfile includes the following:

<?php $file=fopen("/num","r"); $bar=fgets($file); $bar=$bar+1; $file=fopen("/num","w"); fwrite($file,$bar); ?>

As said before, it simply doesn't add that to the file.

I tried htmlentities but that made the PHP code visible to the page and not hardwired into the file.

Thanks for any help.

Upvotes: 1

Views: 119

Answers (3)

Martin
Martin

Reputation: 22760

Step 1: Code clarification:

$link = "some like address";
  if(mb_strpos($link, 'http://') === FALSE || mb_strpos($link, 'http://') > 0) {
     $link = "http://".$link;
   }
  $phptext = PHP_EOL."<meta http-equiv='refresh' content='0; URL=".$link." '/>";
   file_put_contents('backupfile.php', $phptext, FILE_APPEND); 

Ok so what did I do here:

  • Checking with multibyte string checks if HTTP:// appears in the string, checking at the start is irrelivant because if it's not at the start it's an invalid HTTP request anyway, and you make no checks for this in the code provided.

  • Once checked, the $link value is updated.

  • Then use file_put_content to append what is in the string into the existing file. If the file does not exist then it will be created.


Edit:

It is not clear from your question but if you want $link saved in the string then write the link as follows with single quotes:

$phptext = PHP_EOL.'<meta http-equiv="refresh" content="0; URL=$link"/>';

Upvotes: 0

Bangkokian
Bangkokian

Reputation: 6654

Rewrite your code using only (escaped) single quotes. Using double quotes will cause the embedded php to be interpreted.

Upvotes: 2

Jaquarh
Jaquarh

Reputation: 6673

Its not really about writing code inside a file, you can bridge this idea using a Database.

You could have a standard directory set-up, ie: help documents.

Inside that directory, have a file: you can simply query the Database for pages, integrate a permalink to each page using a get value and then show content from that value (maybe a page ID).

Of-course, you'll need to implement standards and security - ie, if anyone can create pages - ensure only certain html can be added or BBCode.

I hope this widens your idea; this is how most forums, posts, comments ect.. work.

Upvotes: 1

Related Questions