نستخدم الدالة header():
header('Content-Type: application/json');
echo json_encode(['ok' => true]);
استخدامات شائعة
// redirect to another page
header('Location: /thank-you');
exit;
// a response status
http_response_code(404);
// force a file download
header('Content-Disposition: attachment; filename="report.csv"');
أشهر خطأ
Headers already sent: يحدث إذا أرسلت أي مخرجات قبل header()، حتى مسافة أو سطر فارغ قبل <?php. الترويسات يجب أن تُرسل قبل أي محتوى.
وبعد التحويل بـ Location اكتب exit;، حتى لا يكمل الكود التنفيذ.