Invalid argument supplied for foreach() using adldap - php

I am using adldap http://adldap.sourceforge.net/
And I am passing the session from page to page, and checking to make sure the username within the session is a member of a certain member group, for this example, it is the STAFF group.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('/web/ee_web/include/adLDAP.php');
$adldap = new adLDAP();
session_start();
$group = "STAFF";
//$authUser = $adldap->authenticate($username, $password);
$result=$adldap->user_groups($_SESSION['user_session']);
foreach($result as $key=>$value) {
switch($value) {
case $group:
print '<h3>'.$group.'</h3>';
break;
default:
print '<h3>Did not find specific value: '.$value.'</h3>';
}
if($value == $group) { print 'for loop broke'; break; }
}
?>
It gives me the error: Warning: Invalid argument supplied for foreach() on line 15, which is this line of code: foreach($result as $key=>$value) {
When I uncomment the code $authUser = $adldap->authenticate($username, $password); and enter in the appropriate username and password, it works fine, but I shouldn't have to, since the session is valid, I just want to see if the username stored within the valid_session is apart of the STAFF group.
Why would it be giving me that problem?

According to this source file, user_groups() will, return false if the user name was empty (and in some other cases too, check the source). I bet your $_SESSION["user_session"] is empty, and $result is then false. You can't run foreach on a non-array which is why you get the warning.
You will need to find out why your session variable is empty, and/or check whether $result is an array because doing a foreach on it:
if (is_array($result))
foreach ($result....

Related

Automatic conversion of false to array is deprecated

I get this warning in a chunk of instructions PHP 8+ dedicated to the check of the user inside the page:
if ($_POST['go'] ?? null) {
// $_SESSION_VALUES is an array $db, $nick are classes of mine
$_SESSION_VALUES = $nick->get_cookie (COOKIE_NAME); // get the name of the cookie
if ($db->check_user (USERS_TABLE, $_POST['nick'], $db->encode_password($_POST['password']))) {
$_SESSION_VALUES['_USERNAME'] = $db->user_rec['nick']; // get the nickname from the cookie
$_SESSION_VALUES['_PASSWORD'] = $db->user_rec['password']; //get the password
$_SESSION_VALUES['_USER'] = $db->user_type;
if (! $nick->set_cookie (COOKIE_NAME, $_SESSION_VALUES)) die ('Cannot write the cookie'); // record the cookie
header('Location: ./copertina'); }
else $_SESSION_VALUES['_USER'] = -1;
}
The execution of
else $_SESSION_VALUES['_USER'] = -1;
gives "Automatic conversion of false to array is deprecated"
Following a suggestion from stack overflow I tryed this:
$\_SESSION_VALUES = \[\];
if ($\_POST\['go'\] ?? null) {
...
but apparently it doesn't work
any idea?
Thanks
I assume that $nick->get_cookie(COOKIE_NAME); returns false.
Try changing:
else $_SESSION_VALUES['_USER'] = -1;
to:
else $_SESSION_VALUES = ['_USER' => -1];
This will probably get rid of the error message you reported, but I don't know if the rest of your code, which I cannot see, will accept this.

Foreach loop randomly throwing “invalid argument supplied”

I'm trying to get this function to work but for some reason it errors out on the foreach line saying there is an invalid argument.
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
The error I get is: PHP Warning: Invalid argument supplied for foreach()
Note: I need to keep the if... else... in the order it currently is.
Some variations for the if statement, prior to the for
if(!is_array($scores) && !count($scores) || empty($scores)){
if(!is_array($scores) && !count($scores)){
I can't use use var_dump($scores); because the error is on a page on a private website I run (can't provide links) and I am unable to find a way to recreate the error. Maybe someone knows a way I can capture data that causes the foreach to go wrong and save it to a log file?
You can use error_log in case it is no array:
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
if(!is_array($scores)) {
$scores_info = print_r($scores, true);
error_log('$scores is no array but: ' . $scores_info);
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
}
It will write to the error log. You can see more at the error_log doc how to configure it. You should clearly dry it up when you know what the error is, but for temporary catching it this works ...

"Undefined variable" error

I get the error undefined variable err. I've tried isset here but maybe my code is wrong.
if(err ==1)
{
$record = $_POST;
foreach($record as $key=$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
make sure that you have defined "err" as constant somewhere or use $err instead of err.
There is Two mistrake in your code
1. Forget $ sign which is neccessary in PHP
2. Wrong syntax for foreach loop there will be => sign instead of =
// so right code is
if($err ==1)
{
$record = $_POST;
foreach($record as $key=>$val)
$record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
in php variable have prefix $ symbol or err must be constant,but it is good practice to use constant name as Capital letters
try this code
if( isset($err) && $err == 1 )
{
$record = $_POST;
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
EDIT
try to check variable is exist or not using isset()
The reason you are getting undefined is because where you define your err variable you are forgetting to create it as $err.
You need to change every place in your code where you have err variable to $err, not just in the place you have shown in this question. That's why you're still getting undefined after trying the solutions here, because you're only changing to $err in one place.

Handle errors in simple html dom

I have some code to get some public available data that i am fetching from a website
//Array of params
foreach($params as $par){
$html = file_get_html('WEBSITE.COM/$par');
$name = $html->find('div[class=name]');
$link = $html->find('div[class=secondName]');
foreach($link as $i => $result2)
{
$var = $name[$i]->plaintext;
echo $result2->href,"<br>";
//Insert to database
}
}
So it goes to the given website with a different parameter in the URL each time on the loop, i keep getting errors that breaks the script when a 404 comes up or a server temporarily unavailable. I have tried code to check the headers and check if the $html is an object first but i still get the errors, is there a way i can just skip the errors and leave them out and carry on with the script?
Code i have tried to checked headers
function url_exists($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
$headers = #get_headers($url);
//print_r($headers);
if (is_array($headers)){
//Check for http error here....should add checks for other errors too...
if(strpos($headers[0], '404 Not Found'))
return false;
else
return true;
}
else
return false;
}
Code i have tried to check if object
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
// and only then start searching (and manipulating) the dom
You need to be more specific, what kind of errors are you getting? Which line errors out?
Edit: Since you did specify the errors you're getting, here's what to do:
I've noticed you're using SINGLE quotes with a string that contains variables. This won't work, use double quotes instead, i.e.:
$html = file_get_html("WEBSITE.COM/$par");
Perhaps this is the issue?
Also, you could use file_get_contents()
if (file_get_contents("WEBSITE.COM/$par") !== false) {
...
}

Having trouble getting the right idea

well i'm writing a php code to edit tags and data inside those tags but i'm having big trouble getting my head around the thing.
basically i have an xml file similar to this but bigger
<users>
<user1>
<password></password>
</user1>
</users>
and the php code i'm using to try and change the user1 tag is this
function mod_user() {
// Get global Variables
global $access_level;
// Pull the data from the form
$entered_new_username = $_POST['mod_user_new_username'];
$entered_pass = $_POST['mod_user_new_password'];
$entered_confirm_pass = $_POST['mod_user_confirm_new_password'];
$entered_new_roll = $_POST['mod_user_new_roll'];
$entered_new_access_level = $_POST['mod_user_new_access_level'];
// Grab the old username from the last page as well so we know who we are looking for
$current_username = $_POST['mod_user_old_username'];
// !!-------- First thing is first. we need to run checks to make sure that this operation can be completed ----------------!!
// Check to see if the user exist. we just use the normal phaser since we are only reading and it's much easier to make loop through
$xml = simplexml_load_file('../users/users.xml');
// read the xml file find the user to be modified
foreach ($xml->children() as $xml_user_get)
{
$xml_user = ($xml_user_get->getName());
if ($xml_user == $entered_new_username){
// Set array to send data back
//$a = array ("error"=>103, "entered_user"=>$new_user, "entered_roll"=>$new_roll, "entered_access"=>$new_access_level);
// Add to session to be sent back to other page
// $_SESSION['add_error'] = $a;
die("Username Already exist - Pass");
// header('location: ../admin.php?page=usermanage&task=adduser');
}
}
// Check the passwords and make sure they match
if ($entered_pass == $entered_confirm_pass) {
// Encrypt the new password and unset the old password variables so they don't stay in memory un-encrytped
$new_password = hash('sha512', $entered_pass);
unset ($entered_pass, $entered_confirm_pass, $_POST['mod_user_new_password'], $_POST['mod_user_confirm_pass']);
}
else {
die("passwords did not match - Pass");
}
if ($entered_new_access_level != "") {
if ($entered_new_access_level < $access_level){
die("Access level is not sufficiant to grant access - Pass");
}
}
// Now to load up the xml file and commit changes.
$doc = new DOMDocument;
$doc->formatOutput = true;
$doc->perserveWhiteSpace = false;
$doc->load('../users/users.xml');
$old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0);
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($entered_new_username, $old_user);
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
}
when run with just the username entered for change i get this error
Catchable fatal error: Argument 1 passed to DOMNode::replaceChild() must be an instance of DOMNode, string given, called in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 252 and defined in E:\xampp\htdocs\CGS-Intranet\admin\html\useraction.php on line 201
could someone explain to me how to do this or show me how they'd do it.. it might make a little sense to me to see how it's done :s
thanks
$entered_new_username is a string so you'll need to wrap it with a DOM object, via something like$doc->createElement()
$xml_old_user = $doc->getElementsByTagName('users')->item(0)->getElementsByTagName($current_username)->item(0)->replaceChild($doc->createElement($entered_new_username), $old_user);
This may not be quite right, but hopefully it points you in the correct direction.
alright got it writing and replacing the node that i want but i have ran into other issues i have to work out (IE: it's replacing the whole tree rather then just changing the node name)
anyway the code i used is
// For initial debugging - to be deleted
if ($old_user == $current_username)
echo "old username found and matches";
// Check the variables to see if there is something to change in the data.
if ($entered_new_username != "") {
try {
$new_node_name = $doc->createElement($entered_new_username);
$old_user->parentNode->replaceChild($new_node_name, $old_user);
}
catch (DOMException $e) {
echo $e;
}
echo "Username is now: " . $current_username;
}
if ($new_pass != "") {
$current_password = $doc->getElementsByTagName($current_user)->item(0)->getElementsByTagName('password')->item(0)->nodeValue;
//$replace_password = $doc
}
$doc->save('../users/users.xml');

Categories