Failing to connect and output my json requests - php

So I have access to a public web API and I'm trying to pull information from it and use it in a PHP if statement. I have tried a few different ways but each time I fail? I will post all of my failed attempts to see if anyone knows what I'm doing wrong...
This is the JSON file;
{
"players": [
{
"SteamId": "76561198074117457",
"CommunityBanned": false,
"VACBanned": true,
"NumberOfVACBans": 1,
"DaysSinceLastBan": 738,
"NumberOfGameBans": 0,
"EconomyBan": "none"
}
]
}
Attempt 1 using a PHP function
(php file)
<?php
function VACBanned($vacban) {
if ($vacban == "false") {
return "";
}
elseif ($vacban == "true") {
return "<p>This user has a vac ban...</p>";
}
}
?>
(index file)
<html>
<body>
<?=VACBanned($json['players'][0]['VACBanned']);?>
</body>
</html>
This would output the following error;
PHP Notice: Undefined index: players in index.php on line 13
I initially thought that the API must not have been correctly connecting, so I went into the PHP file and echoed my user ID like so $json["players"][0]["SteamId"]; and it worked... But when I went and attempted to perform the same thing in the Index <?php echo $json["players"][0]["SteamId"];?> I got the error again? When I did this in the php file $test = $json["players"][0]["SteamId"]; and this in the index <?php echo $test;?>it echoed my steam id?????? I tried to just call the if statement in the index like so
<?php
if ($vac_ban == "false") {
return "123";
}
else {
return "<div class='ban_vac'><p>1 VAC BAN<br>76 Days Ago</p></div>";
}
?>
and $vac_ban would be stated in the php file as = $json["players"][0]["VACBanned"]; but that just made it outpute everything above the <? tag and nothing below it. Note the whole time during this I had the two files connected using include('filename'); and error_reporting(E_ALL); ini_set("display_errors", 1); and the json is decoded json_decode(file_get_contents($api_url), true);

You must decode json before use with PHP:
$array = json_decode($data, true);
Now you can do what you want:
VACBanned($array['players'][0]['VACBanned']);
Take a look: json_decode

So, I worked it out for anyone who might be having this issue, I just put my PHP code into the one document, it looks messy but works :)

Related

getting PHP warning while running application

I am getting a warning in php while running my application
HTML code:
<span> <?php if($a==true) { ?><?php echo $d->n; ?> <?php } ?></span>
PHP code:
$q=$mysqli->query("select object from object_store where Email='$email' ");
$r=$q->fetch_assoc();
$d=unserialize($r['object']);
if(!is_null($d))
{
$a=true;
}
else
{
$a=false;
}
The warning is cant call a member function on non object. I know that at first the value of $d is NULL but having used $a variable for check still the code block of $d is getting executed. Please suggest a way to remove this warning.
I think this code:
$d=unserialize($r['object']);
if(!is_null($d))
will always be true, since unserialize doesn't return null.
Try: if($d != false) or if(is_array($d))

PHP SAP RFC Function call not working

This is the first time I used PHP to call a SAP function. Ran into this problem that I couldn’t figure until someone with experience helped me.
<?php
// saprfc-class-library
require_once("saprfc.php");
// Create saprfc-instance
$sap = new saprfc(array(
"logindata"=>array(
"ASHOST"=>"" // application server
,"SYSNR"=>"" // system number
,"CLIENT"=>"" // client
,"USER"=>"" // user
,"PASSWD"=>"" // password
)
,"show_errors"=>false // let class printout errors
,"debug"=>true)) ; // detailed debugging information
// Call-Function
$result=$sap->callFunction("ZBAPI",
array( array("IMPORT","FROM_","100"),
array("EXPORT","RETURN",""),
array("TABLE","Namesdata",array())
));
if ($sap->getStatus() == SAPRFC_OK) {
// Yes, print out the Userlist
?><table>
<?php
//$sap->printStatus();
foreach ($result["Namesdata"] as $orders) {
echo "<tr><td>", $orders["name"],"</td><td>",$orders["form"],"</td> <td>",$orders["Names"],"</td></tr>";
}
?></table><?php
} else {
$sap->printStatus();
}
$sap->logoff();
?>
This Code so some error like this
saprfc::callFunction('ZBAPI')
Import-Parameter=FROM_ could not be set. (Does it exist?)
But i comment the import parameter means its fetch the data from saprfc whats wrong in this code..
Import values like this ---
array("IMPORT","name",array( "fieldname"=>"1000"))

Is there any way to catch fatal error using eval()?

$code = 'php statement';
// getting perse error
function perse_error_check($code){
if(eval($code) === "true"){
return "no perse error";
}
if(eval($code) === "false"){
return "perse error found";
}
}
// getting fatal error
function fatal_error_check($code){
.......................................
.......................................
}
Can you help me to complete the second function? Actually I am not sure weather it is possible or not.
The following writes the PHP code to another file.
It then uses command line execution to parse the file and check for erros:
/* Put the code to be tested in a separate file: */
$code = '<?php echo "Test"; ?>';
file_put_contents('check.php', $code);
/* Parse that file and store the message from the PHP parser */
$x = exec( 'php -l check.php');
/* Check the message returned from the PHP parser */
if(preg_match('/Errors parsing/i',$x))
{
echo 'The code has errors!';
}
else
{
echo 'The code looks good!';
}
/* delete the file */
unlink('check.php');
The benefit is that the code doesn't run, it just gets parsed. However I assume you would then write that code to a file and use it... so like others mentioned, be VERY careful. Use things like open_basedir (and test it) to restrict access to specific directories, manually check the code before including it in production... etc.
There is a simple way. Put your PHP code in an another file. For an example: index.php and check.php . Put your PHP code in check.php.
Now in index.php write:
$check_data = file_get_contents("yourhosturl/allotherdirectory/check.php");
if(preg_match("/Fatal error/",$check_data)){
echo "fatal error found";
}

how to show the error when missing function is inside an if

Today I noticed that the missing function dosent show an error when is inside an if. And what to see that error, because is hard for debugging
<?php if(3 >1): ?>
<?php echo missingFunction(3); ?>
<?php else: ?>
<?php echo missingFunction(3); ?>
<?php endif; ?>
If I call the function on its own
// This will show that the function is missing
<?php echo missingFunction(4); ?>
In the beging of the file I have
ini_set('display_errors', 1);
error_reporting(E_ALL);
You can't see error if xy function is inside of a (negative) if - only when its triggered. There is no way.
But you can do (check) file like this, and you should write "questionable/suspicious/hidden/if" functions in manually (hardcoded).. better then nothing though.
$maybe_fns = (function1,function2); //... you should type in `if` functions here, manually
$check = #explode(',', $maybe_fns);
while (list($key,$xxx) = each($check))
{
if(!function_exists($xxx)
{
echo '<b>Warning:</b> No function <b>'.$xxx.'</b><br>';
}
}
May come handy in alpha & beta testings, and its better then reading bunch of functions files for sure.
The existence of a function in PHP is only determined at the very last minute when the interpreter executes the statement.
So if you have a missing function inside a condition that never evaluates to true, no errors will be triggered.
For example:
if (false) {
this_function_does_not_exist(); // this never gets run
}
// no errors

output issue with command line

main.php
<?php
mb_internal_encoding("UTF-8");
require_once('./TController.php');
TController::doMain($argc, $argv);
return 0;
?>
TController.php
<?php
require_once(dirname(__FILE__)."/A.php");
require_once(dirname(__FILE__)."/../../B.php");
require_once(dirname(__FILE__)."/../../C.php");
require_once(dirname(__FILE__)."/D.php");
require_once(dirname(__FILE__)."/E.php");
class TController
{
public function doMain($argc, $argv)
{
StockPriceDefiner::defineStock();
if($argc != 10) {
$file = "main.php";
echo <<<EOT
usage:
php $file year month day width 500 ana_ana isDiv
ex):
input parameters
EOT;
return;
}
print_r($argv);
}
}
?>
I have tried to php main.php [enter] from the command prompt but the usage above isn't displayed. is there anything incorrect you can spot, please help me.
[UPDATE]
there is no error, just nothing is displayed.
Please enable error report by adding
error_report(E_ALL);
at the start of your main.php file.
Secondly, if TController.php file is all you have pasted, then it certainly doesn't contain any definition of
TravelJpController::doMain()
This should do the trick:
TController::doMain($argc, $argv);

Categories