getting PHP warning while running application - php

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))

Related

Failing to connect and output my json requests

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 :)

PHP function in do while

Here is my code. Basically it generates a random string and I want to regenerate if the generated code exists in my db, but I always get recurring error.
What can I do to stop recurring error?
Here's my error
cannot redeclare exists_in_db (previously declared)
Code:
function exists_in_db($str)
{
$check_badge_in_paids = "sql query";
return mysqli_num_rows($check_badge_in_paids) > 0;
}
function rand_string()
{
$str = "";
do
{
$str = substr(md5(microtime()), 0, 5);
}
while(exists_in_db($str));
return $str;
}
Well Crys that error would only occur if you've previously declared that function, so here's what I advice you do, clear this code and do this:
var_dump(function_exists('exists_in_db'));
OR:
at the top where you have declared the function, do this:
var_dump(function_exists('exists_in_db'));
die;
if it returns true, then you have to check you code for previous declarations, probably included files etc.

Find out where custom PHP function is defined

I use internal function function_exists, that can return true but I can't find the custom function in my project. I also debugged my code to trace the function, but the debugger does not step into my custom function. I very look forward to know why. Please help me, thank you.
To find out where is the function defined, use following code:
<?php
$rf = new ReflectionFunction('my_fuction_name');
echo 'file:' . $rf->getFileName() . ', line:' . $rf->getStartLine();
?>
Please note that if the function is not defined in source code, but it's internal PHP function, both getFileName() and getStartLine() will return false.
You can check if the function is internal that way:
<?php
$rf = new ReflectionFunction('my_fuction_name');
if($rf->isInternal() === TRUE){
echo "Function is internal!";
}else{
echo "Function is not internal.";
}
?>

Fatal error: Can't use function return value in write context in [filter_input]

I'm learning PHP and have problem with I think filter_input function.
<?php
if (!isSet(filter_input(INPUT_COOKIE, 'nazwa')) && !isSet(filter_input(INPUT_GET, 'nazwa')))
{
include ("header.html");
include 'form.html';
include 'footer.html';
}
else if (isset(filter_input(INPUT_GET, 'nazwa'))) {
setcookie("nazwa", (filter_input(INPUT_GET, 'nazwa')), time() + 60*60*24*365);
include 'header.html';
echo "<p> Dziękujemy za podanie danych.</p>";
include 'footer.html';
}
else {
include 'header.html';
echo "Witamy, zostałeś rozpoznany jako {filter_input(INPUT_COOKIE, 'nazwa')}.";
include 'footer.html';
}
?>
I got:
Fatal error: Can't use function return value in write context in C:\Users\User\Documents\NetBeansProjects\PhpProject3\cookie\index.php on line 4
Could you plese help me?
You are using
isset(filter_input(INPUT_GET, 'nazwa')
Instead, you could use something like this (everywhere you call isset()):
$func = filter_input(INPUT_COOKIE, 'nazwa');
isset($func)
Directly from php documentation
Warning
isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.
isset() is a language construct. Not a normal function.
You cannot use isset() on the result of a function call, here filter_input().
Pull the filter_input() call out (assign return value of function to variable and then check it)
$nazwa = filter_input(INPUT_POST, 'nazwa');
if($nazwa) { ... }
or inline it:
if ($nazwa = filter_input(INPUT_POST, 'nazwa'))
{
// your code
} else {
echo 'Nope';
}

Using a function to initialise a variable if it not set - PHP

Upon executing a script, sometimes the variable will be set, and sometimes it won't. The times that it isn't, I'm given a notice that the variable is not defined.
In efforts to clear the notice, I simple added the following code
if(!isset($var)) {
$var = NULL;
}
That works just as needed because it tests if the variable isn't already set so that we don't set something that we need to NULL. But in a file where there are over 60 variables that are of this case and more to come, I thought creating a simple function to do so would be easier. So I started with this:
function init($var) {
if(!isset($var)) {
return $var = NULL;
}
}
Obviously that doesn't work and is also riddled with errors that will annoy most programmers out there (such as the !isset() inside a function, not supplying a return statement in case the if statement is false, etc.) but that's just to give you the basic jist of what I need so in the code I can just call init($var); to test if the variable isn't already set, and then creates one and sets it to NULL to avoid the notice.
Is this even possible? To use a function to test if a variable is already set outside of the function? Thanks in advance :)
You can't use a function to check if a variable exists without it being initialized in the process of passing it to the function as an argument. You can, however, define an array of variable names your script requires then loop through them and check if they exist one by one. Such as:
foreach(array('username','userid','userrole','posts','dob','friends') as $var)
{
if(!isset($$var))$$var=NULL;
}
Edit: Simplifying user4035's approach, you could get the function down to:
<?php
function init(&$var){}
init($myVariable);
var_dump($myVariable);
Or even avoid a function altogether:
<?php
array(&$var1,&$var2,&$var3);//define several variables in one shot as NULL if not already defined.
var_dump($var1);
var_dump($var2);
var_dump($var3);
Another approach would be to use extract:
<?php
$defaults=array('username'=>NULL,'userid'=>0,'userrole'=>'guest','posts'=>0,'dob'=>0,'friends'=>array());
$userid=24334;
$username='bob';
$friends=array(2,5,7);
extract($defaults, EXTR_SKIP);
echo '<pre>';
print_r(
array(
'userid'=>$userid,
'username'=>$username,
'friends'=>$friends,
'userrole'=>$userrole,
'posts'=>$posts,
'dob'=>$dob)
);
echo '</pre>';
Another approach would be to temporarily disable error reporting:
<?php
$v=ini_get("error_reporting");
error_reporting(0);
echo 'One';
echo $doh;//Use an undefined variable
echo ' Two';
error_reporting($v);
I'd advise against this approach though because it is just hiding the errors rather than fixing them and will also hide errors worthy of your attention.
And my personal favorite would be to take advantage of namespaces.
Usually you'd put these into separate files but I put them into a single snippet for your convenience:
<?php
namespace //This is the global namespace
{
$config=array('production'=>0);
}
namespace MyScript
{
//Initialize all variables for our script
//anything not defined here will be inherited from the global namespace
$username=NULL;
$userid=NULL;
$userrole=NULL;
$posts=NULL;
$dob=NULL;
$friends=NULL;
}
namespace MyScript\Main
{
//Define only two variables for our script
//Everything else will be inherited from the parent namespace if not defined
$username='Ultimater';
$userid=4;
echo '<pre>';
print_r(
array(
'userid'=>$userid,
'username'=>$username,
'friends'=>$friends,
'userrole'=>$userrole,
'posts'=>$posts,
'dob'=>$dob,
'config'=>$config)
);
echo '</pre>';
}
If your intention is this:
if(variable is not set)
set variable to NULL
then it's quite easy to implement, using a reference:
function init(&$var) {
if(!isset($var)) {
$var = NULL;
}
}
Testing:
<?php
error_reporting(E_ALL);
function init(&$var) {
if(!isset($var)) {
$var = NULL;
}
}
init($x);
var_dump($x);
Output:
NULL

Categories