CURL return null on json load file - php

My code below return NULL when I try to load a json file with Curl in PHP ! What I did wrong ? I check my phpinfo and curl is enabled.
// set HTTP header
$headers = array(
'Content-Type: application/json'
);
$url = 'http://www.mywebsite.com/json.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
// DUMP
var_dump(json_decode($result, true));
My json file :
{
"0": {
"temps": "09:03:09",
"temps_bonus": "-00:16:00",
"ordre": 1,
"numero": "10",
"ecart": ""
},
"1": {
"temps": "09:15:19",
"temps_bonus": "-00:17:00",
"ordre": 2,
"numero": "7",
"ecart": "00:12:10"
}
}
Thanks for your help...

Related

How to pass string variable from dart to php file

I'm trying to send string variable to php file with post method this is my function in dart:
Future<Verify> verifyOTP() async {
var response_verifyotp = await http.post(Uri.parse(linkverifyOTP), body: {
"OTP_code": SOTP,
});
if (response_verifyotp.statusCode == 200) {
print(response_verifyotp.body);
st_verfiy = Verify.fromJson(json.decode(response_verifyotp.body));
print(st_verfiy.status);
}
}
but it doesn't pass correctly still appear to me it's missing value
I'm try also with: "OTP_code": SOTP.toString(),
it's same
This is my php code:
<?php
session_start();
$ch = curl_init();
$OTP_code=$_POST["OTP_code"];
if(isset($_SESSION["id"]))
$id=$_SESSION["id"];
curl_setopt($ch, CURLOPT_URL, "https://www.msegat.com/gw/verifyOTPCode.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
$fields = <<<EOT
{
"lang":"EN",
"userName": "Bloom_Ducks",
"apiKey":"f92b62af08ed0be",
"code":"$OTP_code",
"id": "$id" ,
"userSender":"APP"
}
EOT;
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json"
));
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$response=json_decode($response,true);
$code=$response["code"];
if($code == 1){
json_encode(array("status" => 1));
}else{
json_encode(array("status" => 0));
}
?>

Getting error while sending http request via curl

I want to send charging request through php which I have sent via postman and it worked, but when I try this with php I m getting error response.
I have tried to send the request using curl and used function to send the request. But, after hitting the php I m getting the response that "invalid request" .
Here is the code snippet:
<?php
define('TML_CHARGE_URL2', 'http://sandbox-apigw.mytelenor.com.mm/v1/mm/en/customers/products/vas');
$client_id="MDq0MdGtZUGZWfanE8k2fva7GsLvwS0I";
$client_secret="GEzAxTE6YYSfLEAD";
$accessToken="ytSxhvjSUfNEurD5M6SOJPm6XAfu";
/* CP & Product Codes */
$cpid="15";
$login="apigwtest";
$password="apigwtestpwd";
$client_id="175612092873562378";
$msisdn="9791000601";
$prod_code = "APIGW_TEST";
$requestParamList = array("cpID" => $cpid,
"clientTransactionId" => $client_id,
"loginName" => $login,
"password" => $password,
"id" => array (
"type" => "MSISDN",
"value" => $msisdn
),
"productCode" => $prod_code
);
function callAPI($apiURL, $requestParamList) {
$jsonResponse = "";
$responseParamList = array();
$JsonData =json_encode($requestParamList);
$postData = 'JsonData='.urlencode($JsonData);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}
function oneshotpayment($requestParamList) {
return callAPI(TML_CHARGE_URL, $requestParamList);
}
function subscription_payment($requestParamList) {
return callAPI(TML_CHARGE_URL2, $requestParamList);
}
echo subscription_payment($requestParamList);
?>
The error response is like below:
{
"transactionId": "",
"timestamp": "2017-08-13T17:28:24+06:30",
"recipientMsisdn": "",
"code": "500.023.003",
"error": "Internal Server Error",
"message": "Request input is malformed or invalid"
}
You need to change your callAPI method.
1) You dont need to do urlencode after you have done json_encode
2) Remove unnecessory concatination of 'JsonData='. in string.
change you method like below
function callAPI($apiURL, $requestParamList) {
$postData = "";
$responseParamList = array();
$postData =json_encode($requestParamList);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
echo $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData),
'Authorization: Bearer ytSxhvjSUfNEurD5M6SOJPm6XAfu'
)
);
echo $jsonResponse = curl_exec($ch);
$responseParamList = json_decode($jsonResponse,true);
return $responseParamList;
}

Safe Browsing Lookup API (v4) Invalid JSON payload received

I have a php script which tries to use google Safe Browsing Lookup API (v4), but I'm getting error "Invalid JSON payload received. Unknown name \"\": Root element must be a message..."
Here is my code:
<?php
$data = '{
"client": {
"clientId": "TestClient",
"clientVersion": "1.0"
},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["LINUX"],
"threatEntryTypes": ["URL"],
"threatEntries": [
{"url": "http://www.google.com"}
]
}
}';
$apikey = "my_secret_api_key";
$url_send ="https://safebrowsing.googleapis.com/v4/threatMatches:find?key=".$apikey."";
$str_data = json_encode($data);
function sendPostData($url, $post){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", 'Content-Length: ' . strlen($post)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
$jaahas = sendPostData($url_send, $str_data);
echo "<pre>";
var_dump($jaahas);
?>
Is there something wrong with the json-data array formatting or what might be the problem?
You're running json_encode on data which is already encoded.
ie. change this line:
$jaahas = sendPostData($url_send, $str_data);
to
$jaahas = sendPostData($url_send, $data);

Stream Target in wowza

I have implemented for creating stream target through php with the help of curl.
<?php
$service_url = 'http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/liveSource';
$curl = curl_init($service_url);
$curl_post_data ='
{
"restURI": "http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/testlive"
"stream_target": {
"name": “defaultTarget”,
"provider": "rtmp",
"username": "liveSource",
"password": "Welcomehere",
"stream_name": “customTarget”,
"primary_url": "http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/liveSource",
} "https://api.cloud.wowza.com/api/v1/stream_targets"
}';
$headers = array(
'Content-Type: application/json; charset=utf-8',
'Accept: application/json; charset=utf-8'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response;
?>
But it is showing error as success as false with code 401
{"message":"The request requires user authentication","success":false,"wowzaServer":"4.4.0","code":"401"}
If you are trying to create a stream target in Wowza Streaming engine, I would start with a simple example as follows:
<?php
// Modify values here
$entryName = "ppSource";
$appName = "live";
$streamName = "myStream";
$userName = "user";
$password = "pass";
$profile = "rtmp";
$server = "localhost";
// End modification
$url = "http://{$server}:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/{$appName}/pushpublish/mapentries/{$entryName}";
$json = "{
\"restURI\": \"http://{$server}:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/{$appName}/pushpublish/mapentries/{$entryName}\",
\"serverName\":\"_defaultServer_\",
\"sourceStreamName\": \"{$streamName}\",
\"entryName\": \"{$entryName}\",
\"profile\": \"{$profile}\",
\"host\": \"{$server}\",
\"application\":\"{$appName}\",
\"userName\":\"{$userName}\",
\"password\":\"{$password}\",
\"streamName\":\"{$streamName}\"
}'";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
// curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
// curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-type:application/json; charset=utf-8',
'Content-Length: '.strlen($json)));
$contents = curl_exec($ch);
curl_close($ch);
$obj = json_decode($contents);
var_dump($obj);
However if you are trying to initiate a live stream through our cloud api, here is a small example (only) of what your request might look like:
// Modify values here
$cloudApiKey = "xxxxxxxxxxx";
$cloudApiAccessKey="xxxxxxxxxx";
// End modification
$url = "https://api.cloud.wowza.com/api/v1/live_streams";
$json = "{
\"live_stream\": {
\"id\": \"1234abcd\",
\"name\": \"MyLiveStream\",
\"transcoder_type\": \"transcoded\",
\"billing_mode\": \"pay_as_you_go\",
\"broadcast_location\": \"us_west_california\",
\"recording\": false,
\"encoder\": \"wowza_gocoder\",
\"delivery_method\": \"push\",
\"use_stream_source\": false,
\"aspect_ratio_width\": 1280,
\"aspect_ratio_height\": 720,
\"connection_code\": \"033334\",
\"connection_code_expires_at\": \"2015-11-25T12:06:38.453-08:00\",
\"source_connection_information\": {
\"primary_server\": \"6022e9.entrypoint.cloud.wowza.com\",
\"host_port\": 1935,
\"application\": \"app-464b\",
\"stream_name\": \"32a5814b\",
\"disable_authentication\": false,
\"username\": \"client2\",
\"password\": \"1234abcd\"
},
\"player_responsive\": true,
\"player_countdown\": false,
\"player_embed_code\": \"in_progress\",
\"player_hds_playback_url\": \"http://wowzadev-f.akamaihd.net/z/32a5814b_1#7217/manifest.f4m\",
\"player_hls_playback_url\": \"http://wowzadev-f.akamaihd.net/i/32a5814b_1#7217/master.m3u8\",
\"hosted_page\": true,
\"hosted_page_title\": \"MyLiveStream\",
\"hosted_page_url\": \"in_progress\",
\"hosted_page_sharing_icons\": true
}
}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json; charset=utf-8',
'Content-type:application/json; charset=utf-8',
'wsc-api-key: '.$cloudApiKey,
'wsc-access-key: '.$cloudApiAccessKey,
);
$contents = curl_exec($ch);
curl_close($ch);
This is obtained from the examples page and modified to fit into a PHP related request.
Thanks,
Matt

json_decode is not returning proper php array of api response with curl call

I am working on the shipping API for one of my client. I have the shipping api from the vendor. On making curl request in json format, the json response is not converted into php array? Find the code below:
$params['format'] = 'json';
$params['data'] =json_encode($package_data);
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$url = "http://test.shipping.co/push/json/?token=".$token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
$results = json_decode($result, true);
print_r($results);
Here I have 2 print_r function, and following is the output:
{ "cash_pickups_count": 1.0, "cod_count": 0, "success": true,
"package_count": 1, "upload_wbn": "UPL21969440", "replacement_count":
0, "cod_amount": 0.0, "prepaid_count": 0, "pickups_count": 0,
"packages": [ { "status": "Success", "waybill": "0008110000125",
"refnum": "8", "client": "demo", "remarks": "", "cod_amount":
21841.0, "payment": "Cash" } ], "cash_pickups": 21841.0 }1
1
I am receiving 2 output as : 1
I want to access the array in php of this response. I tried json_decode() but it is not responding properly.
Need your inputs here. Thanks in advance.
The problem is that you haven't set CURLOPT_RETURNTRANSFER option. In this case CURL outputs response directly into STDOUT (browser) and curl_exec returns true. Because of this json_decode cannot decode $result variable (since it has value = true).
So you have to set CURLOPT_RETURNTRANSFER option:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
$results = json_decode($result, true);
print_r($results);
you forgot to add this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Please try this below one
$results = json_decode(file_get_contents('php://input'), true);
instead of
$results = json_decode($result, true);

Categories