4

I'm trying to direct a php authorization script to act if the page that referred to it belongs to a certain category (free).

Is there something other than <?php wp_get_referer() ?> that will return more than the url? I basically need to get the id of the referrer.

3
  • 2
    I wouldn't recommend you use the page referrer in any security or authorization script, as it is incredibly easy to fake ( do not track mode may remove the referrer too ). Instead a POST or GET variable would be better
    – Tom J Nowell
    Mar 12, 2014 at 14:24
  • Not tested, but it looks like <?php $postid = url_to_postid( $url ); ?> will help perform this task. $refererr = wp_get_referer() $id = url_to_postid( $referrer ); ?>
    – psorensen
    Mar 12, 2014 at 14:41
  • 1
    I would also recommend that you look into nonces, if you're going from page A to page B, nonces will guarantee that people on B came from A, referer or no referrer, and prevent a whole class of attacks from happening
    – Tom J Nowell
    Mar 12, 2014 at 16:46

1 Answer 1

7

url_to_postid(wp_get_referer()) will give you the ID of the referring page/post if you were referred from a page or a post. It won't work if referred from some other types of pages, like archives.

You will then need to retrieve the categories for the ID to see if they match.

I would strongly consider passing a parameter with the request though. You should already have the post ID and possibly the post data on the referring page and won't have to make separate queries to grab it.

You can use a nonce to help prevent abuse of the parameter-- that is, to prevent someone from just typing ?status=free into the URL.

You mention sessions in a comment. I have used sessions successfully in WordPress and with little trouble. Be aware that a lot of people complain about sessions with WordPress.

See:

http://codex.wordpress.org/Function_Reference/url_to_postid

4
  • Thank you! Can you please elaborate on passing a parameter with the request. All links in question are coming from the same page template. In that template, how would I set a $_POST or $_GET parameter without just adding ?status=free (I did this using add_query_arg to the link only to find that just adding ?status=free was too easily replicable.)
    – psorensen
    Mar 12, 2014 at 14:53
  • I will explore PHP Sessions
    – psorensen
    Mar 12, 2014 at 14:55
  • 1
    @PeteSorensen : see the edit
    – s_ha_dum
    Mar 12, 2014 at 15:13
  • For anyone that found this useful and want to get the referrer post title - get_the_title( url_to_postid(wp_get_referer())) Aug 17, 2017 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.