Differentiate between localhost and live


#1

When writing PHP files locally there maybe problems where numerous paths and local scripts, etc are different than the ONLINE version :frowning:

Files with the same file name and different content can create havoc when uploading files to the server!!!

To overcome this problem I have the following defined in the master file:

<?php 
declare(strict_types=1);

declared('LOCALHOST') 
  ||  
declare('LOCALHOST', 'localhost'===$_SERVER['SERVER_NAME'); 

// usage:
// SET DEFAULT DEBUGGING
ini_set( 'display_errors', 'FALSE' );
if( LOCALHOST ):
  ini_set( 'display_errors', 'TRUE' );
endif;

// 
//

if( LOCALHOST ):
  // NO NEED TO DISPLAY Google analytics, Adverts, etc
else:
  // PHP HereDoc 
  // BEWARE: ONLY CARRIAGE-RETURN FOLLOWS ____TMP 
 $tmp = <<< ____TMP
      <script type="text/javascript">
          (function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,"script","' .$analytics .'","ga");
          ga("create", "UA-XXXXXXXX-1", "auto");
          ga("send", "pageview");
        </script>  
____TMP;
// BEWARE: ONLY ; FOLLOWS ____TMP
echo $tmp; // BETTER IF SCRIPT STORED IN AN INCLUDED FILE

// MORE INCLUDES GO HERE

endif;

Edit:
Spelling not my forty :frowning:


How to write proper PHP
#2

Really? Why? There is no reason you should have path problems if you code properly and set up a proper local dev. If the local scripts are different then they should be the updated versions of the ones online. If you did proper local testing there should be no problems overwriting the ones online. That is just the basics of updating an application. The code looks rather hackish IMO.

The error display setting should be set in the Php ini, not the code. Pretty redundant to put it in every application when you can just set it once in the ini. The only place I have found it useful to dynamically determine localhost is in the DB connection. Doing it for analytics is just a hack since you can set the analytics filter to not track localhost or you can add a bit of JS to the analytics code to not track localhost or you can enclose the code in a JS Check for localhost.

If you are having havoc updating an application I have to question your methods.

Example

<script>
    var host = window.location.hostname;
    if(host != "localhost") {
	// your google analytics code goes here
    }
</script>

#3

@benanamen

I have a local dev setup and it is a mirror image of the ONLINE version.
These are the main differences that require toggling:

  1. $_SERVER['SERVER_NAME']
  2. $_SERVER['DOCUMENT_ROOT']
  3. Database uName and pWord

The supplied PHP script defines LOCALHOST as a global CONST. Personally I think this is far quicker than the overhead involved in calling and processing a function. I fail to see why the “code looks rather hackish”.

An alternative testing method which I also use is "Apache2 .htaccess SetEnv" variable which is not as flexible and requires testing a PHP $_SERVER[‘parameter’]. Far easier to test once and to define a global PHP CONST.

The simple example was to show how to test for the LOCALHOST PHP CONST and toggle platform changes. I agree about php.ini settings and also set the database parameters using the LOCALHOST I prefer to also use the same constnat to include Google’s JavaScripts rather than modify the supplied JavaScript.

<script>
    var host = window.location.hostname;
    if(host != "localhost") {
      // your google analytics code goes here
    }
</script>

It appears your supplied JavaScript would be OK and rather verbose to be switching from PHP to JavaScript each time the environment required toggling. Far simpler as mentioned to set the PHP CONST only once.

Also and unfortunately many of my sites use the https://AmpProject.org FrameWork and only their supplied JavaScript may be used. Trying to use your script would invoke:

  1. AmpProject warnings
  2. fail validation
  3. remove the Free Google CDN Cached web-page content, images, etc
  4. remove Google Mobile Search preference

The havoc occurred when first learning to use PHP to write HTML pages. My methods have improved and still enjoy learning… especially because technology is changing daily!


#4

To give a proper response I would like to review your project code. What is the URL to your repo? (You are using version control right?)

Glad to hear you are continuing to learn and improve.


#5

Latest project is https://johns-jokes.cf

I do not use version control.


#6

That should be your first task today. Learn how to use it. Admittedly, it took me far too many years to “discover” version control. What a eureka moment when I did though. Don’t be me. Learn about GIT and Github/Bitbucket. There are several free Windows GUI’s for GIT so you dont have to learn all the commands. It will forever change your coding journey.
https://git-scm.com/

The project link is not of any use. I need to read the code.


#7

What’s Windows? :slight_smile:

I use Linux and looking for a graphical GitHub solution because I seldom use GitHub and have difficulty in trying to remember the commands.

The PHP FrameWork used is still Pre-Alpha (expect Alpha version in September)… which is the reason for the test site. I would especially like to be able to become more familiar with GitHUb so I can contribute towards the GitHub project.

I fail to see why it is necessary to *read the code", if the project link does what it is supposed to do then surely that is sufficient?

If there are any bugs or you are able to create errors then the error_log file-size is shown on the opening screen and I would be grateful for the steps leading towards the problem.


PHP MySQL novice to ninja 6th edition - databasetable.php
#8

Awe cmon John, you haven’t even looked. There are several.

Speechless, just speechless.:banghead:


#11

I haven’t forgotten :slight_smile:

Here we go - a brand new GitHub Repository:


#12

Hey John,
Glad to see you got hooked up with GitHub. Its been a little bit since this thread. Were are you at now? Any problems to resolve?

If we are going to discuss the repo code I would ask that you give me a little background of it and what you were wanting to accomplish with it. I am rather confused between the description and what the demo appears to be doing.


#13

@benanamen, many thanks for taking the time to visit and comment on the GitHub Repository.


Glad to see you got hooked up with GitHub

I still find Github confusing because it seems to add an additional complexity layer. I usually develop locally and use the server to keep online backups which are quite easy to maintain by renaming/deleting folders.


Were are you at now?

The source code and Demo URL are still current. The URL was going spare because of interface problems trying to register for with a free web hosting company. I tried and concluded my existing web host is both less expesnive and superior.


Any problems to resolve?

I have problems due to the site appearing to hang when multiple URLs are requested. The page eventually refreshes after the last URL has been interrogated. To solve this delay problem I introduced a New SitePoint Topic and also a new Demo Web Site. Maybe I should replace the existing GitHub Repository with the new AJAX version.


If we are going to discuss the repo code I would ask that you give me a little background of it and what you were wanting to accomplish with it. I am rather confused between the description and what the demo appears to be doing.

The Online Utility was devised to simplify installing LetsEncrypt.org. It was necessary to test and ensure all .htaccess redirections were working correctly. The GitHUb Repository now has brief explanatory details.


I would be grateful for your comments and improvements on either site.


It is interesting to note the differences on how major web sites tackle htaccess redirection. Some large sites even have some URLs timing out or not even reached!

How do your sites handle redirection?


#14

Once you learn how to use it, it will forever change your coding life. Learning a Git GUI will be much easier than starting with the command line.

The title “Template-to-render-web-page” threw me off. I never would have thought that’s what it was for from the name.


#15

Depends on your personal background and the GUI you use. For me - as i work mostly on CLI or in code - the native git GUI is a scrapyard (except for some read-only features) and the 5 every-day git commands are way more convenient. But PHPStorm has a few tweaks and a good workflow, if already in use. The GitHub app is also OK imho.


#16

Yes the Template was copied from another project and I forgot to change the title.

The Template Site consists of a single index.php file and an included Class.php.

index.php

<?php 
declare(strict_types=1);
error_reporting(-1);
ini_set('display_errors', '1');

define('LOCALHOST', 'localhost'===$_SERVER['SERVER_NAME']);

  require 'incs/Class_Ttn.php';
  $jb = new Class_Ttn;

  $problemByRef=FALSE;
  $mode = $jb->getMode($problemByRef);

  $tmp     = 'https://this-is-a-test-to-see-if-it-works.tk/ajax/';
  $aTitles = [
    'John_Betong\'s URL Tester',
    'Version: 005.01',
  ];

# RENDER STUFF
  $jb->renderForm($aTitles, $mode, $aHttps=['','']);

 $jb->renderFooter(); # close </body.</html>

  require 'js/_ajax.php';

  if(LOCALHOST):
    # DO NOT INCLUDE Google Analytics
  else:   
    $jb->renderGoogle();
  endif;  

echo "\n\n</body></html>";