Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

Populate form text input from PHP session - Simplify existing code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is the shortest code I can came up:

echo '<input type="text" value="' . ($_SESSION['myfield'] ?? '') . '">';

More herein Null Coalescing Operator: https://www.php.net/manual/en/language.operators.comparison.php

For filter var you need to use the same operator, inside the function:

echo '<input type="text" value="' . (filter_var($_SESSION['myfield'] ?? '', FILTER_SANITIZE_STRING) : '') . '">';

or implement a function to filter multiples vars at once:

function filterMySessionVars() {
    $myVars = ['myfield1','myfield2',];
    foreach($myVars as $v) {
        $_SESSION[$v] = filter_var($_SESSION[$v] ?? '', FILTER_SANITIZE_STRING);
    }
}
filterMySessionVars();

echo '<input type="text" value="'.$_SESSION['myfield'].'">';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...