PHP Output (json) - php

This is my script which is fetching a delivery report form my service providers api & displaying it in json format. I want this to be displayed in a table form using the mobile & status fields.
<?php
$uid="UID";
$pin="PIN";
$domain="DOMAIN";
$route="5";
$method="POST";
$rtype="json";
//---------------------------------
if(isset($_REQUEST['send']))
{
$date=$_REQUEST['date'];
$uid=urlencode($uid);
$pin=urlencode($pin);
$rtype=urlencode($rtype);
$route=urlencode($route);
$date=urlencode($date);
$rtype=urlencode($rtype);
$parameters="uid=$uid&pin=$pin&date=$date&route=$route&rtype=$rtype";
$url="http://$domain/api/dlr.php";
$ch = curl_init($url);
if($method=="POST")
{
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters);
}
else
{
$get_url=$url."?".$parameters;
curl_setopt($ch, CURLOPT_POST,0);
curl_setopt($ch, CURLOPT_URL, $get_url);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_HEADER,0); // DO NOT RETURN HTTP HEADERS
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // RETURN THE CONTENTS OF THE CALL
$return_val = curl_exec($ch);
if($return_val=="")
echo "Process Failed, Please check your connecting domain, username or password.";
else
echo "$return_val";
}
echo "<form name='f1' method='post'>";
echo "<p> Date (##-##-####): <input name='date' > </p>";
echo "<p> <input type='submit' value='Send' name='send'></p>";
echo "</form";
?>
OUTPUT
[{"smsid":"211677113","mobile":"9876546577","status":"Delivered"},{"smsid":"211677166","mobile":"98765454377","status":"Delivered"}]

try json_decode()
$str = json_decode('[{"smsid":"211677113","mobile":"9876546577","status":"Delivered"},{"smsid":"211677166","mobile":"98765454377","status":"Delivered"}]', true);
print_r($str);
it will convert your json string in an array then loop through your array and print output as you wish like
foreach($str as $k=>$v) {
echo $v['smsid'];
echo $v['mobile'];
echo $v['status'];
}

Try to show table
<?php
$a = json_decode('[{"smsid":"211677113","mobile":"9876546577","status":"Delivered"},{"smsid":"211677166","mobile":"98765454377","status":"Delivered"}]');
?>
<table border="1">
<?php
foreach($a as $k=>$v){?>
<tr>
<td><?=$v->mobile?></td>
<td><?=$v->status?></td>
</tr>
<?php } ?>
</table>

Related

Need help passing session using header redirect

I am trying to create a 3rd party app for a game I like (EVE Online) which requires oauth.
I have decided to do the oauth handling in it's own script and once resolved, put an associative array into the session based on the CharacterID retrieved from oauth.
I am able to successfully output the desired contents of the session array from the /callback/index.php' that handles the oauth requests at the end of the script. However, I want to keep this script "in the background" and somewhat secret, and redirect most of the activity to a '../main.php' in the directory just below.
However, when I finally get to main.php, printing the session returns an empty array. What am I doing wrong? I have searched all day for solutions and have implemented every one of them.
Below are the relevant files:
session.php
<?php
if (!empty($_GET['ID'])) {
session_id($_GET['ID']);
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
} else {
$sLocation="http://eve.oriigen.com/eClt";
header("Location: ".$sLocation);
exit();
}
?>
/callback/index.php
<?php require_once '../src/session.php' ?>
<?php require_once 'secret.php' ?>
<?php
function auth_error($error_message)
{
print "There's been an error";
error_log($error_message);
exit();
}
$sUserAgent = "EVE Contact List Toolkit [eClt]";
$post_url = "https://login.eveonline.com/oauth/token";
$get_url = "https://login.eveonline.com/oauth/verify";
$client_id="Basic ".base64_encode($sClientId.":".$sSecretKey);
$content_type = "application/x-www-form-urlencoded";
$host_url = "login.eveonline.com";
$aHeaders = array("Authorization: ".$client_id,
"Content-type: ".$content_type,
"Host: ".$host_url);
$aPostFields = array("grant_type"=>"authorization_code",
"code"=>$_GET["code"]);
$oCurlRequest = curl_init();
curl_setopt($oCurlRequest, CURLOPT_URL, $post_url);
curl_setopt($oCurlRequest, CURLOPT_USERAGENT, $sUserAgent);
curl_setopt($oCurlRequest, CURLOPT_HTTPHEADER, $aHeaders);
curl_setopt($oCurlRequest, CURLOPT_POST, count($aPostFields));
curl_setopt($oCurlRequest, CURLOPT_POSTFIELDS, http_build_query($aPostFields));
curl_setopt($oCurlRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYHOST, 2);
$oResult = curl_exec($oCurlRequest);
if ($oResult===false) {
auth_error(curl_error($oCurlRequest));
}
curl_close($oCurlRequest);
$aResponse=json_decode($oResult);
unset($oCurlRequest);
unset($oResult);
$sTokenType=$aResponse->token_type;
$sAuthToken=$aResponse->access_token;
$iAuthTokenExpire=$aResponse->expires_in;
$sRefreshToken=$aResponse->refresh_token;
$sGetHeader="Authorization: ".$sTokenType." ".$sAuthToken;
$oCurlRequest = curl_init();
curl_setopt($oCurlRequest, CURLOPT_URL, $get_url);
curl_setopt($oCurlRequest, CURLOPT_USERAGENT, $sUserAgent);
curl_setopt($oCurlRequest, CURLOPT_HTTPHEADER, array($sGetHeader));
curl_setopt($oCurlRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($oCurlRequest, CURLOPT_SSL_VERIFYHOST, 2);
$oResult = curl_exec($oCurlRequest);
if ($oResult===false) {
auth_error(curl_error($oCurlRequest));
}
curl_close($oCurlRequest);
$aResponse=json_decode($oResult);
unset($oCurlRequest);
unset($oResult);
$sCharId=(string)$aResponse->CharacterID;
$sCharacterName=$aResponse->CharacterName;
$sExpiresOn=$aResponse->ExpiresOn;
$sTokenType=$aResponse->TokenType;
$sCharacterOwnerHash=$aResponse->CharacterOwnerHash;
$sIntellectualProperty=$aResponse->IntellectualProperty;
/* $aCharInfo=array("CharID"=>(int)$sCharId,
"CharName"=>$sCharacterName,
"CharOwnerHash"=>$sCharacterOwnerHash,
"ExpiresOn"=>$sExpiresOn,
"AuthToken"=>$sAuthToken,
"AuthTokenExpIn"=>$iAuthTokenExpire,
"RefreshToken"=>$sRefreshToken);*/
if (!isset($_SESSION[(string)$sCharId])) {
$_SESSION[(string)$sCharId]=array("CharID"=>(int)$sCharId,
"CharName"=>$sCharacterName,
"CharOwnerHash"=>$sCharacterOwnerHash,
"ExpiresOn"=>$sExpiresOn,
"AuthToken"=>$sAuthToken,
"AuthTokenExpIn"=>$iAuthTokenExpire,
"RefreshToken"=>$sRefreshToken);
} else {
$_SESSION["moo"]=0;
}
session_write_close();
$sRedirect="../main.php?ID=".session_id();
header("Location: ".$sRedirect);
exit();
/* echo "<pre>";
print_r($_SESSION);
echo "</pre>";
echo "<hr />";
echo gettype($iCharId);
echo "<hr />";
echo "<pre>";
print_r($aCharInfo);
echo "</pre>";*/
?>
../main.php
<?php require_once './src/session.php' ?>
<?php
//echo "SessionId: ".session_id()."<br />";
//echo "<hr/>";
//echo "<pre>";
print_r($_SESSION);
//echo "</pre>";
?>
[ Logout ]
As you can see from the commented sections, I have tried every diagnostic printout I can think of. So, where am I going wrong?
Solved it - per a related question I found only after posting this question:
from here:
The PHP session storage mechanism was originally built around "registering" variables, so the keys in $_SESSION must be names that could be treated as variables in their own right. This means that $_SESSION[10] is invalid, because $10 wouldn't be a valid variable name, and since $foo[10] and $foo['10'] refer to the same thing, $_SESSION['10'] is invalid as well.
CharacterID was either and int of a string version of an int, apparently PHP sessions don't like numbers in their array keys...

Using curl to load next json page results in php

I'm using PHP and cURL to retrieve API information from a website. I have a loop to display all the information on my page which works just fine. The problem I'm having is, my results page displays 10 items per page. The API offers pagination in which it provides me with the next page link url to page 2, 3, and so forth. I cannot find for the life of me, how to make this next link load page 2 information and display it on the same page(it sounds easy enough). I have tried numerous different techniques and none have worked so far. I'm currently stuck where page 1 loads and displays page 1 and 2 data. I would like to have it to where you click the next link and it refreshes the page with your page 2 data and removes page 1 data. Any help is greatly appreciated...Here is my current code...
<section>
<form method="post" action="<?php echo $PHP_SELF;?>" id="searchForm">
<input type="text" name="searchText" id="searchText" placeholder="e.g. Haze.." value=""/><br>
<button type="submit" name="submit" id="searchButton" form="searchForm">Search</button>
<?php
if (isset($_POST['submit'])){
$url = 'https://www.cannabisreports.com/api/v1.0/strains/search/:' . urlencode ($_POST["searchText"]);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-API-Key : XXXXXXXXXXXXXXXXXXXXXXXX'));
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec($curl);
curl_close($curl);
$jsonobj = json_decode($result);
echo('<ul id="resultList">');
foreach($jsonobj->data as $value)
{
echo('<li class="resultListItem">');
echo('<img src="' . $value->image . '">');
echo '<br>';
echo $value->seedCompany->name;
echo '<br>';
echo $value->genetics->names;
echo '<br>';
echo $value->reviews->count;
echo("</li>");
}
echo("</ul>");
//********code for next page
echo(' Next ');
if(isset($_GET['nextPage'])) {
header('location: http://www.strains.blazedmaps.com ');
$urlNext = $jsonobj->meta->pagination->links->next;
$curlNext = curl_init();
curl_setopt ($curlNext, CURLOPT_URL, $urlNext);
curl_setopt ($curlNext, CURLOPT_HTTPheader, array('X-API-Key : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'));
curl_setopt ($curlNext, CURLOPT_RETURNTRANSFER, 1 );
$resultNext = curl_exec($curlNext);
curl_close($curlNext);
$jsonobjNext = json_decode($resultNext);
echo('<ul id="resultList">');
foreach($jsonobjNext->data as $value1)
{
echo('<li class="resultListItem">');
echo('<img src="' . $value1->image . '">');
echo '<br>';
echo $value1->seedCompany->name;
echo '<br>';
echo $value1->genetics->names;
echo '<br>';
echo $value->reviews->count;
echo("</li>");
}
echo("</ul>");
}
}
?>
</form>
</section>

php file get contents not working while fetching fb page data

I have the following code to get fb page list
$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$pagedata=file_get_contents($graph_url_pages);
echo "DATA : <br>";
print_r($pagedata);
$pages=json_decode($pagedata,true);
var_dump($pages);
$dropdown = "";
for($i=0;$i<count($pages->data);$i++)
{
if($me=="iamindex"){
$dropdown .= "<option value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."</option>";
}elseif($me=="iammulti"){
$dropdown .= "<input type='checkbox' name='page' id='status' value='".$pages->data[$i]->access_token."-".$pages->data[$i]->id."'>".$pages->data[$i]->name."<br>";
}else{$dropdown.="<option value=''>No Category Selection</option>";}
}
$pagedata and $pages is empty and so dropdown doesn't get populated.
Somewhere at the top of the page I am using Ob_start() and at the end Ob_flush(); And they are needed. I don't know whether this is the issue.
Would be great if somebody can point out what is going wrong ! if more code is needed, I can provide. Please note I am an amateur programmer. Self taught.
I recommend using cURL
$graph_url_pages = "https://graph.facebook.com/me/accounts?access_token=".$_SESSION['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $graph_url_pages);
if(curl_error($c))
{
echo 'error:' . curl_error($c);
//it will produce the error if any exists
}
$data = curl_exec($ch);
curl_close($ch);
print_r($data);

php search url source code for specific word and then redirect to url

I need the php code for searching the source code of an url for a specific word and if the word exists it will redirect to that url. I have the following code but i don't know how to do the redirect part:
<?php
$ch = curl_init("http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo (stristr ($result, 'specificword')) ? "<div style='text-align:center; color:green'>Online</div>" : "<div style='text-align:center; color:red'>Offline</div>";
?>
UPDATE: with the code you provided, this is my fix:
<?php
$URL = 'http://www.example.com';
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (stristr ($result, 'Domain')) {
header('Location: '. $URL);
}
else{
echo "No matches found";
}
?>
Old answer
If you first want to show ONLINE, you would require something like a META-refresh.
Change the last line to:
echo (CONDITION HERE) '<html>
<head>
<title>Site online</title>
<meta http-equiv="refresh" content="5; url=http://example.com/">
</head>
<body>
<div style="text-align:center; color:green">Online</div>" : "<div style='text-align:center; color:red'>Offline</div>
</body>
</html>';
If you don't need to first show ONLINE and just want to redirect, try:
if (stristr ($result, 'specificword')) {
header('Location: http://www.example.com');
}
Also I suggest to use mb_stristr because it handles Unicode better.
My updated code is as follows:
<?php
$URL = 'http://www.example.com';
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (stristr ($result, 'Domain')) {
header('Location: '. $URL);
}
else{
echo "No matches found";
}
?>
if something == true then
header("location: myurl.com");
exit;
end

my sample code is not working in sms gateway integration?what I to do next?

I have purchase the sms gateway.I my login panel they have given the sample code to integrate i don't understand this line $url="http://$domain/api/sms.php"; shall i have send all the form values to sms.php? because they have given the entire code link this. yesterday also i execute in localhost. I got the error Process Failed, Please check your connecting domain, username or password. myquestion is what i have to do to execute correctly this one.because they have given the code. it is not running?
note:I have taken transactional sms route 5.I have discussed with those people they said for transaction you have to create tempid?after we do approval. before I start with dynamic message api first i have to integrate this with sample code,so that i come to know will it work with sample code? later i change this to dynamic.
<?php
$uid="##my_ID##"; //your uid
$pin="##MY_PIN##"; //your api pin
$sender="PSGRKC"; // approved sender id
$domain="http://www.smsalertbox.com/"; // connecting url
$route="0";// 0-Normal,1-Priority
$method="POST"
if(isset($_REQUEST['send']))
{
$mobile=$_REQUEST['mobile'];
$message=$_REQUEST['message'];
$uid=urlencode($uid);
$pin=urlencode($pin);
$sender=urlencode($sender);
$message=urlencode($message);
$parameters="uid=$uid&pin=$pin&sender=$sender&route=$route&mobile=$mobile&message=$message ";
$url="http://$domain/api/sms.php";
$ch = curl_init($url);
if($method=="POST")
{
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters);
}
else
{
$get_url=$url."?".$parameters;
curl_setopt($ch, CURLOPT_POST,0);
curl_setopt($ch, CURLOPT_URL, $get_url);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_HEADER,0); // DO NOT RETURN HTTP HEADERS
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // RETURN THE CONTENTS OF THE CALL
$return_val = curl_exec($ch);
if($return_val=="")
echo "Process Failed, Please check your connecting domain, username or password.";
else
echo "Message Id : $return_val"; //Returning the message id : Whenever you are sending an SMS our system will give a message id for each numbers, which can be saved into your database and in future by calling these message id's using correct API's you can update the delivery status.
}
echo "<form name='f1' method='post'>";
echo "<p> Mobile: <input name='mobile' > </p>";
echo "<p> Message: <textarea name='message' ></textarea> </p>";
echo "<p> <input type='submit' value='Send' name='send'></p>";
echo "</form>";
?>
Remove http:// from your domain url
$domain="www.smsalertbox.com/"; // connecting url
As you have used http in $url also so it is using http:// two times
Working code :
<?php
$uid="##########"; //your uid
$pin="########"; //your api pin
$sender="PSGRKC"; // approved sender id
$domain="www.smsalertbox.com/"; // connecting url
$route="0";// 0-Normal,1-Priority
$method="POST";
if(isset($_REQUEST['send']))
{
$mobile=$_REQUEST['mobile'];
$message=$_REQUEST['message'];
$uid=urlencode($uid);
$pin=urlencode($pin);
$sender=urlencode($sender);
$message=urlencode($message);
$parameters="uid=$uid&pin=$pin&sender=$sender&route=$route&mobile=$mobile&message=$message ";
$url="http://$domain/api/sms.php";
$ch = curl_init($url);
if($method=="POST")
{
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters);
}
else
{
$get_url=$url."?".$parameters;
curl_setopt($ch, CURLOPT_POST,0);
curl_setopt($ch, CURLOPT_URL, $get_url);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_HEADER,0); // DO NOT RETURN HTTP HEADERS
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // RETURN THE CONTENTS OF THE CALL
$return_val = curl_exec($ch);
if($return_val=="")
echo "Process Failed, Please check your connecting domain, username or password.";
else
echo "Message Id : $return_val"; //Returning the message id : Whenever you are sending an SMS our system will give a message id for each numbers, which can be saved into your database and in future by calling these message id's using correct API's you can update the delivery status.
}
echo "<form name='f1' method='post'>";
echo "<p> Mobile: <input name='mobile' > </p>";
echo "<p> Message: <textarea name='message' ></textarea> </p>";
echo "<p> <input type='submit' value='Send' name='send'></p>";
echo "</form>";
?>

Categories