get data from URL using file_get_contents and cURL - php

I am using codeigniter framework.
I want to retrieve the data from the URL provided. I already tried this answers: tried.
Problem is that when i access the url that time it is printing the data. but when i try it with file_get_contents function, it is not going to print any data.
<?php
$url ='https://test.com/getSessionData';
$test = file_get_contents($url);
$t = json_decode($test);
var_dump($t);
?>
That url returns json data like:
{
"email": "test#t.com",
"LOGIN": true,
"name": "testing",
"logintype": "ca"
}
Also tried using cURL:
<?php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
?>
But it is not working and it returns empty. i have checked that allow_url_fopen is on.

This might helpful
http://php.net/manual/en/migration56.openssl.php
So code looks like this:
<?php
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/path/to/bundle/ca-bundle.crt",
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://test.com/getSessionData", false, stream_context_create($arrContextOptions));
echo $response; ?>

This is the class I said:
/**
* Created by PhpStorm.
* User: rain
* Date: 15/11/2
* Time: 下午4:08
*/
class MyCurlLibrary{
public static function getRequest($url,Array $data=array(),$isNeedHeader=0){
$ch = curl_init();
if($data){
$bindQuery = http_build_query($data);
$url.="?".$bindQuery;
}
curl_setopt($ch, CURLOPT_URL, $url);
//if need return
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//this is for https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, $isNeedHeader);//if contains header
//this is for web redirect problem
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public static function postRequest($url,Array $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post Data
curl_setopt($ch, CURLOPT_POST, 1);
// post variable
if($data){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($ch);
curl_close($ch);
//return data
return $output;
}
}
/**
* sample
*
* //test Data
$url = "http://localhost:8080/test/test.php";//改文件有代码 print_r($_GET); print_r($_POST)
$data = array('a'=>'b','c'=>'d',8=>666,888);
//test get function
$result = MyCurl::getRequest($url,$data);
//test post function
$result = MyCurl::postRequest($url,$data);
//print result
var_dump($result);
*
*
*/

Related

How to properly send a JSON CURL to Slack?

I have a CURL code that I use to integrate with GetResponse and I thought ill go ahead and copy/paste it for slack too. For some reason there are no errors at all yet slack is empty of requests (a POST to this URL with Postman works just fine). What am I missing? I couldn't find a solution the whole night.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
$slackReporting_error = "";
if(empty($slackReporting_res->error)){
echo "OK";
} else {
$slackReporting_error = $slackReporting_res->error->message;
}
echo $slackReporting_error;
?>
I always get an OK.
Since you din't return anything from function so you are getting nothing inside $slackReporting_res .Do like below:-
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function slackReporting($data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hooks.slack.com/services/XXXX/XXXX/XXXXXX');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);exit;
}
curl_close($ch);
return $content;
}
$slackReporting_data = array(
'text' => "`New Lead` `+34 today`.",
'username' => "Leads",
'mrkdwn' => true
);
$slackReporting_res = json_decode(slackReporting($slackReporting_data));
var_dump ($slackReporting_res); //check output and work accordingly
?>
And now Op's got error and solved through this link(mentioned by OP in comment):-
PHP - SSL certificate error: unable to get local issuer certificate
Here is a simple example of how to use slack with curl
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
$msg = array('text' => $txt);
$c = curl_init(SLACK_WEBHOOK);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
curl_exec($c);
curl_close($c);
}
?>
Snippet taken from here

how to view final url before submission curl php

I want to know final url just before executing curl to check all parameters passing as desired. how to view that.
<?PHP
function openurl($url) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
openurl($sms_url);
?>
desired output to check all params and its values passing correct..
http://remoteserver/plain?user=user123&password=user#user!123&Text=TESThere
You forgot to add the $postvars as parameter to your function.
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
}
$postvars = array('user' => "user123",'password' => "user#user!123",'Text' => "Test");
$sms_url ="http://remoteserver/plain";
// create a test var which we can display on screen / log
$test_url = sms_url . http_build_query($postvars);
// either send it to the browser
echo $test_url;
// or send it to your log (make sure loggin is enabled!)
error_log("CURL URL: $test_url", 0);
openurl($sms_url, $postvars);

Attaching get fields to URL using Curl in PHP

I am able to perform server and client side redirects using Curl but I am unable to attach GET fields to the URL via a get request, here is my code:
$post = curl_init();
curl_setopt($post,CURLOPT_URL,$url);
curl_setopt($post,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($post, CURLOPT_USERAGENT,'Codular');
curl_setopt($post, CURLOPT_CUSTOMREQUEST,'GET');
curl_exec($post);
curl_close($post);
Nothing gets attached when I perform the execution, what am I doing wrong?
New code I am using:
function curl_req($url, $req, $data='')
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
if (is_array($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$temp = array("akash"=>"test");
$result = curl_req("http://localhost/test.php", 'POST', $temp);
echo $result;
print_r($result);
test.php:
print_r($_POST);
print_r($_REQUEST);
Try this:
// Fill in your DATA below.
$data = array('param' => "datata", 'param2' => "HelloWorld");
/*
* cURL request
*
* #param $url string The url to post to 'theurlyouneedtosendto.com/m/admin'/something'
* #param $req string Request type. Ex. 'POST', 'GET' or 'PUT'
* #param $data array Array of data to be POSTed
* #return $result HTTP resonse
*/
function curl_req($url, $req, $data='')
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
if (is_array($data)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Fill in your URL below.
$result = curl_req("http://yourURL.com/?", "POST", $data)
echo $result;
This works fine for me.

parse json data from curl

server.php
// some code here .....
// this is the end of the file:
$json_data = array(
'test1'=>hello world,
'test2'=>hello stack
);
echo json_encode($json_data);
api.php
$text = api("http://example.com/?TEXT=$text&APIKEY=$apikey");
// return the json from server.php file
echo $text;
function api($url) {
$ch = curl_init();
$timeout = 20;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
the file api.php return the json successfully
{"test1":"hello world","test2":"hello stack"}
The problem is when I try to parse the returned JSON in order to get the value of test1 it doesn't show anything.
I tried something like this it but can't parse the JSON.
$obj=json_decode($text);
// dosent show anything
echo $obj->test1;
Put quotes around the values in your array.
$json_data = array(
'test1'=>"hello world",
'test2'=>"hello stack");

getting JSON object from a GET cURL in php

Here is my code:
$ch = curl_init('');
$request = 'where={"place":"'.$place.'"}&count=1&limit=0';
$url = "https://api.parse.com/1/classes/className" . "?" . $request;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Parse-Application-Id: ...',
'X-Parse-REST-API-Key: ...
));
//curl_setopt($ch, CURLOPT_POST, true);
// Execute
$result = curl_exec($ch);
// Close connection
curl_close($ch);
Here is the output:
{"results":[],"count":0}
I want to get only he number in count.
I tried this:
$json_res = json_decode($result, true);
echo 'Number : '.$json_res['count'];
but the output becomes:
Number :
If i do json_encode the result is just a True value.
I tried added this:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
but didn't change anything.
What am I missing?
EDIT: doing a var_dump on $json_res gives me that: int(1).
Why is that?
Curl does not return the output if you don't set the CURLOPT_RETURNTRANSFER option
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Categories