I want to decode Json returned from the WebService, And it should set a cookie, that i want to use to call next WebService API. I am not sure how to set a cookie, and decode this json.
I tried decoding it, but get the error. I need to extract sessionId. You can use the WebService.. I have put this on Internet.
Here is my code sample
<?php //extract data from the post
extract($_POST); //set POST variables
$url = 'http://202.83.243.119/ems/loginByEID.json';
$fields = array(
'eid'=>urlencode("7ea888b6-36e9-49db-84f3-856043841bef")
);
//url-ify the data for the POST
foreach($fields as $key=>$value) {
$fields_string .=
$key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection $ch = curl_init();
//set the url, number of POST vars,
POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post $result =
curl_exec($ch);
//close connection curl_close($ch);
//decoding Json $obj =
json_decode($result);
print $obj->{'stat'};
?>
Use setcookie() to set a cookie.
Avoid extract() like the plague; it can be used to introduce any client-specified variables into your code.
Use $fields_string = http_build_query($_GET) to build a query string instead of your hodge-podge above.
Format your code properly. For example, you put the $obj = inside the previous comment line.
Related
I am executing a curl request and get a response which returns a json response. Below is the code after the response is sent back.
Response: "Zeros Replaced real token"
{"success":true,"result":{"token":"000000000","serverTime":1471365111,"expireTime":1471365411}}1
Code Used (For Testing) and accessing property:
$json = json_decode($result);
print_r($json); // Prints the Json Response
$firsttry = $json->result['token']; //Access Property results in error :Trying to get property of non-object
$secondtry = $json['token'];
echo $firsttry.'<br>';//Code can't continue because of error from $firsttry.
print_r( $secondtry.'<br>');//Nothing Prints at all
I did notice a weird anomaly where it prints a 1 at the end, where as if i do
json_encode($json);
The return response replaces the one at the end of the string with a "true"
Could the "1 or true" at the end be throwing of the json decode?
Maybe I am missing something simple?
As Requested full test code
$url = "https://website.com/restapi.php";
//username of the user who is to logged in.
$userName="adminuser"; //not real user
$fields_string; //global var
$fields = array( //array will have more in the future
'username' => urlencode($userName)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { global $fields_string;
$fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url.'?'.$fields_string.'operation=getchallenge');
curl_setopt($ch,CURLOPT_POST, count($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
json_decode(), by default makes child objects into stdClass objects rather than arrays unless they are explicitly arrays.
Try something like:
$firsttry = $json->result->token;
The var_dump shows you the data type. Since result itself is an object, access its token with -> rather than []
$response = '{"success":true...}'
$json = json_decode($response); //var_dumping this will show you it's an object
echo $json->result->token; // 000000000
I figured out the issue. In the Curl Options I did not have
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Once i put this in #GentelmanMax solution worked for me, but the issue was in the curl response responding directly, where as the return transfer sends back a string that php can work with, which then allowed json_decode()to function as is should. I knew it was something simple.
I've been trying to use the code below to send sms but it does not send when I loop. It only works if I just pick one number from database. I have over 5,000 numbers in the database and wish to send an sms to all of them at the same time, Please help.
mysql_select_db($database_xxx, $xxx);
$query_rs = "SELECT phone FROM `notify` order by id asc LIMIT $l1 , $l2";
$rs= mysql_query($query_rs, $xxx) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);
$totalRows_rs= mysql_num_rows($rs);
$phone = $row_rs['phone'];
// Do while loop to send sms.
while($row=mysql_fetch_assoc($rs)){
// Let's do some formatting and keep smiling.
$giringirin = ereg_replace("[^0-9]", "", $phone );
if (strlen($giringirin) == 11) {
$phone1=substr($giringirin, 1);
$phone= "234$phone1";
} elseif (strlen($giringirin) == 13){
$phone = $giringirin;
}
extract($_POST);
//set POST variables
$url = "http://sms.xxx.com/bulksms/bulksms.php?username=$username&password=$password&message=$smsmessage&mobile=$phone&sender=$sender";
$fields = array(
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
if ($result == '1801') { echo "SMS has also been sent to the Customer ($phone) \n";} else { echo "Oooops, No sms was sent";}
//close connection
curl_close($ch);
}
Your code is confusing...
curl_setopt($ch,CURLOPT_POST,count($fields));
CURLOPT_POST is a boolean flag. Either you're doing a post, or you're not. The number of fields you're posting is irrelevant.
You're building up a series of variables/values to be posted, but doing it via string operations. CURL is perfectly capable of taking an array and doing all that for you, reducing your entire foreach loop to just
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
You're using extract() on $_POST, which pollutes your script's variable namespace with any garbage a malicious user cares to send over - you're essentially replicating PHP's utterly moronically brain-dead register_globals all over again.
You're using ereg, which has been deprecated for approximiately 5 million internet years. You should be using the preg functions insteadl
What happens when you run this script in the browser? Blank page? Something? Error?
Start by changing
$url = "http://sms.xxx.com/bulksms/bulksms.php?username=$username&password=$password&message=$smsmessage&mobile=$phone&sender=$sender";
to
$url = "http://sms.xxx.com/bulksms/bulksms.php?username=".$username."&password=".$password."&message=".$smsmessage."&mobile=".$phone."&sender=".$sender."";
I have this bit of javascript:
var jsonString = "some string of json";
$.post('proxy.php', { data : jsonString }, function(response) {
var print = response;
alert(print);
and this bit of PHP (in proxy.php):
$json = $_POST['json'];
//set POST variables, THIS IS WHERE I WANT TO POST TO!
$url = 'http://my.site.com/post';
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, "data=" . urlencode($json));
//execute post (the result will be something like {"result":1,"error":"","pic":"43248234af832048","code":"234920348239048"})
$result = curl_exec($ch);
$response = json_decode($result);
$imageHref = 'http://my.site.com/render?picid=' . $response['picid'];
//close connection
curl_close($ch);
echo $imageHref;
I am trying to post data to an external site using a proxy. From there, I append the picid that the site responds with and append it to the URL to get the image URL.
Am I missing something here? I am not getting anything in response and it seems like my data is not even being posted (when I try echo $json after the first line in proxy.php, I get an empty string). Why am I not able to echo the JSON? Is my implementation correct?
Thanks!
In your Javascript code, you are using this :
{ data : jsonString }
So, from your PHP code, should you not be reading from $_POST['data'], instead of $_POST['json'] ?
If necessary, you can use var_dump() to see what's in $_POST :
var_dump($_POST);
Edit after the comment : if you are getting a JSON result such as this :
{"result":1,"error":"","pic":"43248234af832048","code":"234920348239048"}
This is a JSON object -- which means, after decoding it, you should access it as an object in PHP :
$response = json_decode($result);
echo $response->pic;
Note : I don't see a picid element in that object -- maybe you should instead use pic ?
Here too, though, you might want to use var_dump(), to see how your data looks like :
var_dump($response);
try this:
$json = $_POST['data'];
or even better do
var_dump($_POST);
to see what is actually in your post when you start
I've researched everywhere and cannot figure this out.
I am writing a test cUrl request to test my REST service:
// initialize curl handler
$ch = curl_init();
$data = array(
"products" => array ("product1"=>"abc","product2"=>"pass"));
$data = json_encode($data);
$postArgs = 'order=new&data=' . $data;
// set curl options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArgs);
curl_setopt($ch, CURLOPT_URL, 'http://localhost/store/rest.php');
// execute curl
curl_exec($ch);
This works fine and the request is accepted by my service and $_Post is populated as required, with two variables, order and data. Data has the encoded JSON object. And when I print out $_Post['data'] it shows:
{"products":{"product1":"abc","product2":"pass"}}
Which is exactly what is expected and identical to what was sent in.
When I try to decode this, json_decode() returns nothing!
If I create a new string and manually type that string, json_decode() works fine!
I've tried:
strip_tags() to remove any tags that might have been added in the http post
utf8_encode() to encode the string to the required utf 8
addslashes() to add slashes before the quotes
Nothing works.
Any ideas why json_decode() is not working after a string is received from an http post message?
Below is the relevant part of my processing of the request for reference:
public static function processRequest($requestArrays) {
// get our verb
$request_method = strtolower($requestArrays->server['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method) {
case 'post':
$data = $requestArrays->post;
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if (isset($data['data'])) {
// translate the JSON to an Object for use however you want
//$decoded = json_decode(addslashes(utf8_encode($data['data'])));
//print_r(addslashes($data['data']));
//print_r($decoded);
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
Turns out that when JSON is sent by cURL inside the post parameters & quot; replaces the "as part of the message encoding. I'm not sure why the preg_replace() function I tried didn't work, but using html_entity_decode() removed the " and made the JSON decode-able.
old:
$return_obj->setData(json_decode($data['data']));
new:
$data = json_decode( urldecode( $data['data'] ), true );
$return_obj->setData($data);
try it im curious if it works.
Is there something simpler than the following.
I am trying to make a GET request to a PHP script and then exit the current script.
I think this is a job for CURL but is there something simpler as I don't want to really worry about enabling the CURL php extension?
In addition, will the below start the PHP script and then just come back and not wait for it to finish?
//set GET variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name)
);
//url-ify the data for the GET
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_GET,count($fields));
curl_setopt($ch,CURLOPT_GETFIELDS,$fields_string);
//execute GET
$result = curl_exec($ch);
//close connection
curl_close($ch);
I want to run the other script which contains functions when a condition is met so a simple include won't work as the if condition wraps around the functions, right?
Please note, I am on windows machine and the code I am writing will only be used on a Windows OS.
Thanks all for any help and advice
$url = 'http://domain.com/get-post.php?lname=' . urlencode($last_name) . '&fname=' . urlencode($first_name);
$html = file_get_contents($url);
If you want to use the query string assembly method (from the code you posted):
//set GET variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name)
);
//url-ify the data for the GET
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
$html = file_get_contents($url . '?' . $fields_string);
See:
http://php.net/manual/en/function.file-get-contents.php