to get hourly and six hours based weather from NOAA - php

I am trying to get the weather data from NOAA and parse it to get the current temperature, humidity, and other values. I am trying to get the JSON data from its website, which uses the latitude, and longitude values to get the weather data of location. I am getting trouble to get the data, and I found out we have to use CURl to get it done, and I have no idea on using CURL.
this is the URL i am using to get the data
"https://api.weather.gov/points/$latitude,$longitude/forecast".
This is what I tried, based on one example I found here. I want to know how to pass the latitude, and longitude, and add the forecast at the end in the url
<?php
/**
* Created by PhpStorm.
*/
$url='https://api.weather.gov/points/'; //noaa url of choice
$params=array('39.7456','-97.0892','forecast');
$curl = curl_init();
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $params);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
$data = json_decode($result);
curl_close($curl);
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);
echo "<pre>";
?>

Simply append the coordinates to the URL.
<?php
$ch = curl_init('https://api.weather.gov/points/39.7456,-97.0892/forecast');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSLVERSION => 6,
CURLOPT_USERAGENT => 'Firefox',
]);
$response = curl_exec($ch);
if($response === false)
exit(curl_error($ch));
print_r(json_decode($response));
A few notes about the code :
Passing the URL to curl_init is the same as setting it with curl_setopt(CURLOPT_URL
curl_exec returns false on failure, hence the $response === false test. I used === in this case otherwise PHP may interpret an empty string as false, which doesn't make sense in this context.
The network connection would fail unless I set the SSL version to 6 (or CURL_SSLVERSION_TLSv1_2)
The API would forbid me from accessing the data unless I specified a believable user-agent, in this case Firefox.

Related

send a pageview event via Measurement Protocol to a GA4 property

How can I send a pageview event via Measurement Protocol to a GA4 property with PHP?
This is how I'm doing, but inside my Google Analytics 4 property I can't see any traffic.
$data = array(
'api_secret' => 'XXXX-YYYYY',
'measurement_id' => 'G-12345678',
'client_id' => gen_uuid(), // generates a random id
'events' => array(
'name' => 'page_view',
'params' => array(),
)
);
$url = 'https://www.google-analytics.com/mp/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
I'm working on registering pageviews to track API usage right now, here's what I've found:
XTOTHEL is right about setting the content type to content/json above. In addition to specifying the content type you also have to send JSON data as the CURLOPT_POSTFIELDS data.
Also per their specification the api_secret and measurement_id need to be part of the URI: https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#required_parameters
Lastly, you can use debug mode to validate your responses and figure out what's going on now by simply changing the URL to google-analytics.com/debug/mp/collect
Here's the code I'm working with right now:
//retrieve or generate GA tracking id
if (empty($_COOKIE['_cid'])) {
setcookie('_cid', vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)));
}
$data = '{"client_id":"'.$_COOKIE['_cid'].'","events":[{"name":"load_endpoint","params":{"page_location":"'.$request->fullUrl().'"}}]}';
echo '<pre>';
print_r($data);
$measurement_id = 'G-xxxxx';
$api_secret = 'xxxx';
$url = 'https://www.google-analytics.com/debug/mp/collect?api_secret='.$api_secret.'&measurement_id='.$measurement_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
This works to a certain extent. Currently it's registering the page view as a custom event instead of an actual pageview though. I'm still trying to figure out how to get them to come through as page views.
Follow up
After a little more debugging I figured out page views are actually working, they just weren't showing up in some of the views. The fix for that was to add page_title into the params:
$data = '
{
"client_id": "'.$_COOKIE['_cid'].'",
"events": [
{
"name": "page_view",
"params": {
"page_location": "'.$request->fullUrl().'",
"page_title": "'.$request->path().'"
}
}
]
}
';
A few extra notes for whoever comes next:
Debug mode did return some useful validation errors for invalid top-level parameters (client_id, events) - but it didn't return errors for anything inside of the "params" for events. IE - i put "page_asdtitle" instead of "page_title" and it accepted it just fine.
None of the tests I sent through actually showed up in the debug panel while using debug mode. I suspect this is because of the data propagation delay, it's probably not loading realtime data.
Using a JSON validator can help. Make sure you use objects and arrays where GA tells you to.
If you get stuck figuring out why your PHP code doesn't work, write the code as a browser event in JavaScript and run it in your browser. There's tons of examples on how to do that. From there, you can use Dev Tools -> Network to inspect the request. If you right click on the google analytics request to the 'collect' endpoint you'll see an option to Copy Request as CURL. Put that into a text editor and compare it to what your PHP code is sending.
To ACTUALLY test this without the massive propagation delay you can login to Google Analytics, go to Reports -> Realtime, and you should see your data show up within 30-60 seconds if it's working. Realtime data will NOT show up if you're using the /debug/ endpoint though.

Tracking my script installation

I am building a CMS/CRM and want to let users install this software on their server using their databases.
I would like to track some of the data from that installation, like version, so I can send updates to that installation if it is out of date. Like when Wordpress tells you a new version is available.
I also want to be able to track the number of users to be able to charge for the installation.
I am using PHP, MySQL(PDO).
Can you let me know what this process is called and any references to this process would be fantastic.
In your application you may have an array of data you'd like to track; something like this
$data = array(
'domain' => 'http://example.com',
'version' => '1.4.35',
'date_added' => '2014-08-20',
'last_update' => '2014-08-22'
);
Then you could send a request to your server to see if is anything new out there; using cURL or any other method for sending an HTTP request
$curl = curl_init("http://your-server.com/your-service/");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // convert it to JSON format
$json = curl_exec($curl);
curl_close($curl);
// this is your feedback, in JSON format
$response = json_decode($json, true);
It would be good to check the status, like this, but before the curl_close() call
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status == 201){
// ... all fine
}else{
// otherwise, do something but don't use exit() or die() in this case
}
The $response value, after decoding, could look something like this
array(
'some_key' => 'some_value',
'another_key' => 'another_value'
...
);
Now, according to the response, echo a message to the user, like this
if(isset($response['some_key']) && $response['some_key'] == 'some_value')){
echo "An update is out there, Check it out";
}

Getting images from Instagram, always null

I develop a small script on localhost (WAMP server, CURL enabled) to retrieve images from Instagram. Based on this script: see tutorial I have also set up the variables on Instagram. I'm not sure what is wrong more specifically or how to solve it (probably with authentication).
USER ID
CLIENT ID
CLIENT SECRET
WEBSITE URL
REDIRECT URI
This is my user
http://instagram.com/krondorl
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/280766222/media/recent/?access_token=df04c6989eaf4490bdac1f82554182bb");
$result = json_decode($result);
var_dump($result);
Try the code below which works for me. Make sure your URL is correct.
$json_url ='https://api.instagram.com/v1/users/280766222/media/recent/?access_token=df04c6989eaf4490bdac1f82554182bb';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json')
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$results = curl_exec($ch); // Getting jSON result string
$json_decoded = json_decode($results);
By the way I check your URL which happens to be incorrect and give me the below error.
{"meta":{"error_type":"OAuthAccessTokenException","code":400,"error_message":"The \"access_token\" provided is invalid."}}
Before you trying the code, try the URL on the browser and see whether the URL is correct.

How to stop Resource from showing up in curl_exec result

Hi I'm trying to use this script to return a value from another php script on my site without leaving the page, but I am getting the number 1 after the string (I'm assuming that the 1 is the resource number) This is the script:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
echo $result;
?>
Output is somthing like this:
"<?php include \\\\localfolder\\blabla\script.php ?>1"
and the 1 at the end is what I don't want showing up.
Thanks,
Robert
You need to set the CURLOPT_RETURNTRANSFER option to true:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
From the documentation:
CURLOPT_RETURNTRANSFER
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

Why does cURL always return a status code?

I have some PHP code that calls into the cURL library. I'm using it to get JSON data.
I have set cURL opt 'CURLOPT_RETURNTRANSFER' to 1, but still get status code..
Code follows:
<?php
function fetch_page($url)
{
$ch = curl_init();
$array = array(
'include'=>'ayam'
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
$return = fetch_page(MY_LINK_URL);
echo json_decode($return);
?>
The code looks totally correct. Try var_dump($result) before returning it to see what it is exactly.
Also, set CURLOPT_HEADER to 1 and check the view source of the output in your browser; both of these can help debug the issue. Edit the question and post the results if so we can help more effectively.
Update: Since you are using HTTPS, also add
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
That looks correct. I actually have the same problem, but when I added
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
it returns json code correctly instead of returning 1(True).
According to the PHP docs,
Returns TRUE on success or FALSE on
failure. However, if the
CURLOPT_RETURNTRANSFER option is set,
it will return the result on success,
FALSE on failure.
So that means you should get
success: the result
failure: FALSE (which is echoed as 0)
Also, if you are fetching JSON, and need to access it, use json_decode() not json_encode().
Well, you should tell us wich url you're pointing (and wich version of php you are running).
I've tried with php 5.3 on "www.google.com" and it worked as expected ($result contains the whole webpage)
Might of had a similar problem:
- cURL on local dev network problem with virtual host naming
Before you close your curl handle output this:
$result = curl_exec ($ch);
print_r(curl_getinfo($ch));
curl_close ($ch);
Here was my solution for getting around the virtual host
// This is your Virtual Hosts name
$request_host = 'dev.project';
// This is the IP
$request_url = '192.168.0.1';
$headers = array("Host: ".$request_host);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $request_url.'?'.$request_args);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
There seems to be a number of reasons why CURLOPT_RETURNTRANSFER can be ignored, and SSL certificate checking is only one of them:
In my case the culprit was CURLOPT_POST which I had set to true. I was expecting to get back a string consisting of the HTTP response header plus the response itself. Instead I was getting status code 1. Go figure. Thankfully I did not need the HTTP header so the solution for me was:
curl_setopt($ch, CURLOPT_HEADER, false);
If I did need the header info, I don't know what I would do. I've wasted an insane amount of time tracking down the problem.
Damn you PHP curl! (waves fist in anger)

Categories