-1

I would like to retrieve the original URL from a shortened link before clicking on it and visiting the destination.

I have this external link https://example.com/api.php?redirect=XXXXXXX which redirect to https://new.com . How can I get the original link https://new.com using PHP or Javascript.

Emma Grove
  • 148
  • 2
  • 11
  • I just have to ask... How is the `https://example.com/api.php?redirect=xxxxx` a shortened link to `https://new.com`? Also when asking a question, you should specify a specific language, not add alternatives. Just tag the language that you prefer the solution in. I also don't see how `html` is relevant here. – M. Eriksson Nov 13 '20 at 14:49
  • You also need to do some research and make some attempts yourself first. If you get stuck on something _specific_ with your code along the way, come back, show us what you've tried, the expected result and what results you're getting. – M. Eriksson Nov 13 '20 at 14:52

2 Answers2

-1

const extractParams = (url) =>{
    const search = url.split("?")[1];
    return Object.fromEntries(
        search.split("&").map(param => param.split("="))
    )
}

window.addEventListener("load", ()=>{
    // select all a tag containg word redirect in href attr
    const links = document.querySelectorAll('a[href*="redirect"]')
    links.forEach(el => {
       el.addEventListener("click", (e) =>{
       /// remove line below in your solution if you need to links works correctly
            e.preventDefault();
            const url = e.target.href;
            const params = extractParams(url);
            //belove you have access to redirect and any otter url params
            console.log(params.redirect);
       })
    })
})
<a href="https://example.com/api.php?redirect=https://new.com">New</a>
<a href="https://example.com/api.php?redirect=https://ben.com">Ben</a>
<a href="https://example.com/api.php?redirect=https://den.com">Den</a>
Robert
  • 2,538
  • 1
  • 9
  • 17
-2

Use $_SERVER['HTTP_REFERER'].

It returns the address of the page (if any) which referred the user agent to the current page.

For more details, refer : https://www.w3schools.com/php/php_superglobals_server.asp

Zeta
  • 46
  • 7
  • Not sure how this would answer their question in any way? The question was: _"I would like to retrieve the original URL from a shortened link before clicking on it and visiting the destination."_ This would just give them the URL the request came from. Not always though, since `HTTP_REFERER` is known not always being set and can't be trusted since clients can override it. – M. Eriksson Nov 13 '20 at 14:53