Accessing super globals (PHP & MySQL: Novice to Ninja)

Hi,

I am getting an error about it being bad practice to access super global directly on these three functions. How should I rewrite them?

public function delete()
    {
        $this->jokesTable->delete($_POST['id']);
        header('location: /joke/list');
    }

public function saveEdit()
    {
        $joke = $_POST['joke'];
        $joke['jokedate'] = new \DateTime();
        $joke['authorId'] = 1;
        $this->jokesTable->save($joke);
        header('location: /joke/list');
    }

public function edit()
    {
        if (isset($_GET['id'])) {
            $joke = $this->jokesTable->findById($_GET['id']);
        }
        $title = 'Edit joke';
        return ['template' => 'editjoke.html.php',
        'title' => $title,
        'variables' => [
         'joke' => $joke ?? null
                    ]
        ];
    }

Cheers.
Mike

public function delete(int $id)
{
    $this->jokesTable->delete($id);
    header('location: /joke/list');
}

// passing arrays into methods is quite a bad idea
// it would be better to pass all seperate elements of
// the joke as parameters, or use a simple object
// with properties
// Since I don't know the full structure of 
// $_POST['joke'] I'm unable to provide that here
public function saveEdit(array $jokeData)
{
    $joke = $jokeData;
    $joke['jokedate'] = new \DateTime();
    $joke['authorId'] = 1;
    $this->jokesTable->save($joke);
    header('location: /joke/list');
}

// if no id is set you can't call this function - it doesn't make sense
public function edit(int $id)
{
    $joke = $this->jokesTable->findById($id);
    $title = 'Edit joke';
    return ['template' => 'editjoke.html.php',
    'title' => $title,
    'variables' => [
        'joke' => $joke ?? null
                ]
    ];
}

Hi, rpkamp

The code I’m using is from a SitePoint book (PHP & MySQL: Novice to Ninja). It is from a custom framework which doesn’t work like you’ve suggested here (arguments are not passed in where you have done so).

Apologies. I’ll rephrase the question to aim it at those who have read the book.

Mike

I think the super globals $_POSTshould be sanitized before usage.

It would be interesting to run the complete project through Tom Butler’s latest PHP validation tool. The results are comprehensive and should give explicit solutions to the problematic script.

https://r.je/about

Hi, John.

A promising concept but no results for the above… no detection of the errors. Two errors (unrelated to this) were detected which, if memory serves me, Tom fixes as he builds the framework towards completion.

But no help here.

Mike

What validation utility shows the errors?

Usually the validation tool offered solutions.