0

I am migrating code from PHP 5 to PHP 8 and I got new errors I've never had during 20 years...

Here is PHP 5 code (without errors) :

 <?php


if (isset($_POST['valid']) && $_POST['valid'] == '1') {
    // Check submission
    $errors = array();
    if (!$_POST['field']) $errors[] = 'Field : field is required';

    if (!count($errors)) {
        // database processing is done here.
        header('Location:/')
        exit();
    }
}

<html>
<head>
</head>
<body>

    <?php
            
    if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'add' || $_REQUEST['action'] == 'edit')) {
        // edit
        if (isset($_GET['action'])) {
            if ($_GET['action'] == 'edit')  {
                foreach($row as $k => $v) {
                    $_POST[$k] = $v;
                }
            }
            elseif($_GET['action'] == 'add'){
                $_POST['field'] = 'default value';
            }
        }

        // show errors from post
        if (count($errors)) show_errors($errors);

        // show form to add / edit datas
        echo ' 

    <form method="post" action="{$_SERVER['PHP_SELF']}">
        <input type="hidden" name="action" value="',$_REQUEST['action'],'" />
        <input type="text" name="field" id="field" maxlength="100" size="90" value="',$_POST['field'],'">
        <input type="text" name="field2" id="field2" maxlength="100" size="90" value="',$_POST['field2'],'">


        <input type="submit">
    </form>
    ';
</body>
</html>

Hosted this same code with PHP 8, when I load page ($_GET), I get for each input field this error : Warning: Undefined array key "field"

Is there a way to prevent this error without writing a condition by field to keep quick (and clean) code writing ?

Yohan

Yohan
  • 593
  • 1
  • 4
  • 4

0 Answers0