La respuesta es si y no. Como poder hacer se puede haciendo uso del evento onunload de JavaScript + un poco de AJAX. Algo como esto:
test.php
Código PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Documento sin título</title>
<script type="text/javascript">
function nuevoAjax()
{
var xmlhttp=false;
try
{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) { xmlhttp=false; }
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); }
return xmlhttp;
}
function meCerre()
{
var ajax=nuevoAjax();
var dato="un dato";
ajax.open("POST", "test2.php", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("dato="+dato);
}
</script>
</head>
<body onunload="meCerre()">
</body>
</html>
test2.php
Código PHP:
<?php
$var=$_POST['dato'];
$file=fopen('archivo.txt', 'a');
fwrite($file, $var.' - ');
fclose($file);
?>
El problema es que con el evento onunload no tenés la certeza de que tu PHP se vaya a ejecutar siempre que el usuario cierra el navegador ya que puede tener el JS deshabilitado. Por este motivo esta solución es aplicable solo cuando el código a ejecutarse en servidor no es indispensable que se ejecute.
Saludos.