0

I have a .php file, say "index.php" . This file is being generated dynamically and I want to add the following code at the beginning of the file.

   <?php
        session_start();
    require_once('login/auth.php');
        require_once('config.php');
   ?>

Intention is to force user to sign up or sign in before they see this file. But I wasted a whole day and turned into nothing as resultant file is blank. what I found is , its facing problem with <?php and ?>

if I replace them with their equivalent entities &lt;?php and ?&gt; then they gets added easily but its not what I wanted.

So , question is how to add this original code to the beginning on file dynamically. Can someone help please?

5
  • 2
    This is most certainly now how PHP is meant to work. There's probably a better solution than code generation for whatever problem you're tackling. Commented Jul 2, 2013 at 22:06
  • If you can use `.htaccess to set PHP config options: php.net/manual/en/ini.core.php#ini.auto-prepend-file Commented Jul 2, 2013 at 22:09
  • Those spaces will cause session_start to error out because headers are already sent. Commented Jul 2, 2013 at 22:10
  • @meagar Just to clarify: you meant 'not', not 'now'. Commented Jul 2, 2013 at 22:11
  • Yes. Not how PHP was meant to work :p Commented Jul 3, 2013 at 1:05

2 Answers 2

1
<?php

$preamble = <<<EOL
<?php 
   session_start();
   yada;
   yada;
   yada;
?>
EOL;

file_put_contents('index.php', $preamble);
Sign up to request clarification or add additional context in comments.

Comments

0

How about the following:

<?php

  file_put_contents('index.php', "   <?php
        session_start();
    require_once('login/auth.php');
        require_once('config.php');
   ?>");

Edit: Marc's idea to use heredoc syntax may be better in your situation, given the variety of text you may want to write to a file.

4 Comments

Those spaces will cause session_start to error out because headers are already sent.
I just ran it on my localhost and it was fine.
No, I didn't mean this code, I meant the resulting index.php. That will break because of the spaces before the opening <?php tag.
That I don't know about. I didn't actually test the resulting script. I simply gave the OP what he asked for (and his sample code has spaces at the beginning).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.