Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Show or Hide a Button with a PHP Condition

Conditionally render a PHP button or download link with a strict status check, while avoiding invalid HTML and insecure UI-only access control.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Render the control only when the server-side status matches the expected value:

<?php if ($status === 'COMPLETE'): ?>
    <a href="/download.php?id=<?= (int) $fileId ?>" download>
        Download
    </a>
<?php endif; ?>

When $status is not exactly COMPLETE, PHP sends no download link to the browser.

As an Amazon Associate I earn from qualifying purchases.

Use an anchor for downloads

The original SitePoint question uses a button with href and download. A normal <button> does not navigate to an href; use an anchor for a downloadable resource:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The HTML anchor element is intended for links, while buttons are for form submission or actions handled by JavaScript.

#1 Best Overall
Sale
GTAAOY 9.5 mm Metal Snap Buttons with Snap Pliers, 100 Sets / 400 pcs
  • Metal snap buttons: Metal Snaps Buttons with Snap Pliers, 100 sets/400 pieces of snap button: Hollow Prong Snaps cover 200 pcs, Female Button 100 pcs,Male Button 100 pcs.
  • Metal Snap size: approx. 6.5 mm/ 0.23(1/4) inch in inside diameter, 9.5 mm/ 0.35(3/8) inch in outside diameter.Please note that this product is more suitable for baby clothes bibs etc.
  • High Quality Materials:This No-Sew Buttons are made of high quality copper, long-lasting, not easy to fade and deformation. Aluminum fastening pliers with special added non-slip handle design, easy to control and use.
  • Wide Range of Uses: Metal Snaps can be used for a variety of DIY clothes, cloth bags, dolls, cloth Christmas gifts and any cloth products you feel the need to snap. And has a certain decorative role. Exercise your hands, enjoy the fun of DIY.
  • Suggestion: Since the press button on the pliers have two positions, so be sure to press the button correctly installed in the appropriate location, so you can use a piece of waste cloth for the first time to experience to avoid unnecessary losses.
<?php if ($status === 'COMPLETE'): ?>
    <a href="/downloads/myfile.jpg" download class="download-button">
        Download
    </a>
<?php endif; ?>

The download attribute is a browser hint, not a security control. Browser behavior can depend on the response headers, origin, and other restrictions. See the HTML specification.

Why use ===?

Use a strict comparison when the required value is a known string:

$status === 'COMPLETE'

This checks both the value and its type and avoids unintended matches from PHP’s type juggling. PHP documents strict comparison in its comparison operators reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If formatting is known to be inconsistent, normalize it explicitly:

Rank #2
100PCS Cover Button Kit with Tools, DIY Fabric Covered Buttons Set - 5 Sizes & Fabric Template for DIY Covered Buttons, Clothes, Hats, Sweaters, Backpacks and Crafts
  • Package Lists: You will get 5 sizes of button covers and 1 installation tool kits, 20 button covers of each size, 101 sets in total. The button cover kit includes cover button and wire back.
  • Various Button Sizes with Fabric Template: There is a combination of 5 sizes #12 MM, #15MM, #18MM, #22MM, #28MM, 20 sets of each size, which can better help you choose and match different clothes.Cutting fabric with templates is more convenient!
  • DIY Your Own Buttons: The included tools can help you easily DIY your own buttons, decorate your clothes according to your hobbies.(Please refer to the picture steps, easy to assemble.)
  • Premium Aluminum Alloy Button: Our cover button kit is made of premium aluminum alloy, compact and lightweight, sturdy and long-lasting. These button covers will not increase extra weight to your clothes while decorate your clothes.
  • Wide Application: These button covers are widely used in clothes, hats, sweaters, backpacks, DIY crafts, etc. Multiple sizes are available and you can choose suitable buttons according to different clothing to DIY buttons in your own styles.
$status = strtoupper(trim((string) ($status ?? '')));

if ($status === 'COMPLETE') {
    // Render the control.
}

For security-sensitive workflow states, it is better to correct the source data rather than silently normalizing invalid values.

Alternative PHP syntax versus echo

PHP’s template-friendly alternative syntax is usually easier to maintain when the condition contains HTML:

<?php if ($status === 'COMPLETE'): ?>
    <a href="/download.php" download>Download</a>
<?php endif; ?>

This is equivalent to echoing the markup:

<?php
if ($status === 'COMPLETE') {
    echo '<a href="/download.php" download>Download</a>';
}
?>

Use echo for very small fragments. Larger HTML becomes harder to read because of nested quotes and escaping.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Omit, hide, or disable the control?

Requirement Recommended approach
The action is irrelevant unless eligible Omit it with a PHP condition
JavaScript may reveal it later Keep it in the document with hidden
The action is relevant but temporarily unavailable Show a disabled control with an explanation
The layout must reserve its space Use visibility: hidden

Keep the element but hide it

<a href="/download.php" download
   <?= $status === 'COMPLETE' ? '' : 'hidden' ?>>
    Download
</a>

The HTML hidden attribute keeps the element in the markup while preventing normal presentation.

Rank #3
FIKLOTA Universal Cover Button Tool
  • Customizable Button Making: Elevate your sewing projects with our Universal Brass Cover Button Tool. Craft buttons that perfectly match your style by using your favorite fabrics in colors and patterns that express your unique taste. This tool allows you to create buttons that are not only functional but also a true reflection of your preferences.
  • Versatile Sizes: With five convenient options (11mm, 15mm, 19mm, 23mm, 29mm), this cover button tool caters to a variety of needs. Whether you're working on delicate details or larger designs, this tool provides the versatility you require to create buttons of different sizes, enhancing the customization options for your projects.
  • Easy to Use: The universal design of this tool makes it user-friendly for both beginners and experienced crafters. Simply select the size you need, cut your favorite fabric, and effortlessly craft personalized buttons to enhance your garments, accessories, or home decor items.
  • Define Your Style: Take control of your creative process and define your own unique style. The ability to choose fabric colors and patterns empowers you to make buttons that seamlessly integrate with your projects, providing a professional and personalized touch.
  • 5-in-1 Design: The inclusion of five sizes ensures that you have the right tool for various projects. Whether you're working on a small-scale DIY project or a larger sewing endeavor, this universal cover button tool makes it easy to meet your multiple button-making needs with precision and ease.

CSS alternatives include:

.is-hidden {
    display: none;
}

.is-invisible {
    visibility: hidden;
}

display: none removes the element from the layout. visibility: hidden normally preserves its layout space, which can leave an unwanted gap.

Show a disabled button

<button type="button" <?= $status === 'COMPLETE' ? '' : 'disabled' ?>>
    Download
</button>

Use this when the action is relevant but unavailable for now. Explain why it is disabled. Neither a disabled control nor a hidden element prevents a user from sending a direct request.

Secure the download endpoint separately

Conditional rendering controls presentation only. Anyone who knows or guesses the endpoint may request it directly, so the endpoint must authenticate the user and re-check authorization, ownership, and status.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    exit('Authentication required.');
}

$fileId = filter_input(INPUT_GET, 'file', FILTER_VALIDATE_INT);
if ($fileId === false || $fileId === null) {
    http_response_code(400);
    exit('Invalid file.');
}

// Load the record with a prepared query.
// Verify ownership, permission, and current status on the server.
if ($status !== 'COMPLETE' || $ownerId !== $_SESSION['user_id']) {
    http_response_code(403);
    exit('Download not permitted.');
}

$filePath = '/srv/private-files/myfile.jpg';
if (!is_file($filePath) || !is_readable($filePath)) {
    http_response_code(404);
    exit('File not found.');
}

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="myfile.jpg"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);

Do not accept a raw filesystem path from the request. Resolve a trusted server-side path from a validated identifier.

Rank #4
YEQIN Universal Tool for Cover Button 673170 - Make Own Covered Buttons (11-29mm Size)
  • Universal Tool for Cover Buttons of Brass
  • Size: 11mm, 15mm, 19mm, 23mm, 29mm
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Database values, IDs, and output escaping

If the status comes from a database, compare it on the server and encode dynamic values for their output context:

$status = $row['status'] ?? null;

?>
<?php if ($status === 'COMPLETE'): ?>
    <a href="/download.php?id=<?= (int) $row['id'] ?>" download>
        Download
    </a>
<?php endif; ?>

For arbitrary text inserted into HTML, use htmlspecialchars():

<?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>

For multiple permitted statuses, use an explicit allowlist with strict comparison:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$downloadableStatuses = ['COMPLETE', 'READY'];

if (in_array($status, $downloadableStatuses, true)):
?>
    <a href="/download.php?id=<?= (int) $fileId ?>" download>Download</a>
<?php endif; ?>

Combine the status with server-calculated permissions when access varies by user:

Best Value
OKYMOTOR 100PCS Cover Button Kit with Tools, DIY Fabric Covered Buttons Set - 5 Sizes & Fabric Template for DIY Covered Buttons, Clothes, Hats, Sweaters, Backpacks and Crafts
  • Package Lists: You will get 5 sizes of button covers and 1 installation tool kits, 20 button covers of each size, 101 sets in total. The button cover kit includes cover button and wire back.
  • Premium Aluminum Alloy Button: Our cover button kit is made of premium aluminum alloy, compact and lightweight, sturdy and long-lasting. These button covers will not increase extra weight to your clothes while decorate your clothes.
  • Various Button Sizes with Fabric Template: There is a combination of 5 sizes #12 MM, #15MM, #18MM, #22MM, #28MM, 20 sets of each size, which can better help you choose and match different clothes.Cutting fabric with templates is more convenient!
  • DIY Your Own Buttons: The included tools can help you easily DIY your own buttons, decorate your clothes according to your hobbies.(Please refer to the picture steps, easy to assemble.)
  • Wide Range of Application: These button covers are widely used in clothes, hats, sweaters, backpacks, DIY crafts, etc. Multiple sizes are available and you can choose suitable buttons according to different clothing to DIY buttons in your own styles.
<?php if ($status === 'COMPLETE' && $currentUserCanDownload): ?>
    <a href="/download.php?id=<?= (int) $fileId ?>" download>Download</a>
<?php endif; ?>

When the status changes after page load

PHP runs on the server before the response reaches the browser. It cannot react to a later database change without another request. Reload the page, poll an endpoint, or use a live mechanism such as Server-Sent Events or WebSockets.

For a client-side update, keep the control hidden initially and toggle it after receiving a trusted status response:

<a id="download-button" href="/downloads/myfile.jpg" download hidden>
    Download
</a>

<script>
function updateDownloadButton(status) {
    document.querySelector('#download-button').hidden = status !== 'COMPLETE';
}

updateDownloadButton('COMPLETE');
</script>

This improves the interface only. The endpoint must still perform its own authorization check.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a form button is the right choice

Use a form and a submit button when the action is a POST request or requires application processing:

<?php if ($status === 'COMPLETE'): ?>
    <form method="post" action="/download.php">
        <input type="hidden" name="file_id" value="<?= (int) $fileId ?>">
        <button type="submit">Download</button>
    </form>
<?php endif; ?>

Specify type explicitly: a button inside a form can otherwise behave as a submit button. Add CSRF protection where required by your application’s security model.

Troubleshooting checklist

  • Write 'COMPLETE' as a quoted string unless COMPLETE is deliberately defined as a constant.
  • Check capitalization and trailing whitespace in database values.
  • Use <a href="..." download> for a file link, not href on a button.
  • Use an absolute path such as /downloads/file.jpg; a value beginning with www. but lacking a scheme may be treated as relative.
  • Remember that hidden, disabled, and CSS-controlled states are not authorization.
  • Escape arbitrary dynamic HTML values with htmlspecialchars().
  • Reload or fetch fresh status data if a cached page shows an old state.

Recommendation

For a normal server-rendered PHP page, omit the control with a strict condition:

<?php if ($status === 'COMPLETE'): ?>
    <a href="/download.php?id=<?= (int) $fileId ?>" download>
        Download
    </a>
<?php endif; ?>

Use hidden or JavaScript only when the control must remain available for later UI updates, and always enforce the same permission checks in the download endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.