I need a help here, There's an error every time I add a link in my php file.
Example:

<php
$link = "twitter.com";
echo "<a href = '".$link."'> link </a>";
?>

on click, the address would be change on "http://localhost/project/twitter.com" whch is supposed to be "twitter.com"
I've tried placing

<?php
$link = "twitter.com";
echo "<a href = '../../".$link."'> link </a>";
?>

but still it doesn't work. $link is stored in the database.
I'm new here. Please help me.

Dani AI

Generated

Quick summary and a couple of checks: the browser treats twitter.com as a relative path, so the click ends up under http://localhost/.../twitter.com. As pointed out, a full URL scheme is required for an external link; ’s suggestion to include www helps only if a scheme is present. Also double-check the PHP open tag in the original post (it should be <?php), and make sure the value coming from the database is the raw URL (not already an <a> tag).

A robust pattern is: 1) normalize the value you read from the DB, 2) validate it, and 3) output an escaped anchor. Example implementation:

function build_external_link($rawUrl, $label = null) {
    $url = trim(strip_tags($rawUrl));
    if (!parse_url($url, PHP_URL_SCHEME)) {
        $url = 'http://' . $url;
    }
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        return htmlspecialchars($label ?: $rawUrl, ENT_QUOTES, 'UTF-8');
    }
    $safeUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
    $text = htmlspecialchars($label ?: $url, ENT_QUOTES, 'UTF-8');
    return sprintf('<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>', $safeUrl, $text);
}

Quick debugging checklist: view page source to see the rendered href; inspect the raw DB value to ensure it has no HTML and no leading/trailing whitespace; avoid storing full anchor tags in the DB (store only the URL); and use strip_tags, trim, parse_url, and filter_var to normalize/validate. For details on the PHP functions used, see parse_url, filter_var, and htmlspecialchars.

Recommended Answers

All 3 Replies

try like this

$link = "www.twitter.com";
<a href ="<?=$link?>"> link </a>

That happens because if you don't put a protocol in a link it will be interpreted as a subdirectory so if you want to make an external link you should put

etc so in your case it would be

$link = "http://www.twitter.com";
<a href ="<?=$link?>"> link </a>
Member Avatar for Member #334542

You can try these kind of things without www. or http:// in your browser but not with the codes, code strictly first refers to your local. So that only it retrieves your php localhost and tried from there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.