Get variable from php file

How to execute and get content of a .php file in a variable?

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.

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

ALWAYS BE CAREFULL, because if you will use ob_get_contents() , then you may need to do ob_end_flush , otherwises you may have problems, if you use will use any php header command after that.

9 Answers 9

You have to differentiate two things:

  • Do you want to capture the output ( echo , print . ) of the included file and use the output in a variable (string)?
  • Do you want to return certain values from the included files and use them as a variable in your host script?

Local variables in your included files will always be moved to the current scope of your host script — this should be noted. You can combine all of these features into one:

$hello = "Hello"; echo "Hello World"; return "World"; 
ob_start(); $return = include 'include.php'; // (string)"World" $output = ob_get_clean(); // (string)"Hello World" // $hello has been moved to the current scope echo $hello . ' ' . $return; // echos "Hello World" 

The return -feature comes in handy especially when using configuration files.

return array( 'host' => 'localhost', . ); 
$config = include 'config.php'; // $config is an array 

To answer your question about the performance penalty when using the output buffers, I just did some quick testing. 1,000,000 iterations of ob_start() and the corresponding $o = ob_get_clean() take about 7.5 seconds on my Windows machine (arguably not the best environment for PHP). I’d say that the performance impact should be considered quite small.

Читайте также:  Java colored console output

If you only wanted the content echo() ‘ed by the included page, you could consider using output buffering:

ob_start(); include 'myfile2.php'; $echoed_content = ob_get_clean(); // gets content, discards buffer 

ob_start() is new for me. So, @harto can you suggest me which method will do better according to performance, your method or the method @zombat suggested ??

Output buffering adds a small performance hit, as there is overhead in initializing and maintaining the buffers.

@Prashant: I don’t have any data available, but I’d guess that the performance impact would be negligible. You could try both methods and see if there’s a measurable difference between the two, but I think it would be very small indeed.

I always try to avoid ob_ functions. Instead, I use:

Your answer is interesting. Can you please share that why you avoid output buffering, and use eval() instead? Your answer will be a good knowledge for me.

OB_ functions modify the output buffer, and the many other codes in CMS could be using buffer functions indpendently at that time, and it may come into conflict, or clean buffer, or modify it. So,I never touch it.

If eval() is the answer, you’re almost certainly asking the wrong question. — Rasmus Lerdorf, BDFL of PHP

You can use the include directive to do this.

Actually I was just looking that is there any «return » type method which can directly give me the value. Anyways I adopted @zombat’s answer as the method suggested by @harto may have some performance issues, and I can’t compromise with performance. Thanks guyz.

«Actually I was just looking that is there any return type method which can directly give me the value» — You just answered your own question.

You can use output buffers, which will store everything you output, and will not print it out unless you explicitly tell it to, or do not end/clear the buffers by the end of path of execution.

// Create an output buffer which will take in everything written to // stdout(i.e. everything you `echo`ed or `print`ed) ob_start() // Go to the file require_once 'file.php'; // Get what was in the file $output = ob_get_clean(); 

If you want to get all over site use by

If you want to return the output from code in a file, simply just make a RESTful API call to it. This way, you can use the same code file for ajax calls, REST API, or for your internal PHP code.

It requires cURL to be installed but no output buffers or no includes, just the page executed and returned into a string.

I’ll give you the code I wrote. It works with nearly every REST/web server (and even works with Equifax):

$post = array('name' => 'Bob', 'id' => '12345'); $return = PostRestApi($url, $post, false, 6, false); 
/** * Calls a REST API and returns the result * * $loginRequest = json_encode(array("Code" => "somecode", "SecretKey" => "somekey")); * $result = CallRestApi("https://server.com/api/login", $loginRequest); * * @param string $url The URL for the request * @param array/string $data Input data to send to server; If array, use key/value pairs and if string use urlencode() for text values) * @param array $header_array Simple array of strings (i.e. array('Content-Type: application/json'); * @param int $ssl_type Set preferred TLS/SSL version; Default is TLSv1.2 * @param boolean $verify_ssl Whether to verify the SSL certificate or not * @param boolean $timeout_seconds Timeout in seconds; if zero then never time out * @return string Returned results */ function PostRestApi($url, $data = false, $header_array = false, $ssl_type = 6, $verify_ssl = true, $timeout_seconds = false) < // If cURL is not installed. if (! function_exists('curl_init')) < // Log and show the error $error = 'Function ' . __FUNCTION__ . ' Error: cURL is not installed.'; error_log($error, 0); die($error); >else < // Initialize the cURL session $curl = curl_init($url); // Set the POST data $send = ''; if ($data !== false) < if (is_array($data)) < $send = http_build_query($data); >else < $send = $data; >curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($curl, CURLOPT_POSTFIELDS, $send); > // Set the default header information $header = array('Content-Length: ' . strlen($send)); if (is_array($header_array) && count($header_array) > 0) < $header = array_merge($header, $header_array); >curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // Set preferred TLS/SSL version curl_setopt($curl, CURLOPT_SSLVERSION, $ssl_type); // Verify the server's security certificate? curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ($verify_ssl) ? 1 : 0); // Set the time out in seconds curl_setopt($curl, CURLOPT_TIMEOUT, ($timeout_seconds) ? $timeout_seconds : 0); // Should cURL return or print out the data? (true = return, false = print) curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Execute the request $result = curl_exec($curl); // Close cURL resource, and free up system resources curl_close($curl); unset($curl); // Return the results return $result; > > 

Источник

PHP — Get variables from another PHP file without executing the code?

I’m trying to create a script to extract the variables from a file on the same server. The problem is, I don’t know what else is going to be in the file all of the time (the script is for other people to use), so I don’t really want to load all of the contents or execute any of the code. I’ve thought of using file_get_contents rather than anything like require or include, but I’m stuck. is there a way to parse all of the variables within the string? Alternatively, is there a «safe» way to include files? Many thanks, James

I am trying to create a script that will add functionality to existing systems client’s user. Each client has a file that contains information held in variables that I need, but in addition to the information I need are also other variables (and potentially, but not likely, other PHP code that performs specific functions). I’m looking for a safe way to extract the data I need from these files.

5 Answers 5

You’ll need some crafty regex to go along with it.

Why don’t you put all the variables in a third file, then include them in the other two files?

What you are trying to do sounds dangerous, especially if by «for other people to use» you mean others can write those files.

My script is trying to add functionality to existing systems. Typically these files should only contain variables, but I’m very weary. I also don’t want to include lots of useless variables that I don’t need into my script. Ideally this needs to be a «plug-and-play» kind of application, so I can’t really ask the users to change their apps.

function extract_file_variables($path) < $tokens = token_get_all(file_get_contents($path)); $variables = []; $temp_var = null; foreach ($tokens as $token) < if (!is_array($token)) continue; $value = trim($token[1], "'\""); if ($token[0] === T_VARIABLE) < $temp_var = substr($value, 1); >if (!isset($variables[$temp_var]) && $temp_var !== null && in_array($token[0], [ T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, ], true)) < $variables[$temp_var] = $value; $temp_var = null; >> return $variables; > 
print_r(extract_file_variables('dbconnection.php')); 
Array ( [servername] => localhost [username] => root [password] => [database] => my_database ) 

In this case, you don’t want your users editing a PHP file at all. As you’ve pointed out, you cannot include() the file if you cannot trust its contents. Since you can’t execute the file as PHP, there’s no advantage to the file even being PHP, so you can choose a format that your own script can more readily read. For example, with the parse_ini_file function you can easily read configuration values from a .ini file.

If it absolutely has to be a PHP file, you might have to attempt to parse it by hand. If you can demand that the file be a subset of PHP (e.g., that it include nothing but variable declarations) that sounds feasible, albeit still very hackish. If the file can legitimately be a completely functional PHP script, in which some variables happen to be defined, it’s probably time to rethink the architecture entirely.

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to get a PHP variable value from another PHP file?

I would like to know how can I get the value of the variable $answer with button, then what should I put at the line :

You should include the other php file but be careful with variable names so it won’t conflict with the main file, also $_post should be $_POST.

2 Answers 2

This is a low-quality answer because it doesn’t say where to put the line (anything at all actually). It doesn’t say to replace the current code or anything.

where i put that code coz i use the button to get the value from file2.php without go to file2.php page?

Use require_once() to include file2.php in your php file, then in your file you can access the variables in file2.php.

require_once("path of file2.php"); echo $answer; 

if your file2.php and the file1.php is in the same dir, then path of file2.php is «./file2.php» or «file2.php». You also can give it the absolute path of file2.php.

i know your mean sir thanks, but what i ask its get that value without go to page file2.php, sory bad english

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью