PHP get request returning false - php

$data = file_get_contents("http://randomword.setgetgo.com/get.php");
var_dump($data);
I keep getting false when sending this get request, anyone have an idea why?
It works just fine with a simple php script I wrote hosted from the same domain, might that be the issue, how do I go about sending a get request to this API if that is the case?
I tried using curl as well with the same result. It works with my test script but not the API.

As noted in the various comments above, the code originally posted works fine for me but not for the OP - most likely due to a restriction placed upon various standard PHP functions by the webhost. As an alternative, cURL should be able to retrieve the content unless a similar restriction has been placed on standard curl functions too.
$url='http://randomword.setgetgo.com/get.php';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_USERAGENT, 'curl-wordfetcher' );
$result = curl_exec( $ch );
if( curl_errno( $ch ) ) echo 'Curl error: ' . curl_error( $ch );
curl_close( $ch );
print_r( $result );

Related

How is it possible to get instance metadata using PHP AWS SDK?

I would like to get the instance metadata (like AZ) for the current EC2, using AWS SDK.
I was able to find an alternative solution, but it is not using the SDK just a file_get_contents
How is it possible with the SDK?
The solution proposed by JasonQ-AWS is useful to get information about all instances and applications in your account. However, it does not tell you what information describes the instance that is really executed by the current process.
For that you have to use IMDSv2 which requires two CURL commands, the first one to get a TOKEN and the second one to get the actual metadata of the current instance.
In PHP the code can therefore be :
$ch = curl_init();
// get a valid TOKEN
$headers = array (
'X-aws-ec2-metadata-token-ttl-seconds: 10' );
$url = "http://169.254.169.254/latest/api/token";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT" );
curl_setopt( $ch, CURLOPT_URL, $url );
$token = curl_exec( $ch );
echo "<p> TOKEN :" . $token;
// then get metadata of the current instance
$headers = array (
'X-aws-ec2-metadata-token: '.$token );
$url = "http://169.254.169.254/latest/dynamic/instance-identity/document";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
$result = curl_exec( $ch );
echo "<p> RESULT :" . $result;
All you have to do is to extract the desired information. You can also ask for a unique information, such as the instance id with a more specific url like :
$url = "http://169.254.169.254/latest/meta-data/instance-id";
By current EC2 instance, are you referring to PHP code running on an EC2, and you would like to inject that metadata into some variables for use?
Or do you mean you have an object created with the PHP SDK such as with something like:
$ec2Client = new Aws\Ec2\Ec2Client([
'region' => 'us-east-1',
'version' => 'latest'
]);
If you mean the second way, you can access that data through describeInstances like this:
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
echo "Availability Zone: {$instance['Placement']['AvailabilityZone']} \n";
}
echo "\n";
}
You can also filter by adding parameters to the method call such as by type or instanceId.
If you're just running PHP code on the EC2 instance and you want that info, you can check out this page for some options: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
I don't think this is possible at all. IMDSv2 info like AZ, instance-id, instance-type, etc is readable via https://169.254.169.254 and if you look into the source code for the SDK, it only pulls temporary credentials via IMDSv2 (https://github.com/aws/aws-sdk-php/search?q=169.254)
and does not allow arbitrary IMDSv2 queries.
Unless I'm missing something, you need to pull this data yourself or use some 3rd-party library which does that for you in PHP.

file_get_content not working for https in php

Has anybody had an issue with display content from a website thats over https? The code was working until all the sites on server got ssl. maybe something to so with the certificate being tlss 1.2? So the site im trying to do this from has this certificate now.
$data = file_get_contents('https://www.ladygaga.com/');
echo $data;
According to php.net
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
Source link
Based on OpenSSL changes in PHP 5.6, try this:
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://www.ladygaga.com/", false, stream_context_create($arrContextOptions));
echo $response;
Another option would be to use curl as such:
function file_get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
$data = curl_exec( $ch );
curl_close( $ch );
return $data;
}
$data = file_get_contents_curl("https://www.ladygaga.com");

CentralPlanner API cal via curl. 500 response

I have done little with cURL so far, so bear with me.
This is the api that I am currently dealing with:
CentralPlannerAPI
I have a token, I can call it via the bash shell and all is fine, except for the part where PHP comes into play. I constantly get authentication errors. The last one would be a 500.
This one works:
curl "https://centralplanner.net/api/contacts" -H 'Authorization: Token token="my-api-token"'
This one does not work:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://centralplanner.net/api/contacts/count" );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Authorization: Token token='myToken'" ) );
curl_exec( $ch );
curl_close( $ch );
Why does the PHP part not work?
What am I not getting here. Yes, there is currently not much to it and later one it will only be slightly more than this, at least from the current perspective; no it will not run on a server; yes, I will add some validation on and yes, it will a proper class construct and so and so forth.
PS:
Before someone refers me to other SO sites, I looked at them ... did not help.
Please try this code:
$ch = curl_init("https://centralplanner.net/api/contacts/count");
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => "Authorization: Token token=\"myToken\""
];
curl_setopt_array($ch, $options);
$content = curl_exec($ch);

Google Cloud Messaging Push Notifications only work once (PHP, Android)

I am having trouble getting Google Cloud Messaging for Android working.
I have had it working before but it decides to stop working after the first couple of times.
In order to get it working again I have to delete my API key and recreate it.
I am using PHP with a SERVER API key with a IP whitelist of ::/0 (All IPv6 apparently)
Note: My android app requests a device message key each time the app is opened (Usually returns the same message key)
The Error I get is: Unauthorized Error 401
When I got to the following url to check my app message id i get 'invalid token'.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14
The PHP code I am using is:
$data = array( 'message' => 'Hello World!222!' );
$ids = array('APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14');
$apiKey = 'AIzaSyATkp_UTZh....'; //obviously the complete key is used...
$url = 'https://android.googleapis.com/gcm/send';
$post = array('registration_ids' => $ids, 'data' => $data);
$headers = array( 'Authorization: key=' . $apiKey, 'Content-Type: application/json');
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Thanks for any help given.
EDIT: It seems to work since I unregistered my device and reregistered it with GCM. I am not sure if this is a permanent fix but it works for now.

How to make a request to a web page with PHP?

What i'm trying to achieve is this:
1st- I want to query a page like google but without filling it's search filed manually
2nd- I want to get the result and save it to a database
I saw an example of doing this with C# here
http://www.farooqazam.net/c-sharp-auto-click-button-and-auto-fill-form/comment-page-1/#comment-27256
but i'd like to do it with php, can you help me please?
Thanks
You should use cURL to do so, not only because it is way faster than file_get_contents, but also because it has many more features. Another reason to use it is that, as Xeoncross correctly mentioned in the comments, file_get_contents may be disabled by your webhost for security reasons.
A basic example would be this one:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
If you need the return data from the request, you need to specify the CURLOPT_RETURNTRANSFER option:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true ); // Fetch the contents too
$html = curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
There are tons of cURL options, for example, you can set a request timeout:
curl_setopt( $curl_handle, CURLOPT_CONNECTTIMEOUT, 2 ); // 2 second timeout
For a reference of all options see the curl_setopt() reference.
$html = file_get_contents('http://example.com');
is the simplest version you'll get.
<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
$r->send();
if ($r->getResponseCode() == 200) {
file_put_contents('local.rss', $r->getResponseBody());
}
} catch (HttpException $ex) {
echo $ex;
}
?>
From the php manual...
You can use PHP CUrl, for detailed manupulations with the site you access!
you can even perform get and posts on the site you access, or use services from different sites (in case the site provides services!).
If you find the name of the field (q) you want to fill on the remote page (Google), you can fill it by using GET syntax:
http://www.google.com/?q=hello

Categories