require/include into variable

前端 未结 9 1577
萌比男神i
萌比男神i 2020-11-27 17:46

I want to require/include a file and retrieve its contents into a variable.

test.php



        
相关标签:
9条回答
  • 2020-11-27 18:09

    It is possible only if required or included php file returns something (array, object, string, int, variable, etc.)

    $var = require '/dir/file.php';
    

    But if it isn't php file and you would like to eval contents of this file, you can:

    <?php
    
    function get_file($path){
    
        return eval(trim(str_replace(array('<?php', '?>'), '', file_get_contents($path))));
    }
    
    $var = get_file('/dir/file.php');
    
    0 讨论(0)
  • 2020-11-27 18:10

    I think eval(file_get_contents('include.php')) help you. Remember that other way to execute like shell_exec could be disabled on your hosting.

    0 讨论(0)
  • 2020-11-27 18:11

    require/include does not return the contents of the file. You'll have to make separate calls to achieve what you're trying to do.

    EDIT

    Using echo will not let you do what you want. But returning the contents of the file will get the job done as stated in the manual - http://www.php.net/manual/en/function.include.php

    0 讨论(0)
  • 2020-11-27 18:11

    Or maybe something like this

    in file include.php:

    <?php
      //include.php file
      $return .= "value1 ";
      $return .= time();
    

    in some other php file (doen't matter what is a content of this file):

    <?php
      // other.php file
      function() {
        $return = "Values are: ";
        include "path_to_file/include.php";
    
        return $return;
      }
    

    return will be look like this for example:

    Values are: value1, 145635165
    

    The point is, that the content of included file has the same scope as a content of function in example i have provided about.

    0 讨论(0)
  • 2020-11-27 18:13

    In PHP/7 you can use a self-invoking anonymous function to accomplish simple encapsulation and prevent global scope from polluting with random global variables:

    return (function () {
        // Local variables (not exported)
        $current_time = time();
        $reference_time = '01-01-1970 00:00';
    
        return "seconds passed since $reference_time GMT is $current_time";
    })();
    

    An alternative syntax for PHP/5.3+ would be:

    return call_user_func(function(){
        // Local variables (not exported)
        $current_time = time();
        $reference_time = '01-01-1970 00:00';
    
        return "seconds passed since $reference_time GMT is $current_time";
    });
    

    You can then choose the variable name as usual:

    $banner = require 'test.php';
    
    0 讨论(0)
  • 2020-11-27 18:19

    I've also had this issue once, try something like

    <?php
    function requireToVar($file){
        ob_start();
        require($file);
        return ob_get_clean();
    }
    $test=requireToVar($test);
    ?>
    
    0 讨论(0)
提交回复
热议问题