简体   繁体   中英

How to validate referrer url using Javascript and PHP

I want to reload my page whenever the referrer URL is equal to a link but I would love to use like operator, I don't want to use equal to since the level id will not always be the same. Please help me with the correct code.

<?php
    echo '<script type="text/javascript"> 
    if (document.referrer = https://www.maocular.org/membership-account/membership-confirmation/?level=10)  { 
       location.reload(forceGet);
    }
    </script>';
?>

you can use match function of String(javascript) which takes String or Regex as input so as the name suggests match does a check with the string passed to it,if a match is found then match function returns an Array, if a match is not found then match returns null.

Solution for your code:

if(document.referer.match('https://www.maocular.org/membership-account/membership-confirmation/?level=')) {
   location.reload(forceGet);
  }

Explanation: so as document.referrer returns a string we can make use of match function of String Class which exists in Javascript, and inside match we have passed a direct string instead of regex as there's only match required, in case you need more than one match use regex (|) and so on.

Refer this doc for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

<?php
   echo '<script type="text/javascript"> 
   if (document.referrer == https://www.maocular.org/membershipaccount/membership-confirmation/?level=10) 
   { 
        location.reload(forceGet);
     }
    </script>';
?>

In your condition, change to == from =

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM