Checking data error in php

PHP error checking [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.

#do something that may cause an $error if (!$error) < #do something that may cause an $error if (!$error) < #do something that may cause an $error if (!$error) < #do something that may cause an $error if (!$error) < >> > > if ($error)
#do something that may cause an $error if ($error) goto error; #do something that may cause an $error if ($error) goto error; #do something that may cause an $error if ($error) goto error; #do something that may cause an $error if ($error) goto error; error: if ($error)

5 Answers 5

if ($error) < trigger_error('Your error', E_USER_ERROR); >#something if ($error)

I wouldn’t. I’d structure my script to use some logically try/catch blocks so I can handle errors without having to resort to massive if statements. and gotos. (You know my university prof’s would give you an F and kick you out of your class if you put a GOTO statement on any script/code project?)

 else return 1/$x; > try < echo inverse(5) . "\n"; echo inverse(0) . "\n"; >catch (Exception $e) < echo 'Caught exception: ', $e->getMessage(), "\n"; > // Continue execution echo 'Hello World'; ?> 
#Do something try < #code for doing something. >catch(Exception $ex) < throw new Exception("error doing something", $ex); >#do something again, and again. this will only happen if the previous worked. try < #Ok let's try this again. >catch(Exception $ex)

If an exception is thrown — it should/need to/please be caught by another catch, or it will just spit out the error all over the user.

GoTo is Considered Harmful (sorry, old joke) — but most of the time, it isn’t needed. There are more flexible ways to handle errors, but it all largely depends on context.

There’s nothing «wrong» with the nested if statements that you provided as an example, but could get a little hard to read if each block is long, easy to misplace a curly brace, thus harder to maintain.

You can just spread it out:

$error = false; /* do something that might set $error to true */ if ($error === false) < /* continue the process, might set error to non-false (tip: pass an error message!) */ >if ($error === false) < /* continue the process, might set error to non-false */ >if ($error === false) < /* continue the process, might set error to non-false */ >if ($error === false) < /* continue the process, might set error to non-false */ >if ($error !== false) < /* generic error handling (report to the user, etc) */ echo 'There was an error: '.$error; die(); >/* report success to the user */ 

I would not use true/false for the $error , but rather false for no error, or a short message describing the error. That will make debugging easier, and you can give your user a useful message.

Читайте также:  Python breakpoint in code

Further, without knowing what you are doing, I would say that this seems like a clunky way to handle errors. Without seeing context, I can’t say for certain, but it seems likely that if an upper portion of the script were to encounter an error, you wouldn’t want to bother with the rest of the script. Maybe better, then:

$error = false; /* do something that might set $error to true */ if ($error !== false) return errorHandler($error); // . etc 

Or maybe using an exception handler:

$error = false; /* do something that might set $error to true */ if ($error !== false) throw new Exception($error); // . etc 

As you can see, there’s more than one way to skin this cat. It really, really, really depends on context, both within the particular function or procedure and within the project as a whole. It is vital to a project to have consistent error handling, so it pays to develop something that is reusable. The first route, with the block of nested ifs (or ifs in a big series) has the mark of an under-developed error handling system — it doesn’t strike me as very systematic or flexible.

Источник

Detect bad json data in PHP json_decode()?

Then json_decode handles the error fine and spits out «bad json data!»; However, if I set $_POST to something like «invalid data», it gives me:

Warning: json_decode() expects parameter 1 to be string, array given in C:\server\www\myserver.dev\public_html\rivrUI\public_home\index.php on line 6 bad json data! 

Do I need to write a custom script to detect valid json data, or is there some other nifty way to detect this?

$_POST is always an array containing the x-www-form-urlencoded parameters passed via POST. How do you send your data to your PHP script?

The included json functions in PHP are not much help. They have a lot of issues. Take a look at json.org to find a good library.

8 Answers 8

Here are a couple of things about json_decode :

  • it returns the data, or null when there is an error
  • it can also return null when there is no error : when the JSON string contains null
  • it raises a warning where there is a warning — warning that you want to make disappear.

To solve the warning problem, a solution would be to use the @ operator (I don’t often recommend using it, as it makes debuging a lot more harder. But here, there is not much of a choice) :

$_POST = array( 'bad data' ); $data = @json_decode($_POST); 

You’d then have to test if $data is null — and, to avoid the case in which json_decode returns null for null in the JSON string, you could check json_last_error , which (quoting) :

Returns the last error (if any) occurred by last JSON parsing.

Which means you’d have to use some code like the following :

if ($data === null && json_last_error() !== JSON_ERROR_NONE)

As Harry Bosch pointed out in another answer, you need only check for JSON_ERROR_NONE !== json_last_error()

Читайте также:  Javascript var by ref

Since PHP 7.3, the json_decode function will accept a new JSON_THROW_ON_ERROR option that will let json_decode throw an exception instead of returning null on error.

try < json_decode("catch (\JsonException $exception) < echo $exception->getMessage(); // displays "Syntax error" > 

I received an exception: «Warning: Use of undefined constant JSON_THROW_ON_ERROR — assumed ‘JSON_THROW_ON_ERROR’ (this will throw an Error in a future version of PHP) in

which as documentation says :

Returns the last error (if any) occurred during the last JSON encoding/decoding.

json_decode($string); switch (json_last_error())

You could do something like this with json_last_error_msg: if (JSON_ERROR_NONE !== json_last_error()) throw new Exception(json_last_error_msg());

This is how Guzzle handles json

 /** * Parse the JSON response body and return an array * * @return array|string|int|bool|float * @throws RuntimeException if the response body is not in JSON format */ public function json() < $data = json_decode((string) $this->body, true); if (JSON_ERROR_NONE !== json_last_error()) < throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error()); >return $data === null ? array() : $data; > 

I just broke my head over a json syntax error in what appeared to be perfect json: from a url encoded string.

But in my case some of the above was html encoded, as adding html_entity_decode($string) did the trick.

$ft = json_decode(html_entity_decode(urldecode(filter_input(INPUT_GET, 'ft', FILTER_SANITIZE_STRING)))); 

Hopefully this will save someone else some time.

I just spent an hour going through all the possible solutions on this page. I took the liberty of collective all these possible solutions into one function, to make it quicker and easier to try and debug.

I hope it can be of use to someone else.

]*?>.*?@si', '', $text ); $text = str_replace(']]>', ']]>', $text); if( $remove_tags )< // Which tags to allow (none!) // $text = strip_tags($text, '

,,,'); $text = strip_tags($text, ''); > if( $remove_line_breaks ) < $text = preg_replace('/[\r\n\t ]+/', ' ', $text); $text = trim( $text ); >if( $remove_BOM ) < // Source: https://stackoverflow.com/a/31594983/1766219 if( 0 === strpos( bin2hex( $text ), 'efbbbf' ) )< $text = substr( $text, 3 ); >> if( $ensure_utf8_encoding ) < // Check if UTF8-encoding if( utf8_encode( utf8_decode( $text ) ) != $text )< $text = mb_convert_encoding( $text, 'utf-8', 'utf-8' ); >> if( $ensure_quotes_are_properly_displayed ) < $text = str_replace('"', '"', $text); >if( $decode_html_entities ) < $text = html_entity_decode( $text ); >/** * Other things to try * - the chr-function: https://stackoverflow.com/a/20845642/1766219 * - stripslashes (THIS ONE BROKE MY JSON DECODING, AFTER IT STARTED WORKING, THOUGH): https://stackoverflow.com/a/28540745/1766219 * - This (improved?) JSON-decoder didn't help me, but it sure looks fancy: https://stackoverflow.com/a/43694325/1766219 */ > return $text; > // Example use $text = decontaminate_text( $text ); // $text = decontaminate_text( $text, false ); // Debug attempt 1 // $text = decontaminate_text( $text, false, false ); // Debug attempt 2 // $text = decontaminate_text( $text, false, false, false ); // Debug attempt 3 $decoded_text = json_decode( $text, true ); echo json_last_error_msg() . ' - ' . json_last_error(); ?>

/** * * custom json_decode * handle json_decode errors * * @param type $json_text * @return type */ public static function custom_json_decode($json_text) < $decoded_array = json_decode($json_text, TRUE); switch (json_last_error()) < case JSON_ERROR_NONE: return array( "status" =>0, "value" => $decoded_array ); case JSON_ERROR_DEPTH: return array( "status" => 1, "value" => 'Maximum stack depth exceeded' ); case JSON_ERROR_STATE_MISMATCH: return array( "status" => 1, "value" => 'Underflow or the modes mismatch' ); case JSON_ERROR_CTRL_CHAR: return array( "status" => 1, "value" => 'Unexpected control character found' ); case JSON_ERROR_SYNTAX: return array( "status" => 1, "value" => 'Syntax error, malformed JSON' ); case JSON_ERROR_UTF8: return array( "status" => 1, "value" => 'Malformed UTF-8 characters, possibly incorrectly encoded' ); default: return array( "status" => 1, "value" => 'Unknown error' ); > > 

Источник

PHP checking if query returns anything error

I’ve been pondering about this for a while, I’m trying to see if the query wields any results and I want to do something if it doesn’t return any results. PHP:

 $json = $_REQUEST['json']; $json = stripslashes($json); $jsonobj = json_decode($json); $me = $jsonobj -> me; $other = $jsonobj -> other; mysql_select_db("tinyspace", $con); $result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')"); if(mysql_num_rows($result) > 0)

5 Answers 5

just to be sure, how many columns do you have named userid ? user_id, user_id1, user_id2 ? do you mean user_id1 in place of user_id in the below line, by any chance?

$result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')"); 

If so, maybe thats why you aren’t fetching any results.

$result = mysql_query("SELECT * FROM friends WHERE (user_id1 = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')"); 

the question asks how to check whether the query returns no results, this answer doesn’t satisfy the question, it should be posted as a comment

for those who think my answer is incorrect or the opposite of what is asked, please read the question from the beginning again, very carefully.

Shouldn’t this be if ($result) instead of the opposite? The else ends up being «if result is false is not true» which is nothing short of confusing.»

the person who asked the question said they wanted to do something if the result returned nothing, this way when the query fails or yields nothing, you can add your code in there, hence my answer

mysql_num_rows() is okay to use for checking if you have results, and should work in your example..

However, if your call to mysql_num_rows() doesn’t work as expected (i.e. always false), it’s almost always down to a problem with the query. mysql_num_rows() expects a result resource, and if there is a problem with your query, mysql_query will return a false.

You can amend your mysql_query() call to

mysql_query("sql here") or die(mysql_error()); 

That should give you an idea if the error lies in the query. Once you’ve checked your query is working as expected, your mysql_num_rows() will start functioning correctly.

Источник

Оцените статью