Hi,

I was hoping for some feedback regarding the way to code links in PHP so that there is a Global solution in effect. For example when you update the location of a file or link then you change one and it changes the whole site:

This is what I have at the moment:

I have a config.php file located in /includes:

/* Live Site */
<?php $url = 'http://www.example.com/'; ?>
/* Local Developing site */
/*<?php $url = 'http://mytestsite/'; ?>*/

Then my links will look like this:

<a href="<?php echo $url; ?>">About us</a>

Is this the way its is normally done or is there a better way?

    I can tell you that's exactly how I do it, except for I don't have a separate url for local development, I add an entry to hosts to direct the domain I'm working on to my local apache. I do this because you wouldn't believe how many times I thought things were working because they linked to local/page (like css or js) but for other people they don't have those files cached from local/page so it wasn't working! So now I always use the final address and just create a catch for it when I need to test it locally. http://en.wikipedia.org/wiki/Hosts_(file) for more info.

      I would say that's a fairly typical approach in general.

      I might define() a constant, perhaps in a config file (or class?) that is used by each script.

      config.php:

      <?php
      define('BASE_URL', 'http://example.com/');
      

      index.php:

      <?php
      require 'config.php';
      ?>
      <html>etc....
      <a href='<?php echo BASE_URL; ?>sub_dir/page.php'>Some Page</a>
      

      Another level of abstraction would be to create a function in your config file that would take one or more arguments, and build the URL for you, or even build the entire HTML tag with all its attributes.

        @

        Thanks for your great reply, as im new to PHP I have only just started using constants and I am liking the flexibility with them. The great thing I believe is you can write in plain English as you used in your example; 'BASE_URL'

          NogDog;11000696 wrote:

          or even build the entire HTML tag with all its attributes.

          Sorry, are you able to elaborate on your quote above?

            Sure something like this maybe:

            <?php 
            
            function anchor($target,$text,$options) { 
               // Prepend base url if not full URL 
               if( !filter_var($target,FILTER_VALIDATE_URL) ) $target = BASE_URL . $target; 
            
               // Build the link 
               $out = '<a href="'.$target.'"'; 
            
               if( isset($options['id']) ) $out .= ' id="'.$options['id'].'"'; 
               if( isset($options['class']) ) $out .= ' class="'.$options['class'].'"'; 
               if( isset($options['target']) ) $out .= ' target="'.$options['target'].'"'; 
               if( isset($options['event']) ) $out .= ' '.$options['event']; 
            
               $out .= '>'.$text.'</a>'; 
            
               return $out; 
            } 
            
            define('BASE_URL','http://www.example.com');
            echo anchor('','Home',array('class'=>'navigation','event'=>'onclick="alert(\'You clicked the Home link!\')"'));

            This is just an example of what I think he meant, of course I welcome being corrected.

              Yep, something like that. You could even break it down more if you wanted, though we might be approaching some sort of point of diminishing returns at this point -- it all depends on the size/scope of your application and how much you might re-use these functions. I probably would not do this, but some people seem to like it.

              <?php
              define('DOMAIN', 'www.example.com');
              
              function buildUrl($domain, $path, Array $params=null, $target=null)
              {
              	$url = 'http://' . $domain . '/' . ltrim($path, '/');
              	if( ! empty($params)) {
              		$url .= '?';
              		foreach($params as $key => $value) {
              			$url .= urlencode($key) . '=' . urlencode($value) . '&';
              		}
              		$url = rtrim($url, '&');
              	}
              	if( ! empty($target)) {
              		$url .= '#' . urlencode($target);
              	}
              	return $url;
              }
              
              function htmlATag($url, $text, Array $attributes=null)
              {
              	$html = '<a href="' . $url . '"';
              	if( ! empty($attributes)) {
              		foreach($attributes as $key => $value) {
              			$html .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
              		}
              	}
              	$html .= '>' . htmlspecialchars($text) . '</a>';
              	return $html;
              }
              ?>
              <!DOCTYPE html>
              <head><title>Test</title></head>
              <body>
              <p><?php
              echo htmlATag(
              	buildUrl(
              		DOMAIN,
              		'/foo/bar.php',
              		array(
              			'Hello' => 'World',
              			'this' => 'is a test'),
              		'some_id'
              	),
              	'The link text',
              	array(
              		'id' => 'an_id',
              		'class' => 'a_class'
              	)
              );
              ?></p>
              </body>
              </html>
              

              Output:

              <!DOCTYPE html>
              <head><title>Test</title></head>
              <body>
              <p><a href="http://example.com/foo/bar.php?Hello=World&this=is+a+test#some_id" id="an_id" class="a_class">The link text</a></p>
              </body>
              </html>
              

                I usually define a constant in this sort of situation.

                  For the base URL, wouldn't you just use the server name variable?

                  <?php
                  echo $_SERVER['SERVER_NAME'];
                  ?>
                  
                    spufi;11000799 wrote:

                    For the base URL, wouldn't you just use the server name variable?

                    <?php
                    echo $_SERVER['SERVER_NAME'];
                    ?>
                    

                    You probably could, though I'm not sure how it handles sub-domains (e.g.: did the user include the "www."?), and if the OP cares in this case. 🙂

                      Derokorian;11000695 wrote:

                      I can tell you that's exactly how I do it, except for I don't have a separate url for local development, I add an entry to hosts to direct the domain I'm working on to my local apache. I do this because you wouldn't believe how many times I thought things were working because they linked to local/page (like css or js) but for other people they don't have those files cached from local/page so it wasn't working! So now I always use the final address and just create a catch for it when I need to test it locally. http://en.wikipedia.org/wiki/Hosts_(file) for more info.

                      Hi Dek,

                      I am very famaliar with the setup of the Hosts file as you suggested. Are you able to give me an example of how you set yours up without needing to change the URL in the config file?

                      What happens when you want to view the site at the live address also?

                        Well, I simply add a line like this:

                        127.0.0.1 example.com

                        And requests for example.com get mapped to the loop-back address. Then I just remove this line to see the actual example.com.

                          spufi;11000799 wrote:

                          For the base URL, wouldn't you just use the server name variable?

                          <?php
                          echo $_SERVER['SERVER_NAME'];
                          ?>
                          

                          I believe I found a suitable solution. I also tested it on subdomains and seems to work fine. Do any of you think there is scope for me solution falling over?

                          Config file:

                          <?php $url = 'http://' .$_SERVER['SERVER_NAME'].'/'; ?>

                          Links:

                          <a class="MyClass" href="<?php echo $url; ?>webpage">My Page</a>

                          The only issue I have with my solution though is that I will have a cause to use SSL on some web pages and wanted to figure out how I could make this possible dynamically form the config file if thats a way to do it?

                            if(!empty($_SERVER['HTTPS']) and $_SERVER['HTTPS'] != 'off') {
                              // current request used HTTPS
                            }
                            

                            The test for 'off' is only really needed if running on Windows IIS ISAPI

                              Write a Reply...