I have this php file that gets the points (id,name,geolocation) of london.The problem is that I get the correct results as a json format but when i decode it and trying to get to contains array of results I get an error.How i can get the data from '/location/location/contains' attribute?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>search</title>
</head>
<body>
<?php
function freebasequery ($fid){
$query = array(array('id' => $fid, '/location/location/contains'=>array(array('id'=>NULL,'name' => NULL,'/location/location/geolocation' =>array(array('/location/geocode/longitude' =>NULL,'/location/geocode/latitude' => NULL))))));
$query_envelope = array('query' => $query);
$service_url = 'http://api.freebase.com/api/service/mqlread';
$url = $service_url . '?query=' . urlencode(json_encode($query_envelope));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$points=freebasequery('/en/london');
//echo $points;
$results=json_decode($points)->result;
foreach($results as $poi){
echo $poi->id;
$contains="/location/location/contains";
$poisarray=$poi->$contains;
foreach($poisarray as $point){
echo $point->id;
}
}
?>
</body>
</html>
The error it was on json_decode ( It requires to have a true) the solution is:
json_decode($points,true);
and then I can access the data array I want like this:
$results["result"][0]["/location/location/contains"];
Related
I am trying to run this API(https://developer.vimeo.com/api/reference/videos#get_video). My goal is to call the API and print out the result, because after I run the the code, nothing is printed from the API call. Appreciate if anyone can help me. Thanks :
FYI, these are my code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
require ("vendor/autoload.php");
use Vimeo\Vimeo;
$client = new Vimeo("{client_id}", "{client_secret}", "{access_token}");
$video_id ="447518879";
$response = $client->request("/videos/$video_id");
//var_dump($response['body']);
if($response['status'] === 200){
echo json_encode($response['body']['message']);
}
else {
echo json_encode($response['body']['error']);
}
?>
</body>
</html>
according to Vimeo API for PHP. the response it's an array with have body, header and status. Vimeo API PHP
to access the body. put this in your code:
var_dump($response['body']);
if you wanna print as a JSON in your page:
echo json_encode($response['body']);
I tested this script bellow in here. and it's working fine:
require 'vendor/autoload.php';
$client = new Vimeo("{client_id}", "{client_secret}", "{access_token}");
$video_id = "451686900";
$response = $client->request("/videos/$video_id");
print_r($response);
I have to create an simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<form method="post" action="process.php">
<input type="text" name="firstname" placeholder="rahul_sharma">
<button type="submit">send</button>
</form>
</body>
</html>
From my process.php file, I have to hit an url like below:
https://stackoverflow.com/api?rahul_sharma
which will give back an json response
{"status":"Success","username":"your username is RAHULSHARMA"}
If status is success, have to display the username value.
New to php.Any help is appreciated.
you can call API using curl.
$url='https://stackoverflow.com/api?';
$call_url = $url . $_POST['first_name'] ;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $call_url,
CURLOPT_SSL_VERIFYPEER => false,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;//{"status":"Success","username":"your username is RAHULSHARMA"}
In your process.php file, you can use the $_POST superglobal to fetch the form data.
$firstname = $_POST['firstname'];
After that you can concatenate it using the . operator to form the url.
$url = "https://your-api-site.com/api?" . $firstname;
Next you can fetch the content from the url using a curl request.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
The result from fetching the url will be obtained in the $output variable. Suppose the result from your API is a JSON string like the one you provided, you can use json_decode PHP function to convert it to an associative array.
$result = json_decode($output);
Now you can use if conditions to check if status is Success and display the username.
if ($result['status'] == "Success") {
echo $result['username'];
}
I created a php page that receive in input a string that is an encoded Json, i must decript this string and put all Json attributes in session.
This page is login.php.
To test this page i created another page named test.php.
In this page i encript a Json and sent it to login.php.
The problem is that all works fine (encription, sending, decription) but the variables is not saved in session.
I tried to open directly login.php, i set a fixed encripted json and in this case all works fine.
Some help???
login.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TantoSvago</title>
<script src="../vendors/jquery/jquery-2.1.4.min.js"></script>
<script src="../js/angular.min.js"></script>
<script src="../js/ui-bootstrap-tpls-0.12.0.js"></script>
<script src="../js/angular-google-maps.min.js"></script>
<script src="https://code.angularjs.org/1.2.28/angular-route.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBze9qLOsDpAWj8938CYJSVsopwrkuWbPA&callback=initMap"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-sanitize.js"></script>
<script src="../js/markerclusterer.js"></script>
<script src="../js/angular.rangeSlider.js"></script>
<script src="../js/assets/app.js"></script>
</head>
<body ng-app="tantoSvagoApp">
<?php
session_start();
include 'AES.php';
$inputText = file_get_contents("php://input");
//$inputText = "RFk0ZGRtZWQ0NUdrNzNHa3BtYVBCdklEYUlUMk5CUUdGMUF5V2tFSHVWRTRsUEtYZTRiL1FmVGNsY2pKZHdIb2lkOG1ra3BMODdPZUVuUmQzN3Vqd1JpamZGRmloeW1EU09xVFMzbU1Jd1Z0N1dNZzF6MitDYWlHZ3p6VUVyRXgycDYrbHU1Tm0yYVQ4amNuK0hheUNyODErSXZqMzVIQm9NdCtOQU0vVTcyMVBUQ09YQmRZTWZkM1JsbHk0aVJJaFFJdUYrR0JWZzF5WG1HUXl6QnFEa0d0V2ozNWl2YmhheGp6UkpXSVRFZDh4TXM3Q2Vyb2liQWp1UmJEZXNvYnFWNmkzc3ZzWEp4ak92MjB0ZWpjYWJGOFVoMEw0Vk8rNTI2WXhoMTRvYW89";
$inputText = base64_decode($inputText);
$inputKey = "466169626f20536f74662052756c657a";
$blockSize = 256;
$aes = new AES($inputText, $inputKey, $blockSize);
$enc = $aes->decrypt();
$inputJson = json_decode($enc);
$email = $inputJson->{'email'};
$firstName = $inputJson->{'firstName'};
$lastName = $inputJson->{'lastName'};
$phone = $inputJson->{'phone'};
$credit = $inputJson->{'credit'};
$userId = $inputJson->{'userId'};
$supportPhone = $inputJson->{'supportPhone'};
$supportMail = $inputJson->{'supportMail'};
$paymentTypes = $inputJson->{'paymentTypes'};
if (isset($email)) {
$_SESSION['email'] = $email;
}
if (isset($firstName)) {
$_SESSION['firstName'] = $firstName;
}
if (isset($lastName)) {
$_SESSION['lastName'] = $lastName;
}
if (isset($phone)) {
$_SESSION['phone'] = $phone;
}
if (isset($credit)) {
$_SESSION['credit'] = $credit;
}
if (isset($userId)) {
$_SESSION['userId'] = $userId;
}
if (isset($supportPhone)) {
$_SESSION['supportPhone'] = $supportPhone;
}
if (isset($supportMail)) {
$_SESSION['supportMail'] = $supportMail;
}
if (isset($paymentTypes)) {
$_SESSION['paymentTypes'] = $paymentTypes;
}else{
$_SESSION['paymentTypes'] = 'welfare';
}
echo 'ok';
?>
<div ng-controller="loginController"></div>
</body>
</html>
test.php
<?php
$inputText = '{"firstName":"Mario","lastName":"Rossi","email":"mario.rossi#gmail.com","phone":"02 342522","userId":2,"credit":30,"paymentTypes":"welfare","supportMail":"supporto#welfarebit.it","supportPhone":"0321 444999"}';
include 'AES.php';
$inputKey = "466169626f20536f74662052756c657a";
$blockSize = 256;
$aes = new AES($inputText, $inputKey, $blockSize);
$enc = $aes->encrypt();
$result = base64_encode($enc);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://welfarebitexperience.tantosvago.it/login/login.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $result );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($result))
);
$result = curl_exec($ch);
curl_close($ch);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body onload="test()">
<form id="B2BKv" name="B2BKv" action="http://welfarebitexperience.tantosvago.it/login/login.php" method="POST">
<input type="hidden" id="MPCookieManager" name="MPCookieManager" value="<?php echo $result; ?>">
</form>
<script language="javascript">
function test() {
document.B2BKv.submit();
}
</script>
</body>
</html>
Try and put session_start() before the html tag on every page
<?php
session_start();?>
<html>
<head>
and this
<?php
session_start();
$inputText = '{"firstName":"Mario","lastName":"Rossi","email":"mario.rossi#gmail.com","phone":"02 342522","userId":2,"credit":30,"paymentTypes":"welfare","supportMail":"supporto#welfarebit.it","supportPhone":"0321 444999"}';
include 'AES.php';
$inputKey = "466169626f20536f74662052756c657a";
As described over here, session_start() needs to be executed before any content gets returned.
What strikes me from the start is where session_start() is called. PHP manual states: to use cookie-based sessions, session_start() must be called before outputting anything to the browser.
I need to post to a URL and I am doing this with curl. But the problem is with the HTML content I am posting. I am using this page which I am requesting to send an html email. So it will have inline styles. When I urlencode() or rawurlenocde() these style attribute is stripped. So the mail will not look correct. How can I avoid this and post the HTML as it is ?
This is my code :
$mail_url = "to=".$email->uEmail;
$mail_url .= "&from=info#domain.com";
$mail_url .= "&subject=".$email_campaign[0]->email_subject;
$mail_url .= "&type=signleOffer";
$mail_url .= "&html=".rawurlencode($email_campaign[0]->email_content);
//open curl request to send the mail
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count(5));
curl_setopt($ch,CURLOPT_POSTFIELDS,$mail_url);
//execute post
$result = curl_exec($ch);
Here is an example, use http_build_query() to build your post data from an array of values:
<?php
//Receiver debug
if($_SERVER['REQUEST_METHOD']=='POST'){
file_put_contents('test.POST.values.txt',print_r($_POST,true));
/*
Array
(
[to] => example#example.com
[from] => info#domain.com
[subject] => subject
[type] => signleOffer
[html] =>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Mail Template</title>
<style>.yada{color:green;}</style>
</head>
<body>
<p style="color:red">Red</p>
<p class="yada">Green</p>
</body>
</html>
)
*/
die;
}
$curl_to_post_parameters = array(
'to'=>'example#example.com',
'from'=>'info#domain.com',
'subject'=>'subject',
'type'=>'signleOffer',
'html'=>'
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Mail Template</title>
<style>.yada{color:green;}</style>
</head>
<body>
<p style="color:red">Red</p>
<p class="yada">Green</p>
</body>
</html>
'
);
$curl_options = array(
CURLOPT_URL => "http://localhost/test.php",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $curl_to_post_parameters ), //<<<
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
$curl = curl_init();
curl_setopt_array($curl, $curl_options);
$result = curl_exec($curl);
curl_close($curl);
?>
Do a POST as described in this post:
Passing $_POST values with cURL
It should solve your problem.
I am using Google Contact API V3 with OAuth 2.0 to retrieve the contacts from Google Account, I am getting a OAuth Token from a child window using jQuery, and after post that token to another file which should get the User's Contacts, but when I pass the token to get the contacts from Google, but it gives an error "Warning: file_get_contents(https://www.google.com/m8/feeds/contacts/default/full&oauth_token=[token]) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Authorization required in ...\getContacts.php on line 7"
Here is my code for reference:
In my index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
$(document).ready(function(){
$('#newWindow').click(function (event){
var url = $(this).attr("href");
var windowName = "popUp";//$(this).attr("name");
var windowSize = windowSizeArray[ $(this).attr("rel") ];
window.open(url, windowName, windowSize);
event.preventDefault();
});
});
function getContacts(accessToken){
$.post("getContacts.php?token="+accessToken,function(data){
$("#contacts").html(data);
});
}
</script>
</head>
<body>
Click Here! to import your contact.
<div id="contacts"></div>
in my childWindow.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.8.1.min.js"></script>
</head>
<body>
<?php
$authcode= $_GET["code"];
$clientid='My Client ID';
$clientsecret='My Client Secret';
$redirecturi='http://localhost/googleContacts/validate.php';
$fields=array(
'code'=> urlencode($authcode),
'client_id'=> urlencode($clientid),
'client_secret'=> urlencode($clientsecret),
'redirect_uri'=> urlencode($redirecturi),
'grant_type'=> urlencode('authorization_code')
);
//url-ify the data for the POST
$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//to trust any ssl certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//extracting access_token from response string
$response= json_decode($result);
$accesstoken= $response->access_token;
//echo "<span>".$accesstoken."</span><hr>";
?>
<script type="text/javascript">
$(document).ready(function() {
window.opener.getContacts("<?php echo $accesstoken; ?>");
window.close();
});
</script>
And finally in my getContacts.php:
<?php
$accesstoken = $_REQUEST['token'];
//passing accesstoken to obtain contact details
$xmlresponse= file_get_contents('https://www.google.com/m8/feeds/contacts/default/full&oauth_token='.$accesstoken);
//reading xml using SimpleXML
$xml= new SimpleXMLElement($xmlresponse);
foreach($xml->entry as $content){
$nameEmail = "";
if(!empty($content->title)){
$nameEmail .= "<span style=\"text-decoration:underline;\">".$content->title."</span>: ";
}
$gd = $content->children('http://schemas.google.com/g/2005');
if($gd){
$nameEmail .= $gd->attributes()->address."<hr>";
echo $nameEmail;
}else{
echo $nameEmail."<hr>";
}
}
?>
Please tell me where is the mistake. Thanks in advance
To allow https for file_get_contents() you should have enabled the php extension php_openssl.dll.
Make sure that in your php.ini you have this lines:
extension=php_openssl.dll
allow_url_fopen = On