retrieve Json information from php file using cURL - php

ive seen lots of examples and to be honest i am a little confused on the matter.
I have been doing php for only 3 weeks so i am very new to this.
Basically i have wrote a function that asks for a token and a url, then it checks the database to if is exists, if it exists it then will offer a json array. I was wondering how select file and enter the function and retrieve the json data using cURL.
The function i have created is within the http://www.domain.com/api.php
Here is the function code:
function check_api_website($token, $url){
$token = trim(htmlentities($token));
$safetoken = mysql_real_escape_string($token);
$url = trim(htmlentities($url));
$safeurl = mysql_real_escape_string($url);
$checkwebsite = "SELECT message,islive FROM websitetokens WHERE url='".$safeurl."' AND token='".$safetoken."'";
$checkwebsite_result = mysql_query($checkwebsite) OR die();
$numberofrows = mysql_num_rows($checkwebsite_result);
if($numberofrows > 0){
$website = mysql_fetch_array($checkwebsite_result);
$message = stripslashes($website["message"]);
$islive = stripslashes($website["islive"]);
json_encode(array(
'message' => $message,
'islive' => $islive,
));
$date = date('Y-m-d');
$time = gmdate('H:i');
$loginwebsite = "UPDATE websitetokens SET loggedin='".$date."',time='".$time."' WHERE url='".$safeurl."' AND token='".$safetoken."'";
$loginwebsite_result = mysql_query($loginwebsite) OR die();
} else {
json_encode(array(
'message' => '',
'islive' => '1',
));
}
}
As you can see the json_encode is there and that is what i am wanting to retrieve.
If you could please explain a little also would help my learning.
Thanks for the help in advance :)

A simple request with cUrl to retrieve and parse JSON data would look like this:
function get_json($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($resultCode == 200) {
return json_decode($data);
} else {
return false;
}
}
You can place this method in your code and simply call it like this:
$json = get_json('http://www.example.com');
Good to see you're aware SQL injections and escaping the input. However, some PHP configurations might have the so called 'magic quotes' enabled, which escapes quotes on any input parameters with slashes.
If those slashes aren't stripped before calling mysql_real_escape_string, the resulting string will be double escaped. You can use a method like this to make sure everything gets escaped properly:
function escape_string($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return mysql_real_escape_string($string);
}

Related

JSON: Update base64 string using url JSON

I'm new to JSON Code. I want to learn about the update function. Currently, I successfully can update data to the database. Below is the code.
<?php
require_once "../config/configPDO.php";
$photo_after = 'kk haha';
$report_id = 1;
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport?taskname=&reportStatus=&photoBefore=&photoAfter=". urlencode($photo_after) . "&reportID=$report_id";
$data = file_get_contents($url);
$json = json_decode($data);
$query = $json->otReportList;
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
the problem is, if the value of $photo_after is base64 string, which is too large string, it will give the error:
1) PHP Warning: file_get_contents.....
2) PHP Notice: Trying to get property 'otReportList' of non-object in C:
BUT
when I change the code to this,
<?php
require_once "../config/configPDO.php";
$photo_after = 'mama kk';
$report_id = 1;
$sql = "UPDATE ot_report SET photo_after ='$photo_after', time_photo_after = GETDATE(), ot_end = '20:30:00' WHERE report_id = '$report_id'";
$query = $conn->prepare($sql);
$query->execute();
if($query){
echo "Data Save!";
}else{
echo "Error!! Not Saved";
}
?>
The data will updated including when the value of $photo_after is in base 64 string.
Can I know what is the problem? Any solution to allow the base64 string update thru json link?
Thanks
// ...
// It's likely that the following line failed
$data = file_get_contents($url);
// ...
If the length of $url is more than 2048 bytes, that could cause file_get_contents($url) to fail. See What is the maximum length of a URL in different browsers?.
Consequent to such failure, you end up with a value of $json which is not an object. Ultimately, the property otReportList would not exist in $json hence the error: ...trying to get property 'otReportList' of non-object in C....
To surmount the URL length limitation, it would be best to embed the value of $photo_after in the request body. As requests made with GET method should not have a body, using POST method would be appropriate.
Below is a conceptual adjustment of your code to send the data with a POST method:
<?php
require_once "../config/configPDO.php";
# You must adapt backend behind this URL to be able to service the
# POST request
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_maintainReport";
$report_id = 1;
$photo_after = 'very-long-base64-encoding-of-an-image';
$request_content = <<<CONTENT
{
"taskname": $taskname,
"report_id": $report_id,
"photoBefore": $photoBefore,
"photo_after": $photo_after,
"reportStatus": $reportStatus
}
CONTENT;
$request_content_length = strlen($request_content);
# Depending on your server configuration, you may need to set
# $request_headers as an associative array instead of a string.
$request_headers = <<<HEADERS
Content-type: application/json
Content-Length: $request_content_length
HEADERS;
$request_options = array(
'http' => array(
'method' => "POST",
'header' => $request_headers,
'content' => $request_content
)
);
$request_context = stream_context_create($request_options);
$data = file_get_contents($url, false, $request_context);
# The request may fail for whatever reason, you should handle that case.
if (!$data) {
throw new Exception('Request failed, data is invalid');
}
$json = json_decode($data);
$query = $json->otReportList;
if ($query) {
echo "Data Save!";
} else {
echo "Error!! Not Saved";
}
?>
sending a long GET URL is not a good practice. You need to use POST method with cURL. And your webservice should receive the data using post method.
Here's example sending post using PHP:
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }
Sample code from: PHP + curl, HTTP POST sample code?
And all output from the webservice will put in the curl_exec() method and from there you can decode the replied json string.

Inserting Data Using PHP Curl

I am trying to add the following data to my database using curl. It insert's the data but the data inserted is blank
Employee Name = Test
Employee Salary = 100
Employee Age = 28
This is my code in inserting the data:
// set post fields
$data["employee_name"] = "test";
$data["employee_salary"] = 1;
$data["employee_age"] = 1;
$ch = curl_init('http://localhost/cloud/v1/employees');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
This is my Function in getting the data :
function insert_employee()
{
global $connection;
$data = json_decode(file_get_contents('php://input'), true);
$employee_name=$data["employee_name"];
$employee_salary=$data["employee_salary"];
$employee_age=$data["employee_age"];
echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'";
if(mysqli_query($connection, $query))
{
$response=array(
'status' => 1,
'status_message' =>'Employee Added Successfully.'
);
}
else
{
$response=array(
'status' => 0,
'status_message' =>'Employee Addition Failed.'
);
}
header('Content-Type: application/json');
echo json_encode($response);
}
Thank you
Replace this line:
$data = json_decode(file_get_contents('php://input'), true);
with:
$data = $_POST;
PHP will take your POSTed data and push it straight into a global $_POST array. No need to play with json_decode (unless you have posted a JSON string) or php://input.
Be aware, however, that blindly trusting posted data, and concatenating posted variables into a SQL statement is a huge security hole! Please look in to prepared statements and input validation.

php function pass return to the function again

I'm doing in instagram API, and little bit confusing about loop in function.
I try to create code to get all images from instagram user, but the API only give limit to 20 images. And we must do next call to the next page.
I'm using https://github.com/cosenary/Instagram-PHP-API to my application, and here is the function to get images.
function getUserMedia($id = 'self', $limit = 0)
{
$params = array();
if ($limit > 0) {
$params['count'] = $limit;
}
return $this->_makeCall('users/' . $id . '/media/recent', strlen($this->getAccessToken()), $params);
}
I try to make a call, the return value is
{
"pagination":
{
"next_url": "https://api.instagram.com/v1/users/21537353/media/recent?access_token=xxxxxxx&max_id=1173734674550540529_21537353",
"next_max_id": "1173734674550540529_21537353"
}, [.... another result data ....]
That the first function result, and produce 20 images.
My Question is:
How to pass return from to that function, to that function again using next_max_id parameter, so it will looping and using that function again?
How to merge the result to be 1 object array?
I'm sorry about my English and my explanation if not good.
Thank you for your help.
You should use recursive function
and stop that function when next_url found null/empty
From Instagram-PHP-Api documentation it seems to me that you should use pagination() method to receive your next page:
$photos = $instagram->getTagMedia('kitten');
$result = $instagram->pagination($photos);
Just use a condition (if) to verify if $result has content and, if it has, make another call with pagination() to request next page. Do it recursively.
But I think it's a good idea to implement without Instagram-PHP-Api using a while loop:
$token = "<your-accces-token>";
$url = "https://api.instagram.com/v1/users/self/media/recent/?access_token=".$token;
while ($url != null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$photos = json_decode($output);
if ($photos->meta->code == 200) {
// do stuff with photos
$url = (isset($photos->pagination->next_url)) ? $photos->pagination->next_url : null; // verify if there's another page
} else {
$url = null; // if error, stop the loop
}
sleep(1000); // to avoid to much requests on Instagram at almost the same time and protect your rate limits API
}
Good luck!

cURL - How to getting last redirect address

i write some code in php.
I wanna get last redirecting adress on this is site:
fluege.de
I posting this is;
$dep= "sFlightInput[accDep]=ZRH";
$arr= "sFlightInput[accArr]=VIE";
$depregion= "sFlightInput[accDepRegion]=";
$arrregion= "sFlightInput[accArrRegion]=";
$multidep= "sFlightInput[accMultiAirportDep]=ZRH";
$multiarr= "sFlightInput[accMultiAirportArr]=ZRH";
$ftype = "sFlightInput[flightType]=RT";
$depcity = "sFlightInput[depCity]=Zürich+-+Flughafen+(ZRH)+-+Schweiz";
$arrcity = "sFlightInput[arrCity]=Wien+-+Internationaler+Flughafen+(VIE)+-+Österreich";
$sdate = "sFlightInput[departureDate]=29.03.2014";
$srange = "sFlightInput[departureTimeRange]=2";
$rdate ="sFlightInput[returnDate]=05.04.2014";
$rrange = "sFlightInput[returnTimeRange]=2";
$adt = "sFlightInput[paxAdt]=1";
$chd ="sFlightInput[paxChd]=0";
$inf = "sFlightInput[paxInf]=0";
$cabin = "sFlightInput[cabinClass]=Y";
$airline = "sFlightInput[depAirline]=";
$send = $dep.$arr.$depregion.$arrregion.$multidep.$multiarr.$ftype.$depcity.$arrcity.$sdate.$srange.$rdate.$rrange.$adt.$chd.$inf.$cabin.$airline;
I using this ;
echo getLastEffectiveUrl("http://www.fluege.de/flight/wait/".$send);
And there is function
function getLastEffectiveUrl($url)
{
// initialize cURL
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
));
// execute the request
$result = curl_exec($curl);
// fail if the request was not successful
if ($result === false) {
curl_close($curl);
return null;
}
// extract the target url
$redirectUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
curl_close($curl);
return $redirectUrl;
}
They code must give this url;
www.fluege.de/wait/?accDep=&accArr=&accDepRegion=&accArrRegion=&accMultiAirportDep=&accMultiAirportArr=&flightType=RT&depCity=Z%FCrich+-+Flughafen+%28ZRH%29+-+Schweiz&arrCity=Wien+-+Internationaler+Flughafen+%28VIE%29+-+%D6sterreich&departureDate=04.04.2014&departureTimeRange=2&returnDate=20.04.2014&returnTimeRange=2&paxAdt=1&paxChd=0&paxInf=0&cabinClass=Y&depAirline=
But i need ;
http://www.fluege.de/flight/encodes/sFlightInput/5f8ccad612bafb69e7693f04cfaf1458/ (etc)
The code you provided does not handle cookies, so if the site you are query'ing requires this, your code won't work.
I checked http://php.net/manual/en/function.curl-setopt.php, but it seems like cURL cannot store cookies in memory. By adding the following line under curl_setopt_array, cookies are kept in a temporary file:
CURLOPT_COOKIEJAR => tempnam(sys_get_temp_dir(), 'cookiejar'),
However, I did not get your specific case to work. I noticed that the URL you create does not contain a question mark, and that the URL that your script creates does not redirect at all; it returns with 200 OK. I checked this using the following shell command:
curl -LI 'http://www.fluege.de/flight/wait/sFlightInput\[accDep\]=ZRHsFlightInput\[accArr\]=VIEsFlightInput\[accDepRegion\]=sFlightInput\[accArrRegion\]=sFlightInput\[accMultiAirportDep\]=ZRHsFlightInput\[accMultiAirportArr\]=ZRHsFlightInput\[flightType\]=RTsFlightInput\[depCity\]=Zürich+-+Flughafen+(ZRH)+-+SchweizsFlightInput\[arrCity\]=Wien+-+Internationaler+Flughafen+(VIE)+-+ÖsterreichsFlightInput\[departureDate\]=29.03.2014sFlightInput\[departureTimeRange\]=2sFlightInput\[returnDate\]=05.04.2014sFlightInput\[returnTimeRange\]=2sFlightInput\[paxAdt\]=1sFlightInput\[paxChd\]=0sFlightInput\[paxInf\]=0sFlightInput\[cabinClass\]=YsFlightInput\[depAirline\]='
If it's unclear what the URL should look like, you should contact fluege.de to ask them how to use their API.

Update Twitter status with media with Twitter Async

Any idea how one would update a user's Twitter status with an image - using the Twitter-Async class?
This is what I have
$twitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$array = array('media[]' => '#/img/1.jpg','status' => $status);
$twitter->post('/statuses/update_with_media.json', $array);
With thanks to #billythekid, I have managed to do this. This is what you need to do:
Look these functions up in the EpiOAuth file and see what I've added and alter it where necessary.
EpiOAuth.php
//I have this on line 24
protected $mediaUrl = 'https://upload.twitter.com';
//and altered getApiUrl() to include check for such (you may wish to make this a regex in keeping with the rest?)
private function getApiUrl($endpoint)
{
if(strpos($endpoint,"with_media") > 0)
return "{$this->mediaUrl}/{$this->apiVersion}{$endpoint}";
elseif(preg_match('#^/(trends|search)[./]?(?=(json|daily|current|weekly))#', $endpoint))
return "{$this->searchUrl}{$endpoint}";
elseif(!empty($this->apiVersion))
return "{$this->apiVersionedUrl}/{$this->apiVersion}{$endpoint}";
else
return "{$this->apiUrl}{$endpoint}";
}
// add urldecode if post is multiPart (otherwise tweet is encoded)
protected function httpPost($url, $params = null, $isMultipart)
{
$this->addDefaultHeaders($url, $params['oauth']);
$ch = $this->curlInit($url);
curl_setopt($ch, CURLOPT_POST, 1);
// php's curl extension automatically sets the content type
// based on whether the params are in string or array form
if ($isMultipart) {
$params['request']['status'] = urldecode($params['request']['status']);
}
if($isMultipart)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params['request']);
else
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->buildHttpQueryRaw($params['request']));
$resp = $this->executeCurl($ch);
$this->emptyHeaders();
return $resp;
}
Post image
// how to post image
$twitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET,$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$array = array('#media[]' => '#/img/1.jpg','status' => $status);
$twitter->post('/statuses/update_with_media.json', $array);

Categories