What is the correct way to use the Location header?

Asked

Viewed 34,966 times

4

I am doing a course of PHP and Mysql in Alura and arrived at the part where we build the code that removes the product from the database.

The page calling the delete function has to redirect the user back to the page produto-lista.php and the course instructor suggested the following code:

<?php
  include("cabecalho.php");
  include("conecta.php");
  include("banco-produto.php");

  $id = $_GET['id'];
  removeProduto($conexao, $id);
  header["location: produto-lista.php"];
?>

It turns out that this way the product is rather being removed however the header location is generating me the following error:

Notice: Use of Undefined Constant header - assumed 'header' in C: xampp htdocs store remove-product.php on line 8

Warning: Illegal string offset 'Location: produto-lista.php' in C: xampp htdocs store remove-product.php on line 8

I’m using Xamp for Windows.

  • 4

    Always take a look at PHP manual to use functions you don’t know. Now, what A lot of people forget is that pretty much always, after a Location header you always need an Exit() or die() if you have more code on the page, and the header is conditional. In your case, if there’s nothing else on the page, Exit won’t make a difference. But it is important to know that if it does not exist, the customer will receive all the information before redirecting.

  • 2

    Another problem I see constantly with solutions like this are the warnings Warning: Cannot modify header information - headers already sent by (output started at ..., yeah, probably this cabecalho.php is generating HTML code that has already generated a header and you try to modify it.

  • 1

    @Renoirdosreis totally oblivious to the question: the course of Alura is good?

  • 1

    Hi @Bia, I’m really enjoying the courses of Alura and I’m already able to develop interesting things with just under a week of total immersion in it, hugs!

2 answers

11


In place of header["location: produto-lista.php"]; puts header("location: produto-lista.php"); die('Não ignore meu cabeçalho...');

The die() is important so that nothing runs after this command, thus avoiding some unexpected error, could use exit() also.

7

The error found in the code you posted in the question is in the way you are calling the header function, where instead of using parentheses you are using brackets.

Wrong shape:

header["location: produto-lista.php"];

Correct form:

header("location: produto-lista.php");

Note: Also remembering that the header function has to be always used before any output of data sent, because it handles the header of the sent HTTP request.

  • +1 By observation. It is common header does not work because something has already been sent before.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.