Daisy Oopsy
Daisy Oopsy

Reputation: 155

Use php include within a php code

I have a php code that will create a txt file, the problem I'm having is adding is the content of the txt file.

I want to include it from an external file.

This is the code i have used so far:

<?php
$data = $_POST;
$time = time();
$filename_prefix = 'file/evidence_file';
$filename_extn   = 'txt';

$filename = $filename_prefix.'-'.$time.'-'.uniqid().'.'.$filename_extn;

if( file_exists( $filename ) ){
 # EXTREMELY UNLIKELY, unless two forms with the same content and at the same time are submitted
  $filename = $filename_prefix.'-'.$time.'-'.uniqid().'-'.uniqid().'.'.$filename_extn;
 # IMPROBABLE that this will clash now...
}

if( file_exists( $filename ) ){
 # Handle the Error Condition
}else{
  file_put_contents( $filename , '<?php include("text.php"); ?>' );
}
?>

The problem is using the php include within the current code! All that it prints in the txt file is:

<?php include("text.php"); ?>

How can I get it to display the content of text.php?

Also the text.php file contains php code.

Upvotes: 0

Views: 182

Answers (4)

yachaka
yachaka

Reputation: 5579

As said, you can use file_gets_content to get the content of the file.

But if you want to first execute the file, as it's php code, and get the resulting content and put in the file then (I guess it's what you want), you have to use the buffer :

ob_start();

include('text.php');

$content = ob_get_contents();
ob_end_clean();

file_put_contents($filename , $content);

This way, the php file is executed and it's resulted content is passed to the file. If you want to know more about ouput control functions, here's the documentation.

Upvotes: 4

matewka
matewka

Reputation: 10168

I guess you should do it like that

file_put_contents( $filename , '<?php '. file_get_contents("text.php") .'?>' );

file_get_contents function returns the file contents as a string while include literally includes and evaluates the file. Since your file is a PHP file and you only want to include it as a string my solution should be fine.

Upvotes: 0

scrblnrd3
scrblnrd3

Reputation: 7426

Currently, you're just putting in a string to the file_put_contents, so it will take what you put in literally, and anyway, include() isn't what you want anyway

include("text.php"); loads the php file and execute its contents when put inside PHP, I don't think you want to do that. Use file_get_contents() instead, like this:

file_put_contents($filename,file_get_contents("text.php"));

Upvotes: 0

fracz
fracz

Reputation: 21278

Use file_get_contents function instead of include.

file_put_contents($filename, file_get_contents("text.php"));

Use include when you want the included code to be executed, not used as a text.

Upvotes: -1

Related Questions