How to generate expiring URL?

Ok I came up with this

add_action( 'wp_loaded', 'my_create_questionnaire_link');
function my_create_questionnaire_link(){

  // this check is for demo, if you go to http://yoursite.demo/?create-my-link, you will get your unique url added to your content
  if( isset( $_GET['create-my-link'] ) ){

    // This filter is for demo purpose
    // You might want to create a button or a special page to generate your
    // unique URL
    add_filter( 'the_content', function( $content ){

      // This is the relevant part
      // This code will create a unique link containing valid period and a nonce

      $valid_period = 60 * 10; // 10 minutes
      $expiry = current_time( 'timestamp', 1 ) + $valid_period; // current_time( 'timestamp' ) for your blog local timestamp
      $url = site_url( '/path/to/your/portfolio/page' );
      $url = add_query_arg( 'valid', $expiry, $url ); // Adding the timestamp to the url with the "valid" arg
      $nonce_url = wp_nonce_url( $url, 'questionnaire_link_uid_' . $expiry, 'questionnaire' );  // Adding our nonce to the url with a unique id made from the expiry timestamp

      // End of relevant part
      // now here I return my nounce to the content of the post for demo purposed
      // You would use this code when a button is pressed or when a special page is visited

      $content .= $nonce_url;

      return $content;
    } );
  }

}

This is where you would check for the validity of the unique URL

add_action( 'template_redirect', 'my_url_check' );
function my_url_check(){

  if( isset( $_GET['questionnaire'] )){

    // if the nonce fails, redirect to homepage
    if( ! wp_verify_nonce( $_GET['questionnaire'], 'questionnaire_link_uid_' . $_GET['valid'] ) ){
      wp_safe_redirect( site_url() );
      exit;
  }

    // if timestamp is not valid, redirect to homepage
    if( $_GET['valid'] < current_time( 'timestamp', 1) ){
      wp_safe_redirect( site_url() );
      exit;
    }

    // Show your content as normal if all verification passes.
  }
}

Leave a Comment