Whether this use of entry data safe?

The user fills the form , data is sent with the POST method.
In PHP scripts similar to the following
foreach ($_POST as $key => $value){
 if (empty($_POST[$key]))
 $errors[$key]='Field is required';
 else {
 //processing the input data
 //if error found, add it to the array $erors[$key];
 //and in the html the user sees what is wrong
 //if everything is OK, send the data to the database.

In html tags that the user did not fill in all 10 fields again, in case of an error the error or incorrect data, such as the following:
<input type="text" name="firstname" value="<?=($_POST['firstname']) ?? ";?>" required>

Is it safe to substitute values obtained from POST(after all, in fact they just fill in the form, without checking in the database they will not go away) or is it not?
June 5th 19 at 21:05
3 answers
June 5th 19 at 21:07
<input type="text" name="firstname" value="<?=($_POST['firstname']) ?? ";?>" required>

$_POST['firstname']='"<script src="scripts.js"></script>'
sure! - Mikel64 commented on June 5th 19 at 21:10
June 5th 19 at 21:09
User input should be cleaned/screened/checked before displaying.
June 5th 19 at 21:11
First you need to see if a POST request came from?

To go through all the contents of the global array is not good.
Instead of foreach ($_POST as $key => $value){
You should have a list of keys that you will later use. For example, if you checked only 1 box and the key 'id' then you can use array_key_exists or filter_has_var:
 if (array_key_exists('id',$_POST)){
 // cleaning the input variable


also you should know what type of data will be listed under specific key of the input array, number, string, array and so on. For validation you can use the function filter_input:

either a simple type conversion if the number is:
$id = (int) $_POST['id'];
$id = intval( $_POST['id']);

or regular expression, like so:
$id = 0; // default value
if (!preg_match("/^[1-9]\d+{1,9}$/")){
 $id = $_POST['id'];

In your case, you want to slightly reduce the work of user is that he did not enter the data again.
this is usually used htmlspecialchars, htmlentities. You can also regular expressions to clean or anything else, the options are many.

Finally we give the function that is used to protect the lines in yii2,

function encode($content, $doubleEncode = true){
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', $doubleEncode);

then your code will look like:
<input type="text" name="firstname" value="<?=encode($_POST['firstname']) ?>" required>

Find more questions by tags HTMLPHP