file_get_contents failed to open streams - php

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";
}

Related

How to get response from server using curl in php

i am using CURL to get data from server. The way it works is like the following:
A device send data to routing application which is found on server.
To get the data from the routing application, clients must ask with GET method specifying server address, port and parameter.
once a client is connected, the application start sending data on every new packet arrived from the device to connected clients. see below picture
now lets see my code that i run to get the response:
<?php
$curl = curl_init('http://192.168.1.4/online?user=dneb');
curl_setopt($curl, CURLOPT_PORT, 1818);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($curl);
curl_close($curl);
echo $result;
With this CURL request i can get the response data from routing application. But the routing application will never stop sending data to connected clients, so i will get the result only if i close the routing application, and it will echo every data as one. Now my question is how can i echo each data without closing the connection or the connection closed by the routing application? i.e When data received, display the data without any conditions. You can suggest any other options to forward this data to another server using TCP. Thanks!
a http connection that never close? don't think php's curl bindings are suitable for that. but you could use the socket api,
$sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_set_block($sock);
socket_connect($sock,"192.168.1.4",1818);
$data=implode("\r\n",array(
'GET /online?user=dneb HTTP/1.0',
'Host: 192.168.1.4',
'User-Agent: PHP/'.PHP_VERSION,
'Accept: */*'
))."\r\n\r\n";
socket_write($sock,$data);
while(false!==($read_last=socket_read($sock,1))){
// do whatever
echo $read_last;
}
var_dump("socket_read returned false, probably means the connection was closed.",
"socket_last_error: ",
socket_last_error($sock),
"socket_strerror: ",
socket_strerror(socket_last_error($sock))
);
socket_close($sock);
or maybe even http fopen,
$fp=fopen("http://192.168.1.4:1818/online?user=dneb","rb");
stream_set_blocking($fp,1);
while(false!==($read_last=fread($fp,1))){
// do whatever
echo $read_last;
}
var_dump("fread returned false, probably means the connection was closed, last error: ",error_get_last());
fclose($fp);
(idk if fopen can use other ports than 80. also this won't work if you have allow_url_fopen disabled in php.ini)

Why am I getting an empty return value from PHP WEB Service that works in a browser address bar call?

OK, firstly, I must be missing something, so I apologise for what may turn out to be a newb question...
I have a complicated bit of code that is just not working, so am putting it out here or any pointers. I can't share too much as it is proprietary, so here goes.
I have three tiers: User, server, appliance. The server, and appliance are php enabled, the client is either IE, or Chrome - the behavior is the same.
The user tier sends data from an HTML 5 form to the server, which in turn logs it in a database, and can send to the appliance - all OK here.
Due to the appliance not being https enabled I am trying to set up a trigger/response model. This means sending an abbreviated message, or key (as a GUID), to the appliance, and then the appliance calling back to the server for an XML message for processing. The call back is done using a get_file_contents() call.
All the parts seem to be working, the server response is retrieving the XML and the client is picking the XML headers correctly - however when the appliance is performing the call, the response is empty.
$result = file_get_contents($DestURL) ;
// If I call the value in $DestURL in a browser address
// box - it all works
// If I echo the $result, it is empty, and then nothing
// executes, except the last line.
if (strlen($result)== 0 ) {
// ==> this is not executing <==
$msg = "Failed to open the <a href='" . htmlspecialchars($DestURL) . "'> URL<a>: " . htmlspecialchars($DestURL);
$result="Error";
}
// ==> this is not executing <<==
if ($result=="Error")
{
/*
* need to send an error message
*/
}
else
{
$result = PrintMessage($my_address, $result
}
// ==> This is executing <==
Echo "all Finished";
?>
Any ideas from anyone greatly appreciated.
The Server Web service reads like this:
<?php
header("Content-type: text/xml");
// a bunch of items getting the data from the database
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
echo $row['message_XML'];
?>
I still have no real reason why this is happening, however a related post helped over here:
PHP ini file_get_contents external url helped a huge amount - Thanks to both responses.
I've changed the get from using file_get_contents() to a CURL call. Problem Solved.
Here is the code:
function get_message($URL)
{
/*
* This code has been lifted from stackoverflow: URL to the article
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
// Can also link in security bits here.
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

Calling file() on pastebin URL fails, but on local file or google.com it works

I'm working on a bit of PHP code that depends on a remote file which happens to be hosted on pastebin. The server I am working on has all the necessary functions enabled, as running it with FILE_URL set to http://google.com returns the expected results. I've also verified through php.ini for extra measure.
Everything should work, but it doesn't. Calling file() on a URL formed as such, http://pastebin.com/raw.php?i=<paste id here>, returns a 500 server error. Doing the same on the exact same file hosted locally or on google.com returns a reasonable result.
I have verified that the URL is set to the correct value and verified that the remote page is where I think that it is. I'm at a loss.
ini_set("allow_url_fopen", true);
// Prefer remote (up-to-date) file, fallback to local file
if( ini_get("allow_url_fopen") ){
$file = file( FILE_URL );
}
if(!isset( $file ) || !$file ) {
$file = file( LOCAL_FILE_PATH );
}
I wasn't able to test this, but you should use curl, try something like this:
<?php
$url = "http://pastebin.com/2ZdFcEKh";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
Pastebin appear to use a protection system that will automatically block IP addresses that issue requests that are "bot-like".
In the case of your example, you will get a 500 server error since the file() command never completes (since their protection system never closes the connection) and there is no timeout facility in your call. The script is probably considered "bot-like" since file() does not pass through all the standard HTTP headers a typical browser would.
To solve this problem, I would recommend investigating cURL and perhaps look at setting a browser user agent as a starting point to grant access to your script. I should also mention that it would be in your interests to investigate whether or not this is considered a breach of the Pastebin user agreement. While I cannot see any reference to using scripts in their FAQ (as of 2012/12/29), they have installed protection against scripts for a reason.

how to use CURL to request a php page on another server and then process the response

I'm trying to connect to a mysql db, but from another server and process all queries on that server and then send all the data off to the original server, using CURL.
I've been researching for hours and cant seem to find the right way to go about it.
so this is what I'm trying to do overall:
When somebody visits a page from server A, a request will then be sent out from server A to server B which will then connect to a db.
Once server B has connected to the db, it will take information from certain rows and fields and then send it back to server a.
Once server A has received the info, it will then echo out and etc etc...
Firstly, is this safe to do? It wont like open a door on both or even one server will it?
Secondly, I have no idea how to go about it.
An example code would be great!
On server A
$post_fields = array(
'variable_name' => 'variable_value',
'variable' => $variable,
);
$ch = curl_init('http://www.serverB.com/example.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
$result now contains the HTML of the page you have requested from server B.
On server B
// pseudocode
$variable = $_POST['variable'];
$variable_name = $_POST['variable_name'];
$db_results = $db->getQuery('SELECT * FROM table WHERE `variable` = ?', array($variable))->toString();
echo $db_results;
Is it safe?
This depends. Does the information coming from the DB need to be protected from public view? Obviously with the setup above the information is just echod out to a page on server B. Was someone to find that page then they would be able to see the information.
If that does not matter then its perfectly save and does not open any doors (you own both sites right?) particularly.
If you need to protect against that then I suggest sending a token from server A to server B to authenticate that the correct script is attempting to access the information. Something like an API key, which you could pass as a header in your curl request and then get out and verify from $_SERVER on server B.

file_get_contents() GET request not showing up on my webserver log

I've got a simple php script to ping some of my domains using file_get_contents(), however I have checked my logs and they are not recording any get requests.
I have
$result = file_get_contents($url);
echo $url. ' pinged ok\n';
where $url for each of the domains is just a simple string of the form http://mydomain.com/, echo verifies this. Manual requests made by myself are showing.
Why would the get requests not be showing in my logs?
Actually I've got it to register the hit when I send $result to the browser. I guess this means the webserver only records browser requests? Is there any way to mimic such in php?
ok tried curl php:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "getcorporate.co.nr");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
same effect though - no hit registered in logs. So far it only registers when I feed the http response back from my script to the browser. Obviously this will only work for a single request and not a bunch as is the purpose of my script.
If something else is going wrong, what debugging output can I look at?
Edit: D'oh! See comments below accepted answer for explanation of my erroneous thinking.
If the request is actually being made, it would be in the logs.
Your example code could be failing silently.
What happens if you do:
<?PHP
if ($result = file_get_contents($url)){
echo "Success";
}else{
echo "Epic Fail!";
}
If that's failing, you'll want to turn on some error reporting or logging and try to figure out why.
Note: if you're in safe mode, or otherwise have fopen url wrappers disabled, file_get_contents() will not grab a remote page. This is the most likely reason things would be failing (assuming there's not a typo in the contents of $url).
Use curl instead?
That's odd. Maybe there is some caching afoot? Have you tried changing the URL dynamically ($url = $url."?timestamp=".time() for example)?

Categories