Automatic conversion of false to array is deprecated - php

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.

Related

php: receive json from POST and save to file

I want to receive a POST request from a JS client with a json body (i.e. this is not form data), and save the .gigs (javascript) array to a file, after checking the .password field. This is all my code (based on Receive JSON POST with PHP)
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)){
/* json_decode(..., true) returns an 'array', not an 'object'
* Working combination: json_decode($json_params) WITH $inp->password
*/
$inp = json_decode($json_params);
} else {
echo "could not decode POST body";
return;
}
$password = $inp->password;
// echo $password;
if ($password == "****") {
$gigs = $inp['gigs'];
// WAS $res = file_put_contents('gigs.json', json_encode($gigs), TEXT_FILE);
$res = file_put_contents('gigs.json', json_encode($gigs));
if ($res > 0) {
echo "Success";
return;
} else {
if (!$res) {
http_response_code(500);
echo "file_put_contents error:".$res;
return;
} else {
http_response_code(500);
echo "Error: saved zero data!";
return;
}
}
}
else {
// http_response_code(403); // (2)
echo "Password invalid";
return;
}
What I find is that
if I comment out the if statement and uncomment echo $password; then the right password is there
if I uncomment line 2, which I want to do, then I get back a 500 and the error logs refer an Illegal string offset 'password' in line (1) above. Without that I get back a "Success" (all for the same password).
I don't understand what is happening, nor how to get 200, 403 and 500 error messages safely.
Note
$json_params = file_get_contents("php://input");
If your scripts are running upon regular HTTP requests, passing data like it comes from HTML form, them you should consider using $_POST for your content, not php://input. If you expect JSON in request body, then I'd be fine, yet I'd also check content type for application/json.
Next:
$inp = "I never got set";
if (strlen($json_params) > 0 && isValidJSON($json_params)){
$inp = json_decode($json_params, true);
}
$password = $inp->password;
$password = $inp['password'];
This is pretty broken. First, see json_decode() arguments (2nd) -> you are decoding to array (true), not object (false), so only $password = $inp['password']; will work in your case. Also the whole code will fail when your input data is invalid as in that case $np is rubbish string, not the array you try to read later on. Use null as default value and check for that prior further use.
Next:
$res = file_put_contents('gigs.json', json_encode($gigs), FILE_TEXT);
there's no FILE_TEXT option for file_put_contents(). Nor you'd need one.
Once you correct these you'd be fine. Also print_r() and var_dump() may be the functions you wish to get familiar with for your further debugging.
In general http://php.net/ -> lookup for functions you are about to use.

Amazon Fatal Error

I am using the amazon.com products API. The call is GetMatchingProductForId. When I type as single value into the call, it works. When I input a large file to my program it works, but I occasionally get a fatal error:
Fatal Error:Can Only Throw Objects in J:/filepath/client.php on line 1003.
I have no idea what the possible error is. When i contacted amazon developer support they said they would investigate the issue.
The problem could possibly be the user input because I ran my program yesterday and was able to get 2797 files in response, but eventually received the same error. When i ran my program for the first time during testing, there was no problem at all. If anyone has knowledge of this error and could explain just the error, I would greatly appreciate it.
Client.php lines 992 - 1004:
for (;;) {
$response = $this->_httpPost($parameters);
$status = $response['Status'];
if ($status == 200) {
return array('ResponseBody' => $response['ResponseBody'],
'ResponseHeaderMetadata' => $response['ResponseHeaderMetadata']);
}
if ($status == 500 && $this->_pauseOnRetry(++$retries)) {
continue;
}
throw $this->_reportAnyErrors($response['ResponseBody'],
$status, $response['ResponseHeaderMetadata']);
}
I did not edit any of this code. This came from developer.amazonservices.com
_reportAnyErrors Function :
private function _reportAnyErrors($responseBody, $status, $responseHeaderMetadata, Exception $e = null)
{
$exProps = array();
$exProps["StatusCode"] = $status;
$exProps["ResponseHeaderMetadata"] = $responseHeaderMetadata;
libxml_use_internal_errors(true); // Silence XML parsing errors
$xmlBody = simplexml_load_string($responseBody);
if ($xmlBody !== false) { // Check XML loaded without errors
$exProps["XML"] = $responseBody;
$exProps["ErrorCode"] = $xmlBody->Error->Code;
$exProps["Message"] = $xmlBody->Error->Message;
$exProps["ErrorType"] = !empty($xmlBody->Error->Type) ? $xmlBody->Error->Type : "Unknown";
$exProps["RequestId"] = !empty($xmlBody->RequestID) ? $xmlBody->RequestID : $xmlBody->RequestId; // 'd' in RequestId is sometimes capitalized
} else { // We got bad XML in response, just throw a generic exception
$exProps["Message"] = "Internal Error";
continue;
}
}
Values :
20373001862
20373002678
20373002685
20373002937
20373003002
20373003583
20373003644
20373003651
20373003675
20373003682
20373003781
20373003811
20373003828
20373003835
20373003842
20373003859
20373003866
20373003873
20373003880
20373003897
20373003903
20373005006
With these values it crashed on the third file which would be the 20th value.

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) {
...
}

Jquery Validation Remote Check Unique Not Working

I wanted to post this online because I have been searching for days on this JQuery Remote validation issue. I cannot get it to work. I think my PHP code is correct as I have test the URL with a query in the URL and it returns false and true depending on with the recordset count is one or more
This is my Jquery Validate Code:
// validate form and submit
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#myform").validate({
rules: {
ord_ref: {
required: true,
minlength: 12,
remote: "check_ord_ref.php"
},
messages: {
ord_ref: {
remote: "Order Number Does Not Exist"
}
}
}
});
});
This is my PHP code for the remote page "check_ord_ref.php"
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = 'false';
} else {
$valid = 'true';
}
echo $valid;
Please someone can you help solve the puzzle for myself and anyone else having issues
Using JQuery 1.5.2min
Validates OK without remote function
Ok, so I'm no PHP expert, but I do know that jQuery Validate expects the following result from a remote validation method:
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements
Sending down "true" or "false" (note the quotation marks) is going to result in the value being parsed as the error message instead of being evaluated as a boolean primitive.
Back to the PHP part, I think you should probably use json_encode with a boolean primitive. I'm not quite sure the way to do this in PHP, but I believe it would be something like this:
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = false; // <-- Note the use of a boolean primitive.
} else {
$valid = true;
}
echo json_encode($valid);
This problem seems to be plaguing remote validation scripters and the jQuery documentation on the matter is clearly lacking.
I notice you are using jQuery 1.5.2: from what I understand (and found from experience) you must use the jQuery callback that is sent to the remote script with $_REQUEST with versions after 1.4, AND jQuery is expecting "true" or "false" as a STRING. Here is an example, confirmed working on multiple forms (I'm using jQuery 1.7.1):
if($totalRows_rscheck_ord_ref < 0){
header('Content-type: application/json');
$valid = 'false'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
} else {
header('Content-type: application/json');
$valid = 'true'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
}
I found this answer here (in the answers section), randomly, and have since stopped pulling out my hair. Hope this helps someone.
To add to Andrew Whitaker's response above, I must stress that you are sure that the response is strictly JSON and that there are no other content types being returned. I was having the same issue with my script, and everything appeared to be set properly - including using json_encode(). After some troubleshooting with Firebug's NET tab, I was able to determine that PHP notices were being sent back to the browser converting the data from JSON to text/html. After I turned the errors off, all was well.
//check_validate.php
<?php
// some logic here
echo json_encode(true);
?>

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