Code samples and practical examples for integrating ShowHeaders into your applications, debugging workflows, and learning projects.
Check headers from a web application using the Fetch API:
// Redirect user to see their headers
function showMyHeaders() {
window.open('https://showheaders.com/headers.php', '_blank');
}
// Or embed in an iframe for seamless integration
function embedHeaderViewer() {
const iframe = document.createElement('iframe');
iframe.src = 'https://showheaders.com/headers.php';
iframe.style.width = '100%';
iframe.style.height = '600px';
iframe.style.border = 'none';
document.getElementById('header-container').appendChild(iframe);
}
// Fetch headers data programmatically (for your own endpoint)
async function getHeadersData() {
try {
const response = await fetch('https://showheaders.com/headers.php?format=json');
const headers = await response.json();
console.log('User headers:', headers);
return headers;
} catch (error) {
console.error('Error fetching headers:', error);
}
}
A React component for header inspection:
import React, { useState, useEffect } from 'react';
const HeaderInspector = () => {
const [headers, setHeaders] = useState(null);
const [loading, setLoading] = useState(false);
const inspectHeaders = () => {
// Open in new window for inspection
window.open('https://showheaders.com/headers.php', 'headers',
'width=800,height=600,scrollbars=yes');
};
return (
<div className="header-inspector">
<h3>HTTP Header Inspector</h3>
<p>Click below to see what headers your browser sends:</p>
<button
onClick={inspectHeaders}
className="btn btn-primary"
>
🔍 Inspect My Headers
</button>
<p className="mt-2 text-muted">
Powered by <a href="https://showheaders.com">ShowHeaders</a>
</p>
</div>
);
};
export default HeaderInspector;
Analyze and redirect to ShowHeaders from your PHP application:
<?php
// Simple header debugging function
function debugHeaders() {
echo "<h3>Quick Header Debug</h3>";
echo "<a href='https://showheaders.com/headers.php' target='_blank' class='btn btn-info'>";
echo "🔍 View Full Headers on ShowHeaders";
echo "</a>";
echo "<h4 class='mt-3'>Key Headers:</h4>";
$key_headers = ['HTTP_USER_AGENT', 'HTTP_REFERER', 'HTTP_ACCEPT_LANGUAGE'];
foreach($key_headers as $header) {
$value = $_SERVER[$header] ?? 'Not set';
echo "<p><strong>" . str_replace('HTTP_', '', $header) . ":</strong> " . htmlspecialchars($value) . "</p>";
}
}
// Advanced header inspection with ShowHeaders integration
class HeaderInspector {
private $showHeadersUrl = 'https://showheaders.com/headers.php';
public function generateInspectionLink($custom_params = []) {
$params = array_merge(['source' => 'your-app'], $custom_params);
return $this->showHeadersUrl . '?' . http_build_query($params);
}
public function embedInspector($width = '100%', $height = '600px') {
$url = $this->generateInspectionLink();
return "<iframe src='{$url}' width='{$width}' height='{$height}' frameborder='0'></iframe>";
}
public function getUserAgent() {
return $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
}
public function isBot() {
$ua = strtolower($this->getUserAgent());
$bots = ['googlebot', 'bingbot', 'slurp', 'crawler', 'spider'];
foreach($bots as $bot) {
if(strpos($ua, $bot) !== false) {
return true;
}
}
return false;
}
}
// Usage
$inspector = new HeaderInspector();
echo $inspector->embedInspector();
?>
Integrate header inspection into a Flask web application:
from flask import Flask, request, render_template_string
import requests
app = Flask(__name__)
@app.route('/debug-headers')
def debug_headers():
"""Show user headers with link to ShowHeaders for detailed view"""
# Get key headers
user_agent = request.headers.get('User-Agent', 'Unknown')
referer = request.headers.get('Referer', 'Direct visit')
accept_lang = request.headers.get('Accept-Language', 'Not specified')
template = '''
<!DOCTYPE html>
<html>
<head>
<title>Header Debug</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-4">
<h2>🔍 Header Debug Tool</h2>
<div class="alert alert-info">
<strong>Quick Overview:</strong>
<ul>
<li><strong>User Agent:</strong> {{ user_agent }}</li>
<li><strong>Referer:</strong> {{ referer }}</li>
<li><strong>Language:</strong> {{ accept_lang }}</li>
</ul>
</div>
<a href="https://showheaders.com/headers.php" target="_blank" class="btn btn-primary">
🛰️ View Complete Headers on ShowHeaders
</a>
<div class="mt-4">
<h4>Integration Example:</h4>
<iframe src="https://showheaders.com/headers.php"
width="100%" height="400" frameborder="0"></iframe>
</div>
</body>
</html>
'''
return render_template_string(template,
user_agent=user_agent,
referer=referer,
accept_lang=accept_lang)
# Header analysis utilities
class HeaderAnalyzer:
@staticmethod
def detect_browser(user_agent):
ua = user_agent.lower()
if 'chrome' in ua:
return 'Chrome'
elif 'firefox' in ua:
return 'Firefox'
elif 'safari' in ua:
return 'Safari'
elif 'edge' in ua:
return 'Edge'
return 'Unknown'
@staticmethod
def detect_mobile(user_agent):
mobile_indicators = ['mobile', 'android', 'iphone', 'ipad']
ua = user_agent.lower()
return any(indicator in ua for indicator in mobile_indicators)
if __name__ == '__main__':
app.run(debug=True)
Use ShowHeaders in your testing pipeline to verify header behavior:
// Selenium WebDriver example for automated header testing
const { Builder, By, until } = require('selenium-webdriver');
async function testHeaderBehavior() {
const driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to your application
await driver.get('https://your-app.com');
// Click a link that should send specific headers
await driver.findElement(By.id('special-link')).click();
// Navigate to ShowHeaders to inspect the result
await driver.get('https://showheaders.com/headers.php');
// Wait for the table to load
await driver.wait(until.elementLocated(By.css('table')), 5000);
// Verify specific headers are present
const pageSource = await driver.getPageSource();
if (pageSource.includes('X-Custom-Header')) {
console.log('✅ Custom header found');
} else {
console.log('❌ Custom header missing');
}
} finally {
await driver.quit();
}
}
// Jest test example
describe('Header Testing', () => {
test('should include proper referrer header', async () => {
// Mock fetch to capture outgoing headers
const mockFetch = jest.fn();
global.fetch = mockFetch;
// Simulate click that should send headers
await simulateHeaderSendingAction();
// Verify the call was made with expected headers
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('showheaders.com'),
expect.objectContaining({
headers: expect.objectContaining({
'Referer': expect.stringContaining('your-app.com')
})
})
);
});
});
Command-line header testing with cURL:
# Basic header inspection
curl -H "Custom-Header: MyValue" https://showheaders.com/headers.php
# Test with specific User-Agent
curl -H "User-Agent: MyApp/1.0" https://showheaders.com/headers.php
# Test with authentication header
curl -H "Authorization: Bearer token123" https://showheaders.com/headers.php
# Get JSON response for parsing
curl -H "Accept: application/json" "https://showheaders.com/headers.php?format=json"
# Test referrer behavior
curl -H "Referer: https://example.com/test-page" https://showheaders.com/headers.php
# Advanced: Test multiple headers and save output
curl -v \
-H "X-API-Key: secret123" \
-H "Content-Type: application/json" \
-H "Accept-Language: en-US,en;q=0.9" \
-H "Cache-Control: no-cache" \
https://showheaders.com/headers.php > headers_test.html
# Parse JSON response with jq
curl -s "https://showheaders.com/headers.php?format=json" | jq '.["User-Agent"]'
Use ShowHeaders to teach web security concepts:
<!-- Security Headers Educational Demo -->
<div class="security-demo">
<h3>🔒 Web Security Headers Demo</h3>
<div class="row">
<div class="col-md-6">
<h5>Normal Request</h5>
<p>Click to see standard browser headers:</p>
<a href="https://showheaders.com/headers.php" class="btn btn-primary">
View Normal Headers
</a>
</div>
<div class="col-md-6">
<h5>Security-Enhanced Request</h5>
<p>Headers with security enhancements:</p>
<form action="https://showheaders.com/headers.php" method="GET">
<input type="hidden" name="demo" value="security">
<button type="submit" class="btn btn-success">
View Secure Headers
</button>
</form>
</div>
</div>
<div class="mt-4">
<h5>Learning Points:</h5>
<ul>
<li><strong>DNT Header:</strong> Shows user privacy preferences</li>
<li><strong>Sec-Fetch Headers:</strong> Help prevent CSRF attacks</li>
<li><strong>Referer Policy:</strong> Controls referrer information leakage</li>
</ul>
</div>
</div>
<script>
// Educational: Show how JavaScript can modify headers
function demonstrateHeaderModification() {
// Note: Most security headers cannot be modified by JavaScript
console.log('Security headers are typically controlled by the browser');
// Open ShowHeaders to show current state
window.open('https://showheaders.com/headers.php?educational=true', '_blank');
}
</script>
?format=json
to get programmatic access to header data