Best Practice Of htaccess Rules For SEO and PWA

Useful htaccess Functions
Below are a few of the most used functions that can be implemented to your site to improve performance or manage access. If there are any which you use or feel are worth sharing please feel free to add them in the comments at the end of the post.

<IfModule mod_rewrite.c> RewriteEngine On # !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading # slashes. # If your page resides at # http://www.example.com/mypage/test1 # then use # RewriteBase /mypage/test1/ RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> ##for mobile portion RewriteCond %{QUERY_STRING} !^desktop RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|iphone|ipod|#opera mobile|palmos|webos" [NC] RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR] RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC] RewriteRule ^$ https://www.example.com/m/ [L,R=302] ##for error page portion RewriteCond %{REQUEST_URI} ^/404/$ RewriteRule ^(.*)$ /pages/errors/404.php [L] RewriteCond %{REQUEST_URI} ^/500/$ RewriteRule ^(.*)$ /pages/errors/500.php [L] # or map them to one error document: #RewriteCond %{REQUEST_URI} ^/404/$ [OR] #RewriteCond %{REQUEST_URI} ^/500/$ #RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L] RewriteCond %{HTTP_HOST} ^example\.com$ RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteRule ^(.*)$ "https\:\/\/www\.example\.com\/$1" [R=301,L]

The Rules of Non-www to www Redirect
This is a very common function for redirecting your site at the top level. Sometimes a site can be accessed at http://www.phpnasp.com/ and https://www.phpnasp.com/ which can cause duplication and site management issues.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Clean up URLs to remove file extensions

If you wanted to make your URLs look a little nicer by removing the file extension from the end of it you can use the function below. in order for this to work internally to the site, you should also ensure that all the linking within the site has the extension manually removed.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

Restrict access

To add an element of security to the .htaccess file you should add the following function. It will deny access to anyone attempting to get to the file externally to view or change it. For example, if you were to add this to your file and then attempt to access it at https://www.phpnasp.com/.htaccess you will be presented with a 403 forbidden error. This means its working!

<Files .htaccess>
order allow,deny
deny from all
</Files>

Password protect directories or pages

To do this you need to create a .htpasswd file to store the secure details of the access passwords for each user. Once this is created you would place the .htpasswd file in the appropriate location and add the function below to the .htaccess file (placed in the directory you wanted to secure) to set the security to the protected directory.

AuthType Basic
AuthName “My Protected Area”
AuthUserFile /path/to/.htpasswd
Require valid-user

To configure the .htpasswd file I recommend using a password generator to create a secure version of the password. In the example below you will see my test username ‘test’ followed by a colon and then the secure version of the password ‘testpassword’ this is how each username and password should be stored with one on each line;

test:$apr1$Onstky$7BKeCkFf6fFE/sftx5D3P/

301 redirects

To redirect an old page to a new page on your (or an external) site you can use the following function. This will set the redirect up showing a 301 server status code and will ensure the appropriate page authority is passed from the old page to the new page.

Redirect 301 /oldpage.html https://www.phpnasp.com/newpage.html

Alternatively, you can write these as:

RewriteRule ^/oldpage.html$ https://www.phpnasp.com/newpage.html [R=301,L]

URL Error handling

Sometimes people type the wrong URL in or there is an error on the site that couldn’t be resolved at the time of the server request. It is important that the generic error page is not provided to the user as sometimes these can look poor and will probably end in the user leaving the site. If possible you should create an error page or pages to handle each error. Once these are created you can add the code below into your .htaccess file substituting the location in the example for the actual location of the pages. (As a rule, you should also disallow these pages in your robots.txt file.)

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authreqd.html
ErrorDocument 403 /errors/forbid.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/serverr.html

Alternatives for other servers

Not all servers have a .htaccess file, some have a console to manage this sort of thing. For example, the Microsoft servers have a configuration management console called the IIS Manager and this is designed to manage asp.NET configurations. Over 50% of websites are configured on an Apache server so it’s quite likely that you will come across a .htaccess file sooner or later.

What is PHP Variable and How to use?

A PHP variable is like a container where we can store a lot of information. For example, a text string “Hello ICT Layer” or an integer value 100. Once you put information in a variable, you can use it again and again throughout the code, instead of repeating the original information (value). In PHP, the variable “$” must start with this symbol or it will not work. The value of a variable may change at any time in the script.

  • Variable name case sensitive. For example, $a_number and $A_number are two different variables, in the eyes of PHP.
  • Variables are written in PHP in the following way
<?php
$hello = "This is a string";
$a_number = 4;
$anotherNumber = 8;
echo $hello ."<br/>";
$total = $a_number+$anotherNumber;
echo $total;
?>
PHP and ASP
Output of PHP variable

Explanation: In the above code, I put the string inside the quotation and put it in the $ hello variable, then I output it to the browser with echo. Again I put numbers in the variables $ a_number and $ anotherNumber and then did math with it.

  • PHP is a “Loosely Typed” language so when declaring a variable without mentioning the type of the variable, PHP will automatically convert the variable to the correct data type.

Variable Naming Method:

  1. Must start with a letter or “_” (underscore).
  2. Names include alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _. May have.
  3. There should be no space in the variable name. If the name is more than one then write “_” in underscore ($ my_string) or uppercase letter ($ myString).
<?php
$feedback = "ictlayer";
$domain = "@google.com";
$feedback = $feedback.$domain;
echo $feedback;
?>

A dot (.) Joins two strings together, this is the general rule. This is called concatenate. The same work can be done as follows. You will see that in different time codes.

<?php
$feedback = "ictlayer";
$domain = "@google.com";
$feedback .= $domain;
echo $feedback;
?>

Its output will be the same as above. Meaning [email protected]

The output of the two code blocks below will be the same: PHP variable

<?php
$test = 0;
$test++;
echo $test;
?>

Output 1 will come, note that if you do not set the value of that test variable then PHP will take its value by default NULL.

<?php
$test = 0;
$test = $test+1;
echo $test;
?>

To know more about PHP variable visit our youtube channel.

Best Coding Practices For Software and Website Development

Best Coding Practices For Software and Website Development PHP and ASP

Best coding practices are a set of informal rules that the software development community has learned over time which can help improve the quality of software. Many computer programs remain in use for far longer than the original authors ever envisaged (sometimes 40 years or more), so any rules need to facilitate both initial development and subsequent maintenance and enhancement by people other than the original authors.

In the Ninety-ninety rule, Tim Cargill is credited with this explanation as to why programming projects often run late:

  • “The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.”
  • Any guidance which can address this lack of foresight is worth considering.
  • The size of a project or program has a significant effect on error rates, programmer productivity, and the amount of management needed.

Software quality

There are many attributes associated with good software:

  • Some of these can be mutually contradictory (e.g. very fast versus full error checking), and different customers and participants may have different priorities.
  • Sommerville has identified four generalized attributes which are not concerned with what a program does, but how well the program does it:
    • Maintainability
    • Dependability
    • Efficiency
    • Usability
  • Weinberg has identified four targets which a good program should meet:
    • Does a program meet its specification; “correct output for each possible input”.
    • Is the program produced on schedule (and within budget)?
    • How adaptable is the program to cope with changing requirements?
    • Is the program efficient enough for the environment in which it is used?
  • Hoare has identified seventeen objectives related to software quality, including:
    • Clear definition of purpose.
    • The simplicity of use.
    • Ruggedness (difficult to misuse, kind to errors).
    • Early availability (delivered on time when needed).
    • Reliability.
    • Extensibility in the light of experience.
    • Brevity.
    • Efficiency (fast enough for the purpose to which it is put).
    • Minimum cost to develop.
    • Conformity to any relevant standards.

Prerequisites

  • Before coding starts, it is important to ensure that all necessary prerequisites have been completed (or have at least progressed far enough to provide a solid foundation for coding).
  • If the various prerequisites are not satisfied then the software is likely to be unsatisfactory, even if it is completed.
  • From Meek & Heath: “What happens before one gets to the coding stage is often of crucial importance to the success of the project.”
  • The prerequisites outlined below cover such matters as:
    • how is development structured? (life cycle)
    • what is the software meant to do? (requirements)
    • the overall structure of the software system (architecture)
    • more detailed design of individual components (design)
    • choice of programming language(s)
  • For small simple projects involving only one person, it may be feasible to combine architecture with design and adopt a very simple life cycle.

Prerequisites

  • A software development methodology is a framework that is used to structure, plan, and control the life cycle of a software product.
  • Common methodologies include a waterfall, prototyping, iterative and incremental development, spiral development, agile software development, rapid application development, and extreme programming.
  • The waterfall model is a sequential development approach; in particular, it assumes that the requirements can be completely defined at the start of a project.
  • However, McConnell quotes three studies which indicate that, on average, requirements change by around 25% during a project.
  • The other methodologies mentioned above all attempt to reduce the impact of such requirement changes, often by some form of step-wise, incremental, or iterative approach.

Requirements

  • McConnell states: “The first prerequisite you need to fulfill before beginning construction is a clear statement of the problem the system is supposed to solve.”
  • Meek and Heath emphasize that a clear, complete, precise, and unambiguous written specification is the target to aim for.
  • Sommerville distinguishes between less detailed user requirements and more detailed system requirements.
  • He also distinguishes between functional requirements (e.g. update a record) and non-functional requirements (e.g. response time must be less than 1 second).

Architecture

  • Hoare points out: “there are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies; the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”
  • Software architecture is concerned with deciding what has to be done, and which program component is going to do it (how something is done is left to the detailed design phase, below).
  • This is particularly important when a software system contains more than one program since it effectively defines the interface between these various programs.
  • It should include some consideration of any user interfaces as well, without going into excessive detail.
  • Any non-functional system requirements (response time, reliability, maintainability, etc.) need to be considered at this stage.
  • The software architecture is also of interest to various stakeholders (sponsors, end-users, etc.) since it gives them a chance to check that their requirements can be met.

Design

  • The main purpose of design is to fill in the details which have been glossed over in the architectural design.
  • The intention is that the design should be detailed enough to provide a good guide for actual coding, including details of any particular algorithms to be used.
  • For example, at the architectural level, it may have been noted that some data has to be sorted, while at the design level it is necessary to decide which sorting algorithm is to be used.
  • As a further example, if an object-oriented approach is being used, then the details of the objects must be determined (attributes and methods).

Choice of programming language(s)

  • “No programming language is perfect.
  • There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes.
  • Understanding the problem and associated programming requirements is necessary for choosing the language best suited for the solution.”

From Meek & Heath:

  • “The essence of the art of choosing a language is to start with the problem, decide what its requirements are, and their relative importance since it will probably be impossible to satisfy them all equally well.
  • The available languages should then be measured against the list of requirements, and the most suitable (or least unsatisfactory) chosen.”
  • It is possible that different programming languages may be appropriate for different aspects of the problem.
  • If the languages or their compilers permit, it may be feasible to mix routines written in different languages within the same program.

Coding standards

This section is also really a prerequisite to coding, as McConnell points out:

  • “Establish programming conventions before you begin programming. It’s nearly impossible to change the code to match them later.”
  • There are different conventions for different programming languages, so it may be counterproductive to apply the same conventions across different languages.
  • The use of coding conventions is particularly important when a project involves more than one programmer (there have been projects with thousands of programmers).
  • It is much easier for a programmer to read code written by someone else if all code follows the same conventions.

Commenting

  • Due to time restrictions or enthusiastic programmers who want immediate results for their code, commenting of code often takes a back seat.
  • Programmers working as a team have found it better to leave comments behind since coding usually follows cycles or more than one person may work on a particular module.
  • However, some commenting can decrease the cost of knowledge transfer between developers working on the same module.
  • In the early days of computing, one commenting practice was to leave a brief description of the following:
    • Name of the module.
    • Purpose of the Module.
    • Description of the Module (In brief).
    • Original Author
    • Modifications
    • Authors who modified code with a description of why it modified.

Naming conventions

  • Use of proper naming conventions is considered good practice.
  • Sometimes programmers tend to use X1, Y1, etc. as variables and forget to replace them with meaningful ones, causing confusion.
  • In order to prevent this waste of time, it is usually considered the good practice to use descriptive names in the code since we deal with real data.
  • Example: A variable for taking in weight as a parameter for a truck can be named TrkWeight or TruckWeightKilograms, with TruckWeightKilograms being the more preferable one, since it is instantly recognizable.

Keep the code simple

  • The code that a programmer writes should be simple.
  • A complicated logic for achieving a simple thing should be kept to a minimum since the code might be modified by another programmer in the future.
  • The logic one programmer implemented may not make perfect sense to another.
  • So, always keep the code as simple as possible.

Portability

  • Program code should never ever contain “hard-coded” (literal) values referring to environmental parameters, such as absolute file paths, file names, usernames, hostnames, IP addresses, URLs, UDP/TCP ports.
  • Otherwise, the application will not run on a host that has a different design than anticipated.
  • A careful programmer can parametrize such variables and configure them for the hosting environment outside of the application proper (for example in property files, on an application server, or even in a database).
  • Remember the mantra of a “single point of a definition” (SPOD).
  • As an extension, resources such as XML files should also contain variables rather than literal values, otherwise, the application will not be portable to another environment without editing the XML files.
  • For example, with J2EE applications running in an application server, such environmental parameters can be defined in the scope of the JVM and the application should get the values from there.

Code development: Code building, Testing & Debugging the code and correcting errors

Code building

  1. A best practice for building code involves daily builds and testing, or better still continuous integration, or even continuous delivery.

Testing

  1. Testing is an integral part of software development that needs to be planned.
  2. It is also important that testing is done proactively; meaning that test cases are planned before coding starts, and test cases are developed while the application is being designed and coded.

Debugging the code and correcting errors

  1. Programmers tend to write the complete code and then begin debugging and checking for errors.
  2. Though this approach can save time on smaller projects, bigger and complex ones tend to have too many variables and functions that need attention.
  3. Therefore, it is good to debug every module once you are done and not the entire program.
  4. This saves time in the long run so that one does not end up wasting a lot of time on figuring out what is wrong.
  5. Unit tests for individual modules, and/or functional tests for web services and web applications, can help with this.
Best Coding Practices Guidelines in brief (Summary) A general overview of all of the above:
  • Know what the code block must perform.
  • Indicate a brief description of what a variable is for (the reference to commenting).
  • Correct errors as they occur.
  • Keep your code simple.
  • Maintain naming conventions which are uniform throughout.
  • Deployment is the final stage of releasing an application for users.

CMS Layer: Most Powerful PHP CMS Using CodeIgniter

CMS Layer The Most Developer Friendly CMS PHP and ASP

CMS Layer

CMS Layer The Most Developer Friendly CMS

The most flexible platform & programmer-friendly content management system (CMS Layer) all around the world! Build using powerful PHP framework CodeIgniter.

CMS Layer has built-in 100% Optimize SEO Comparable.

CMS Layer Plugin and Extensions are Page, Post, Product, Service, Portfolio, Forum, Package, Video, Slideshow, Classified, Download, Listing, Advertisement, Communities, Payment Gateway, ADP Template and AMP Theme.

Design Timeline using CSS and Jquery

Timeline design is the current web trend that visualizes the data in an interesting way. Today I want to discuss about how to design a timeline in a simple way with JSON data feed , that using CSS pseudo elements such as:before and :after. Pseudo elements are used to apply special effects to selectors. This post is a combination of my previous post, please take a quick look at this demo and try demo script with your WAMP server.

csstimeline PHP and ASP

The ::before selector inserts content before the content of the selected element(s).

CSS Code

#updates
{
position:relative;
padding:20px 0px 20px 0px;
}
#updates:before
{
content: ”;
position: absolute;
top: 0px;
bottom: 0px;
width: 5px;
background: #999999 ;
}
.timeline_square
{
width:12px;
height:12px;
display:block;
position: absolute;
left:-4px;
border-top:3px solid #e8eaed;
border-bottom:3px solid #e8eaed;
margin-top:-8px;
}

Status Update HTML Code
Check my previous postStatus Message Design with CSS
<div class=”stbody”>
<span class=”timeline_square color1″></span>
<div class=”stimg”><img src=”profile.jpg” /></div>
<div class=”sttext”>
<span class=”stdelete” title=”Delete”>X</span>
<b>Srinivas Tamada</b><br/>
9lessons Programming Blog
<div class=”sttime”>10 seconds aga.</div>
<div class=”stexpand”>
//Youtube IFrame Code
</div>
</div></div>
users.json
This contains Users data feed, you can generate this using PHP code.
{
Messages“:[
{
“user”:”Srinivas”,
“message”:”9lessons Programming Blog http://www.9lessons.info . “,
“avatar”:”srinivas.jpg”,
“embed”:””,
“time”:”16 seconds ago”
},
{
“user”:”Arun”,
“message”:”Everything is possible. “,
“avatar”:”arun.jpg”,
“embed”:””,
“time”:”18 seconds ago”
},
{
“user”:”Joker”,
“message”:”If you are good at something, never do it for free”,
“avatar”:”joker.png”,
“embed”:”<iframe height=’315′ src=’//www.youtube.com/embed/FalHdi2DkEg’ width=’560′></iframe>”,
“time”:”28 seconds ago”
},
…………..
…………..
…………..
]
}
index.html
Contains Jquery and JavaScript code, here $.getJSON parse the JSON data object.
<script src=”js/jquery.min.js”></script>
<script src=”js/jquery.linkify.min.js”></script>
<script src=”js/jquery.livequery.js”></script>
<script>
$(document).ready(function()
{//Formatting the text that contains URLs (text to link)
$(“.sttext”).livequery(function ()
{
$(this).linkify({ target: “_blank”});
});

//Parsing JSON object.
$.getJSON(“users.json”, function(data)
{
var totalCount=5;
var jsondata=”;
$.each(data.Messages, function(i, M)
{
//Generating random numbers for different dot colors
var num = Math.ceil(Math.random() * totalCount );
jsondata +='<div class=”stbody”>’
+'<span class=”timeline_square color’+num+'”></span>’
+'<div class=”stimg”><img src=”‘+M.avatar+'” /></div>’
+'<div class=”sttext”><span class=”stdelete”>X</span>’
+'<b>’+M.user +'</b><br/>’
+M.message+'<div class=”sttime”>’+M.time
+'</div><div class=”stexpand”>’+M.embed+'</div></div></div>’;
});
$(jsondata).appendTo(“#updates”);
});

//Delete record
$(‘body’).on(“click”,”.stdelete”,function()
{
var A=$(this).parent().parent();
A.addClass(“effectHinge”);
A.delay(500).fadeOut(“slow”,function(){
$(this).remove();
});
});});
</script>
//HTML Code
<div id=”updates”></div>

Deleting record animation effect, please check my previous post CSS3 Animation Effects with Keyframes

CSS code
Random colors for timeline square points.

.color1
{
background-color:#f37160
}
.color2
{
background-color:#50b848
}
.color3
{
background-color:#f39c12
}
.color4
{
background-color:#0073b7
}
.color5
{
background-color:#00acd6
}
.effectHinge
{
animation:hinge 1s;
-webkit-animation:hinge 1s; /* Safari and Chrome */
}