Asked  7 Months ago    Answers:  5   Viewed   40 times

I want to get contents of a .php file in a variable on other page.

I have two files, myfile1.php and myfile2.php.


    $myvar="prashant"; // 
    echo $myvar;

Now I want to get the value echoed by the myfile2.php in an variable in myfile1.php, I have tried the follwing way, but its taking all the contents including php tag () also.

    $root_var .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/myfile2.php", true);

Please tell me how I can get contents returned by one PHP file into a variable defined in another PHP file.




You can use the include directive to do this.

File 2:


File 1:


echo $myvar;

Wednesday, March 31, 2021
answered 7 Months ago

Provided allow_url_fopen is enabled, you can just use file_get_contents :

$my_var = file_get_contents('');

And, if you need more options, take a look at Stream Functions -- there is an example on the stream_context_create manual page where a couple of HTTP-headers are set.

If allow_url_fopen is disabled, another solution is to work with curl -- means a couple more lines of code, though.

Something as basic as this should work in the simplest situations :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$my_var = curl_exec($ch);

But note that you might need some additional options -- see the manual page of curl_setopt for a complete list.

For instance :

  • I often set CURLOPT_FOLLOWLOCATION, so redirects are followed.
  • The tiemout-related options are quite often useful too.
Wednesday, March 31, 2021
answered 7 Months ago
$message = str_replace("$SAD", "HAPPY", $message);

needs to be:

$message = str_replace('$SAD', "HAPPY", $message);

Otherwise PHP will interpret it as the variable $SAD. See this post for an explanation on the difference between single and double quotes.

Saturday, May 29, 2021
answered 5 Months ago

The setting you are looking for is allow_url_fopen.

You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.

I recommend using cURL over file_get_contents() anyways, since it was built for this.

Tuesday, June 1, 2021
answered 5 Months ago

Use for, something along the lines of:

set content=
for /f "delims=" %%i in ('filename') do set content=%content% %%i

Maybe you’ll have to do setlocal enabledelayedexpansion and/or use !content! rather than %content%. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-).

The best batch-file-black-magic-reference I know of is at If you don’t know Russian, you still could make some use of the code snippets provided.

Tuesday, July 27, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :