Check Every Internal Link on a Laravel Site Before You Publish: A Small Script
Broken links are the cheapest SEO and trust problem to fix and the easiest to miss. A call-to-action button that goes to a page that does not exist costs you the visitor most likely to contact you, and nothing in your logs says so. On a content site that grows by dozens of pages a week, a link that was right when you wrote it breaks when a slug changes, a draft is unpublished or a page is renamed.
This guide gives you a short PHP script that crawls a site, follows internal links, and reports every URL that does not answer properly, with the pages that link to it. I wrote it while building this website, and show what it found on a test site with known problems and on this site.
What this article is, and is not
The script is a simple crawler, not a replacement for a search-engine audit tool. I tested it two ways: against a small static site with dead links, a redirect and a link hidden inside JSON, and against this website running locally. It checks internal links only, it does not run JavaScript, and it does not look at images, scripts or styles. It runs on PHP 8.3 with the curl extension. I did not compare it with other tools, and I make no claims about how it performs on a very large site.
What it does
- Reads
/sitemap.xml, if there is one, and the home page, to seed a list of pages.
- Fetches each page and collects every link, from the anchors in the HTML and from links inside embedded JSON page data. Sites built with Inertia or similar frameworks carry page content as JSON, and that JSON escapes slashes, which the script undoes before looking for links.
- Keeps only links to the same site, resolves relative ones, drops the
#fragment, and skips mailto:, tel:, javascript: and files such as images and stylesheets.
- Checks every discovered URL, and remembers which pages linked to it.
- Prints the count of pages, broken links and redirects, with the first three pages that link to each broken URL, and exits with status 1 if anything is broken, so it can fail a deploy.
The script
<?php
/**
* Crawl a site from its sitemap (or the home page) and report broken internal links.
* Usage: php linkcheck.php http://127.0.0.1:8000 [--max=500]
*/
$base = rtrim($argv[1] ?? '', '/');
$max = 500;
foreach ($argv as $arg) { if (str_starts_with($arg, '--max=')) { $max = (int) substr($arg, 6); } }
if ($base === '') { fwrite(STDERR, "Give the site's base URL.\n"); exit(2); }
$host = parse_url($base, PHP_URL_HOST).(parse_url($base, PHP_URL_PORT) ? ':'.parse_url($base, PHP_URL_PORT) : '');
function fetch(string $url, bool $body): array
{
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => 20, CURLOPT_NOBODY => ! $body, CURLOPT_USERAGENT => 'linkcheck/1.0']);
$start = microtime(true);
$content = curl_exec($ch);
$result = ['status' => (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE), 'body' => $body ? (string) $content : '', 'ms' => (microtime(true) - $start) * 1000, 'location' => curl_getinfo($ch, CURLINFO_REDIRECT_URL) ?: null];
curl_close($ch);
return $result;
}
/** Turn an href into a path on this site, or null if it is not an internal page link. */
function internalPath(string $href, string $host, string $currentPath): ?string
{
$href = trim(html_entity_decode($href));
if ($href === '' || preg_match('~^(mailto:|tel:|javascript:|data:|#)~i', $href)) { return null; }
if (preg_match('~^//~', $href)) { $href = 'http:'.$href; }
if (preg_match('~^https?://~i', $href)) {
$p = parse_url($href);
$h = ($p['host'] ?? '').(isset($p['port']) ? ':'.$p['port'] : '');
if ($h !== $host) { return null; } // another site: not checked here
$href = ($p['path'] ?? '/').(isset($p['query']) ? '?'.$p['query'] : '');
} elseif ($href[0] !== '/') {
$href = rtrim(dirname($currentPath), '/').'/'.$href; // relative link
}
$href = preg_replace('~#.*$~', '', $href);
if (preg_match('~\.(png|jpe?g|gif|svg|webp|ico|css|js|woff2?|pdf|zip|xml)(\?.*)?$~i', $href)) { return null; }
return $href === '' ? '/' : $href;
}
// 1. Seed with the sitemap, if there is one, and the home page.
$queue = ['/' => '(start)'];
$sitemap = fetch($base.'/sitemap.xml', true);
if ($sitemap['status'] === 200 && preg_match_all('~<loc>([^<]+)</loc>~', $sitemap['body'], $m)) {
foreach ($m[1] as $loc) { if ($p = internalPath($loc, $host, '/')) { $queue[$p] ??= '(sitemap)'; } }
}
// 2. Visit pages, collecting every internal link and who linked to it.
$seen = []; $linkedFrom = []; $pages = 0; $slow = [];
while ($queue && $pages < $max) {
$path = array_key_first($queue); unset($queue[$path]);
if (isset($seen[$path])) { continue; }
$r = fetch($base.$path, true); $seen[$path] = $r; $pages++;
$slow[$path] = $r['ms'];
if ($r['status'] !== 200) { continue; }
// Anchors in the HTML, and links inside JSON page data (where "/" is escaped as "\/").
$text = str_replace(['\\/', '\\"'], ['/', '"'], $r['body']);
preg_match_all('~href=["\']([^"\']+)["\']~i', $text, $links);
foreach (array_unique($links[1]) as $href) {
if ($target = internalPath($href, $host, $path)) {
$linkedFrom[$target][$path] = true;
if (! isset($seen[$target])) { $queue[$target] ??= $path; }
}
}
}
// 3. Report.
$broken = []; $redirects = [];
foreach ($seen as $path => $r) {
if ($r['status'] === 0 || $r['status'] >= 400) { $broken[$path] = $r['status']; }
elseif ($r['status'] >= 300) { $redirects[$path] = $r['location']; }
}
arsort($slow);
printf("pages checked: %d | links found to internal URLs: %d | broken: %d | redirects: %d\n", $pages, count($linkedFrom), count($broken), count($redirects));
foreach ($broken as $path => $status) {
$from = array_slice(array_keys($linkedFrom[$path] ?? []), 0, 3);
printf(" BROKEN %s (HTTP %s) linked from: %s\n", $path, $status ?: 'no response', $from ? implode(', ', $from) : '(sitemap or start only)');
}
foreach ($redirects as $path => $to) { printf(" REDIRECT %s -> %s\n", $path, $to); }
printf("slowest: %s\n", implode(', ', array_map(fn ($p, $ms) => sprintf('%s %.0f ms', $p, $ms), array_keys(array_slice($slow, 0, 3, true)), array_slice($slow, 0, 3, true))));
exit($broken ? 1 : 0);
First, prove that it can fail
A checker that reports "0 broken" is only meaningful if you have seen it report something else. I built a test site served by PHP's built-in server: a home page with a dead link, an old URL that redirects, a relative link, an external link, a mailto: link, fragment links and a link that exists only inside a JSON block, plus a deeper page with another dead link. The script reported:
pages checked: 9 | links found to internal URLs: 8 | broken: 2 | redirects: 1
BROKEN /missing.html (HTTP 404) linked from: /, /index.html
BROKEN /nowhere-deep.html (HTTP 404) linked from: /deep/page.html
REDIRECT /old -> http://127.0.0.1:9020/ok.html
slowest: / 6 ms, /old 1 ms, /ok.html 1 ms
exit code: 1
Both dead links were found and attributed to the right pages, including one two levels down. The redirect was reported, the link inside the JSON block was followed (the page it points to was checked and found), and the external, mail and fragment links were ignored. The exit code was 1, as it should be.
Then run it on the real site
Against this website, running locally, with 25 published posts and the service, project and category pages:
pages checked: 111 | links found to internal URLs: 111 | broken: 0 | redirects: 0
slowest: /guides/prompt-engineering/llm-prompt-engineering-fundamentals/prompting-basics-instruction-context-format 503 ms, ...
It took about 23 seconds for 111 pages. Zero broken is a reassuring result here only because of the first test: the same script finds problems when they exist. The slowest-pages line is a useful by-product, since a page that takes half a second locally deserves a look.
What it caught in practice, and what it would not
While this site was being built, a set of service pages was written with call-to-action buttons that pointed to a contact page which did not yet exist. I found that by reading the routes before the pages were published, and a crawl later confirmed that every link resolved once the contact page was built. A crawler of this kind catches exactly that class of problem: links to pages that were never created, unpublished or renamed. It does not catch a link that returns 200 but goes to the wrong page, a link that returns 200 on a page that says "not found", or a button that is broken by JavaScript.
When to run it
- Before you publish a batch of pages, against a local or staging copy.
- After every deploy, as a smoke test. The exit code makes it easy to wire into a deploy script or a scheduled job.
- Before and after changing a URL structure or a slug.
- On a schedule, such as weekly, to catch the slow decay of content over time.
Limitations to know about
- Links that exist only after JavaScript runs are not seen unless they are in the HTML or in the embedded JSON. If your pages are rendered only in the browser, use a tool that runs one.
- Pages behind a login are not crawled.
- External links are not checked. Checking them is slower and noisier, and a remote site that blocks crawlers produces false alarms.
- It does not follow redirects. It reports them, so you can fix internal links to point straight at the final URL.
- Politeness. It sends requests one after another with no delay. Against a production site, add a short pause, or run it against a copy.
- It stops at
--max pages (500 by default) to protect you from crawling endlessly.
Common mistakes
- Trusting a clean report from a tool you have never seen fail.
- Only checking the sitemap, which lists the pages you meant to publish and not the links in them.
- Only checking the home page.
- Ignoring redirects, which slow every visitor and waste crawl budget.
- Running it once instead of making it part of the routine.
Frequently asked questions
Why not use an existing tool?
There are good ones. I wanted something small that reads the page data of a JavaScript framework, runs in the same language as the project and returns an exit code. Use whatever fits you.
Does it work for non-Laravel sites?
Yes. It only needs HTTP and, optionally, a sitemap.
Can it check my staging site behind a password?
Not as written. You would add authentication to the fetch() function. I did not test that.
How do I run it in CI?
Start the site, run the script against it, and let the exit code decide whether the job passes. I have not set this up here.
Where this fits
If you want a website or web application checked, fixed and kept clean as it grows, see Full-Stack Web Development, or describe your site here. The related build log is how this site is built. More productivity guides are collected under Developer Productivity.