file_get_contents无法打开流

Helloo, all I am trying to call the web service from file on windows server 2008.

I have connected to the server and installed there xampp and placed all the required files.

this is my code to call the webservice.

$result = file_get_contents("http://*******:8055/API.ashx?Method=Departure");
    $json = json_decode($result, true);

    $departure_count = count($json['Response']);

It gives me correct response on localhost but not on server. I have googled and they tell me that I should use cURL instead of file_gets_contents.

Then I used this code:

$url = 'http://*******:8055/API.ashx?Method=Departure';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$data = curl_exec($curl);
curl_close($curl);
$json = json_decode($data, true);
$departure_count = count($json['Response']);

and it also gives me response on localhost but not on server, The address to access the URl is : http://221.120.222.68:8080/wordpress/fare/

When I tried to open $url in browser, it gives me the response

As the error message says, the stream (URL) requested cannot be opened.

There are many possible reasons for this:

1. base URL is bad.
2. username and/or password are bad
3. username/password do not have permission on the server
4. Your system cannot reach the server (firewall, PHP permissions)

I would use the following strategy to debug:

1. Dump $url and write it down.
2. Use a browser with debug tools (eg Firefox/Firebug) and try to access that URL.
3. Look at the headers returned to see what error the server reports (if any).
4. Think about why that error is returned...

I have googled and they tell me that I should use cURL instead of file_gets_contents.

Who are they? Certainly using curl should make it easier to diagnose the problem - but it won't reveal all the potential problems.

While the answer from Rax has some good hints, you say that the code works on a different machine - so the issue is about how the server connects to the service. There are many reasons this could be a problem:

  • all outgoing connections may be blocked by design
  • there may be no route to the outside network
  • there may be no DNS service available

The first person you should be speaking to is whomever supports/provisions the server. Meanwhile you could try deploying a simple script to attempt to resolve the hostname, and to attempt to retrieve content from a well established site using HTTP (e.g. this one).

e.g.

 <?php

 $ip=gethostbyname('*******'); // the hostname you are trying to connect to
 print "IP = " . var_export($ip, true) . "<br />";
 $content=file_get_contents("http://stackoverflow.com");
 if (false===$content) {
    print "failed to retrieve content - " 
      . var_dump($http_response_header, true);
 } else {
    print "Successfully retrieved " . strlen($content) 
       . " bytes from http://stackoverflow.com";
 }