douao1854 2018-04-11 03:03
浏览 45

是否可以从另一个域调用函数?

I have 2 domain and i want to move a php file from domain 1 to domain 2.
The purpose of the file is get user input, get data from database and etc.
The reason i want to do this is i dont want anyone can view the file in domain 1.
Is it possible to do that?

  • 写回答

1条回答 默认 最新

  • douwa1304 2018-04-11 03:53
    关注

    You need to pass your data using cURL from your 2nd server to the PHP file in your 1st server and process the data there and then read the data sent back.

    This is an example:

    Assume: example.org is the domain of your your 1st server.

    $ch = curl_init("https://example.org/check.php");
    
    $data = array(
        'username'      => 'JohnDoe',
        'password'      => '2hAreZ08npmv'
    );
    
    $data_json = json_encode($data); //Convert the array into a JSON string format
    
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $data_json );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_json))
    );
    
    $result = curl_exec($ch); //Returned value (echo) from the PHP file in your 1st server
    

    Your 1st server will receive the username and password via POST method in JSON format. Like this:

    {"username":"JohnDoe","password":"2hAreZ08npmv"}
    

    Which you can decode and convert it to an array and use it in your function in the 1st server:

    $data_received = "{"username":"JohnDoe","password":"2hAreZ08npmv"}";
    $data_array = json_decode($data_received, true);
    

    echo the result in the 1st server and you will receive it in $result variable that I used in the above code. The value of $result can be something like 'true' or 'false' or any other string that you echo.

    This is a simple way to communicate between two servers using cURL in PHP.

    评论

报告相同问题?