I'm using the function header("Location: example.php") on a page that runs a MySQL query that creates a photogallery and then redirects to the page of the photogallery just created itself. 
The problem is that, after having created 3 or 4 photogalleries this error shows up:
"Cannot modify header information - headers already sent by ..."
I know that before header() shouldn't be any output, but my question is: why it does work for a few times and then it fails?
<?php 
if(isset($_POST['crea'])){
    $nome_lista = $_POST['nome_lista'];
    $slug_lista = str_replace(' ','_',$nome_lista);
    $luogo_lista = $_POST['luogo_lista'];
    $inserisci = mysql_query("INSERT INTO `prova`(`id_lista`, `nome_lista`,`slug_lista`, `id_utente`, `luogo_lista`,`copertina`) VALUES (NULL,'$nome_lista','$slug_lista','$user_id','$luogo_lista','copertina.jpg')");
    $user_id = $_SESSION['id_utente'];
    $id_lista = mysql_query("
    SELECT id_lista 
    FROM prova 
    WHERE id_utente ='$user_id'
    ORDER BY id_lista DESC");
    $ultima_lista = mysql_result($id_lista,0); 
    if($inserisci){
        $percorso_album = "./img_globali/".$user_id.$username;
        mkdir($percorso_album."/".$slug_lista, 0775);
    }else{
        echo 'Non ho inserito la cartella del nuovo album '.mysql_error();
    } 
    header("location: album.php?id=".$ultima_lista);
    exit;
}
?>
The query is executed, even though the page doesn't redirect
 
     
     
     
    