We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 37914
    • 89 Posts
    I wrote this little snippet to redirect specific pages to https:// when they are set trough a TV.
    And it also redirects back to http:// if the page isn't supposed to be secure.
    I have this snippet in the head of every page.

    I don't know much about PHP and MODX caching etc, so I'm curious if this is the best way to do it.
    If it can become better in terms of performance, then I really would like to know.

    I also post this here so everyone can use it.

    <?php
    //Snippet: redirectSSL
    //TV: redirectSSL with options Yes==1||No==0
    
    $toggleSsl = $modx->resource->getTVValue('redirectSSL');
    //echo $toggleSsl;
    if ($toggleSsl == "1") {
    	if($_SERVER["HTTPS"] != "on")
    	{
        	header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
        	exit();
    	}
    } else {
    	if( isset($_SERVER['HTTPS'] ) ) {
    		header("Location: http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
        	exit();
    	};
    };
      • 3749
      • 24,544 Posts
      It looks good to me. smiley

      You might think about renaming the $toggle Ssl variable to something like $forceSsl, since you're not really toggling anything (a toggle would turn it on if it's off and off if it's on).

      Since it runs on every page load and has to be called uncached, you could speed it up slightly by getting the value of the TV this way:

      $resourceId = $modx->resource->get('id');
      $tvId = 12; /* Set to the ID of the TV */
       
      /* Get the value of the modTemplateVarResource */
      $query = $modx->newQuery('modTemplateVarResource', array(
          'contentid' => $resourceId,
          'tmplvarid' => $tvId,
      ));
      $query->select('value');
      $toggleSsl = $modx->getValue($query->prepare());
       
      /* The rest of your code here */
      


      Doing it this way avoids MODX having to get the TV object itself and avoids MODX calling the render method on the TV, since you don't need it rendered. This code assumes that the TV doesn't have a default value (it shouldn't) and you never use @INHERIT with it. If you want a default value, put it in the snippet at the end of the code above:

      if (&toggleSsl === false) {
         $toggleSsl = '0';  /* or $toggleSsl = '1' */
      } 
      

        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting