Category Archives: HTML & CSS

30 Top PHP Tips and Tricks & Coding Tutorials

php-tricks-tips-coding-tutorials

Tip #1

<?php
$todayTimestamp = time();
/* Don’t Use.*/
$nextDay = $todayTimestamp + 86400;

/* Do instead.*/
$nextDay = strtotime(‘+1 day’, $todayTimestamp);
?>
The first one will not work exactly if you move into or out of daylight savings time.

An extra problem is that the second example is more readable, specially if you add like 2 weeks and 2 days (‘+2 weeks 2 days’)
Use date_default_timezone_set() function before, if you doing calculation to a specific region.

 

 

Tip #2

Don’t use regexp to filter/match an email or an URL.There are already built-in filters in PHP for that.

<?php
$email = filter_var(‘scriptarticle@gmail.com’, FILTER_VALIDATE_EMAIL);
?>
See documentation on filter_var()

 

 

Tip #3

echo gives you more than one string as parameter.

Using some parameters is going to more faster than blending some variables into a parameter.

<?php
$a = ‘Hello’;
$b = ‘Scriptarticle’;
echo ‘Say ‘ .$a. ‘ to ‘ .$b;

//Below will faster
echo ‘Say ‘, $a ,’ to ‘, $b;
?>

 

 

Tip #4

Use isset() instead of strlen() function

<?php
$str = “434e5”;

if (!isset($str{5})) {
echo ‘String must be at least 5 chars<br />’;
}

if (strlen($str) < 5){
echo ‘String must be at least 5 chars’;
}
?>
isset() needs little more time than strlen() because isset() is a language construct.

When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $str[5] is the sixth character in $str)

 

 

Tip #5

Avoid the use of printf function

Unlike print and echo, printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables.

<?php
echo ‘Result:’, $result;
// is better than
printf( “Result.%s”, $result );
?>

 

 

Tip #6

Avoid large string concatenation

When do concatenation string, avoid uniting with large size string. It can obstruct code execution that can display faster.

<?php

//Large string concatenation
$title = ‘this is’;
$body  = ‘..a very large blog..’;
echo “Subject.$title\n\n$body”;

//Avoid large string concatenation
$title = ‘this is’;
$body  = ‘..a very large blog..’;
echo “Subject.$title\n\n”;
echo $body;

?>

 

 

Tip #7

Use boolean data type

PHP is allowing writing Boolean data type with uppercase or lowercase.
But, writing with lowercase is faster than uppercase. When found a constant, PHP do lookup hash constant name.

<?php

if ($var = TRUE) {

}

//this is more faster
if ($var = true) {

}

?>
Boolean value 1 and 0 are faster than true and false.

 

 

Tip #8

Avoid space in your code

The main purpose of code optimization is to get faster code execution, because PHP codes going to execute every time they are requested.

Avoid the use of many spaces ( ) is a good thing. Every space is 1 byte and every tab (\t) is 1 byte. When you’re using four spaces, you’ve been use 4 bytes. It will more effective if you’re using a tab (\t).

 

 

Tip #9

Print Output

PHP is giving some sting functions to printing output into browser and we are often using print() and echo() function.

Print() function behavior like the other function in common and having return value integer 1. Thus, print() can used as part of expression which more complex. Meanwhile, echo() is able to accept more than one parameters all at once, and does not having return value.

<?php
print() ‘string 1’;
echo ‘string 1’;
// using some parameters
echo ‘string 1’, “string 2”, ‘…’;
?>
echo() function string will execution more faster than print(). This differentiate caused by will return status (integer) which expose what process has done or not.

 

 

Tip #10

File Access Optimization

When you need to include a file, recheck file content that will be use. If file not contains PHP codes, use readfile() function to increase performance.
Because files that including with readfile() does not parsing by PHP. It will be different with construction language include() and require(), and files will be evaluated before.

Other side is, readfile() increases attack risk. This risk will be happen when accessing file from URL.
Solution for the attack risk is by using File Handling.

 

 

Tip #11

Use ternary operators instead of if, else

Ternary operators can be very helpful and clean up the code, but don’t over complicate them otherwise your code might become inundated with large amounts of complex ridiculousness.

<?php
$name = (!empty($_GET[‘name’])? $_GET[‘name’] .’Scriptarticle’);
?>

 

 

Tip #12

Class Auto loading

If you have a very large number of classes that could potentially use within one or many sections of your code, you could include all of them within a common header file, or only include the ones that you know that you’re going to use on that page. However, you then need to remember to include new classes whenever we want to use a different one etc.

 

Use PHP function spl_autoload_register() instead of that.
You can use the below function where you will need to pass the name of the class that you’re trying to load as the first parameter of the function. As of PHP 5.3.0 we are able to use anonymous functions, basically a function thas has no name.

<?php
spl_autoload_register(function ($class){
echo ‘We are loading class.’ . $class;
include_once(‘classes/’ . $class . ‘.inc.php’);
echo ‘Class loaded.’;
});

?>

In PHP5, there ia a magic function called as __autoload() for fulfilling the same purpose.

 

 

Tip #13

Referencing

Passing variables by reference is a way to pass variables into functions so that the function can alter the original variable without having to return anything or define it as global etc. A function parameter that is going to be passed in as a reference is proceeded by an ampersand (&). Let’s see the below example.

<?php

function lowercase(&$string){
$string = strtolower($string);
}

$name = ‘STEPHEN’;
lowercase($name);
echo $name; // returns stephen
?>

 

There are so many advantages of using references, for example you don’t have to return anything from the function, nor do you have to look to define them as globally accessible.

References are very useful when you use them with arrays. Let’s say we have a function that sets the first item in any array to flower.

 

<?php
function flowerArray(&$array){
$array[0] = ‘flower’;
}
$nonflower = array(‘mahesh’, ‘nirmal’, ‘saurabh’);
flowerArray($nonflower);
print_r($nonflower); // This will now have changed ‘mahesh’ to ‘flower’
?>

 

 

Tip #14
Single Quotes vs. Double Quotes

You may or may not think about this point in your PHP use but it is kind of a big deal. Using the right or wrong quotes can not only cause errors that might be hard to find but there can be a slight performance boost and can make your code much easier to read.

<?php
echo ‘hello scriptarticle’;
?>
<?php
echo “hello scriptarticle”;
?>

These will produce the exact same end result but do you know which one is technically better? The single quote. The single quote just puts exactly what is inside of it without processing while the double quote actually evaluates and processes. Let’s take an example.

<?php

$example = ‘hello scriptarticle’;

echo ‘$example’; // outcome will be $example

echo “$example”; // outcome will be hello scriptarticle
?>

As you can see here the double quotes take the time to process what is inside so technically there will be a little more overhead.

Obviously on a small scale this means nothing but if you have a loop that iterates 1000 or more times you might start to see the benefits of single quotes in a performance sense.

 

 

Tip #15
PHP Short Tags

You know when you just want to pre populate a form or add one PHP variable into the middle of an HTML block. Which one is more readable and easy to use PHP open tags or short tags?

<?php echo $name; ?>
<?=$name ?>

Lower one will produce the exact same output as the first but much neater and with a little less code. It’s it?
NOTE: A short tag is something that can be disabled in the php.ini so it is not guaranteed to work but industry standard has short tags enabled.

 

 

Tip #16
Working with zero filled numbers in PHP

Padding Zero is very easy to do by using PHP build-in functions.

<?php echo $new_number = str_pad($num, 3, “0”, STR_PAD_LEFT); ?>

Remove padding zero
<?php echo intval($new_number); ?>

 

 

Tip #17
Know the Difference between Comparison Operators
<?php

$sentence = ‘scriptarticle is very good blog’;

if (strpos($sentence, ‘scriptarticle’)) {
echo ‘I like scriptarticle.’;
} else {
echo ‘I don\’t like scriptarticle..’;
}

?>
Because the substring “scriptarticle” occurs at the very beginning of “scriptarticle is very good blog”, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like ‘scriptarticle’ is not in the sentence but it is!

This can be corrected with a strict comparison as below.
<?php

if (strpos($sentence, ‘scriptarticle’) !== FALSE) {
echo ‘I like scriptarticle.’;
} else {
echo ‘I don\’t like scriptarticle..’;
}

?>

 

 

Tip #18
Methods in derived classes run faster than ones defined in the base class.

 

 

Tip #19
Accessing arrays
e.g. $row[‘id’] is 7 times faster than $row[id]

 

 

Tip #20
Avoid functions inside loops

Try to use functions outside loops. Otherwise the function may get called each time and obeviously it will affect performance.

<?php
/*  loop with a count() inside the control block will be
executed on EVERY loop iteration.
*/
$max = count( $array );
for( $i = 0; $i < $max; $i++ )
{
// do something here
}

// is better than
for( $i = 0; $i < count( $array ); $i++ )
{
// do something here
}
?>

It’s even faster if you eliminate the call to count() AND the explicit use of the counter by using a foreach loop in place of the for loop.

<?php
foreach ($array as $i) {
// do something
}
?>

 

 

Tip #21

When you need to output a large or even a medium sized static bit of text it is faster and simpler to put it outside the PHP.

This will make the PHP parser effectively skip over this bit of text and output it as is without any overhead. You should be careful however and not use this for many small strings in between PHP code as multiple context switches between PHP and plain text will be away at the performance gained by not having PHP print the text via one of its functions or constructs.

 

 

Tip #22
true is faster than TRUE

This is because when looking for constants PHP does a hash lookup for name as is & since names are always stored lowercased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

 

 

Tip #23
Incrementing or decrementing the value of the variable

When incrementing or decrementing the value of the variable $i++ happens to be a slower then ++$i.++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zends PHP optimizer.

It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

 

Additionally,
* Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
* Incrementing a global variable is 2 times slower than a local variable.
* Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
* Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

 

 

Tip #24
Free unnecessary memory

Unset your variables to free memory, especially large arrays.

 

 

Tip #25
Specify full paths

Use full paths in includes and requires, less time spent on resolving the OS paths.

<?php
include( ‘/var/www/html/your_app/database.php’ );
//is better than
include( ‘database.php’ );
?>

 

 

Tip #26
Use get_browser() built-in function to get browser information

Easily get your hands on the user’s browser-type.Some programmers leave this process to the browser end but can be useful to get this info server side.

 

 

Tip #27
debug_print_backtrace()

This print a debug-style list of what was called to get the point where this function is called.

 

 

Tip #28
Automatic optimization for your database

You will probably add and delete tables from time to time. Therefore, you should use a solution that works no matter how your database looks like. For this, you can use this PHP script that finds all your tables, and then perform Optimize on every single one.

<?php
dbConnect();
$tables = mysql_query(“SHOW TABLES”);

while ($table = mysql_fetch_assoc($tables))
{
foreach ($table as $db => $tablename)
{
mysql_query(“OPTIMIZE TABLE ‘”.$tablename.”‘”)
or die(mysql_error());
}
}
?>

 

Tip #29
require() vs. require_once()

Use require() instead of require_once() where possible.

 

 

Tip #30
Secure HTTP connections

You can force a secure HTTP connection using the following code,
<?php

if (!($HTTPS == “on”)) {
header (“Location.https://$SERVER_NAME$php_SELF”);
exit;
}
?>

 

 

AJAX Loading Icon Generators Tools

ajax-loading-icon-generators-tools

In the field of web development, generally you need to show indicator image until the code/response will ready to display.

 

You can also call the indicator image as an “AJAX loading” icon or a “preloader image”. It is commonly used on AJAX-base sites and applications, informing the user that the site is still processing the request and fetching some data.

 

You all know how important the UI is, so you always want the very good indicator image, If I am not wrong designer is not always ready to do these type of small stuff for you 🙂

 

No worries, we have very good live solutions for that and it is totally free and customizable to fulfilling your need.

 

AJAX preloader images/gifs

Create your AJAX preloader images online dynamically without any head-ache

 

The main customizations you can do are

1) Select the AJAX image indicator according to your wish
2) Set background image color or can make transparent
3) Set foreground color
4) Set size of the indicator GIF
5) Update animation speed
6) Size of the image and many more

 

AJAX Loading Icon Generators Tools

http://preloaders.net/

http://www.ajaxload.info/

http://www.loadinfo.net/

http://heartcode.robertpataki.com/canvasloader/

http://xeosoft.com/ajaxloader

http://spiffygif.com/

http://cssload.net/

Use HTML5 On Your Website

use-html5-on-your-website

Detect HTML5 usage

If you want to see that a website is using HTML5 elements or not, you only need to view the source of the website.
If the source code starts with the following declaration.

<!DOCTYPE HTML>

Then, website was marked up with HTML5.

By using the HTML5 DocType, you can let the browser know what to expect from your document.HTML4 required a DocType reference to a DTD (doc type declaration), and there were three different DTD’s that could be used but HTML5 doesn’t require such a reference.

 

Remove Internet Explorer HTML5 Compatibility Issues

Microsoft IE9 supports HTML5, but there are still so many people using MSIE 7 and 8 and even MSIE 6.Add below HTML5 enabling script to allow developers to use any HTML5 element on their page. It should place within the <HEAD> tags, and is referenced like this:

 

<!–[if lt IE 9]>
<script src=”http://html5shim.googlecode.com/svn/trunk/html5.js”></script>
<![endif]–>

 

HTML5 Element Detection Techniques

When browser renders a web page, it constructs a Document Object Model (DOM), a collection of objects that represent the HTML elements on the page. Every html element is represented in the DOM by a different object. (There are also global objects, like window and document, that aren’t tied to specific elements.)

All DOM objects share a set of common properties, but some objects have more than others. In browsers that support HTML5 features, certain objects will have unique properties. Let’s discuss, which features are supported.

There are four basic techniques can be used to detect whether a browser supports a particular feature or not.

1.Check if a certain property exists on a global object (such as window or navigator).
E.g: test for geolocation support

 

2.Create an element, and then check if a certain property exists on that element.
E.g: test for canvas support

 

3.Create an element, check if a certain method exists on that element, then call the method and check the value it returns.
E.g: test which video formats are supported

 

4.Create an element, set a property to a certain value, and then check if the property has retained its value.
E.g: test which <input> types are supported

 

Modernizr can be used to detect these easily as
Modernizr is an open source, MIT-licensed JavaScript library that detects support for many HTML5 & CSS3 features. You should always use the latest version of this. To use it, include the following <script> element at the top of your page.
<script src=”modernizr.min.js”></script>

 

HTML5 Form Enhancements (New elements)

Autofocus Using HTML5
<input id=”example” name=”example” type=”text” autofocus />

Placeholders Using HTML5
<input id=”example1″ name=”example1″ type=”text” placeholder=”Your Text” />

Editable Content Using HTML5’s contenteditable
<p contenteditable=”true”>Put your mouse pointer in this text and you can update it!</p>

Also, it has also introduced some new elements as below:

<article>
<aside>
<audio>
<canvas>
<command>
<datagrid>
<details>
<dialog>
<figure>
<footer>
<header>
<m>
<meter>
<nav>
<output>
<progress>
<section>
<source>
<time>
<video>

 

HTML5 also defines new input types that you can use in your forms.

<input type=”search”> for search box
<input type=”date”> for calendar date picker
<input type=”month”> for month
<input type=”week”> for week
<input type=”time”> for timestamp
<input type=”datetime”> for precise, absolute date+time stamp
<input type=”datetime-local”> for local dates and time
<input type=”number”> for spinbox
<input type=”range”> for slider
<input type=”color”> for color picker
<input type=”tel”> for telephone number
<input type=”url”> for web address
<input type=”email”> for email address

 

JQuery AJAX file uploading with custom browse button & without Flash

ajax-file-uploading-using-jquery-php

AJAX file uploading using jQuery & PHP:

In the day to day life of web programming, you will need to upload the files on server without page refresh. It is very easy with flash, but will little bit tricky with XMLHttpRequest (JavaScript Browser Object) and AJAX.
Find the below code or Package that will help you to design your file browse button as per your site theme or whatever the design you want. I think you already aware by the AJAX (Asynchronous JavaScript and XML)

 

Find the below Package for doing the job of AJAX file uploading, where you don’t need Flash work at all.

 

You have to add 2 JavaScript (jQuery) file and a very simple Style Sheet, which is used to make the browse button as per your requirement or needs.

 

Download the below zip file to explore your world of web application development.

Cheers!!

ajax-upload-file.zip

 

If you find any bug left by me 🙂 or find any difficultly to implement, please post comment.

Simple Star Rating System With jQuery

jQuery Star Rating System

This is jQuery plugin for star rating systems.The code below is modified of original script to make it simpler for you to develop a star rating in your application.

 

Check the demo below

hover and click events on stars to change there state

$('#star1').rating('www.your-url.php', {maxvalue:1});

$('#star2').rating('www.your-url.php', {maxvalue:1, curvalue:1});

$('#rate1').rating('www.your-url.php', {maxvalue:5, increment:.5});

$('#rate2').rating('www.your-url.php', {maxvalue:5, curvalue:3});

 

Find the complete package of Simple Star Rating by the below link:

jQuery-star-rating.zip

Really Simple Syndication (RSS)

RSS (Really Simple Syndication) or Rich Site Summary is a format of data for delivering regularly changing web content.Without RSS, users will have to check the site daily for new updates that is very time-consuming.Since RSS data is small and fast-loading, it can easily be used with services like as cell phones or PDA‘s also.

 

An RSS document (which is called a “feed”, “web feed”, or “channel”) includes full or summarized text, plus metadata such as publishing dates and author information.

 

A standardized XML file format allows the information to be published once and viewed by many different programs.They benefit readers who want to subscribe to timely updates from favourite websites or to aggregate feeds from many sites into one place.

 

As RSS files are essentially XML formatted plain text, the RSS file itself is relatively easily read both by automated processes and by human.This could be placed on any appropriate communication protocol for file retrieval, such as http or ftp, and reading software would use the information to present a neat display to the end user.

<?xml version=”1.0″ encoding=”UTF-8″ ?>
<rss version=”2.0″>
<channel>

<title>ScriptArticle.com</title>
<description>This is an example of an RSS feed</description>
<link>http://www.scriptarticle.com</link>
<lastBuildDate>Sun, 15 Apr 2012 02:57:45 +0000</lastBuildDate>
<pubDate>Sun, 15 Apr 2012 02:52:32 +0000 </pubDate>
<ttl>1800</ttl>

<item>
<title>Example entry</title>
<description>Here is some text containing a description.</description>
<link>http://www.scriptarticle.com/</link>
<guid>unique string per item</guid>
<pubDate>Sun, 15 Apr 2012 02:52:32 +0000 </pubDate>
</item>

</channel>
</rss>

 

Quick view to RSS

  • RSS stands for Really Simple Syndication
  • RSS is written in XML
  • RSS defines an easy way to share and view headlines and content
  • RSS allows you to syndicate your site content
  • RSS files can be automatically updated
  • RSS allows personalized views for different sites

 

Benefits of using RSS

It allows you to easily stay informed by retrieving the latest content from the sites you are interested in.You save time by not needing to visit each site individually.
With RSS it is possible to distribute/spread up-to-date web content from one website to thousands of other websites around the world easily.

 

RSS of articles of scriptarticle.com
http://www.scriptarticle.com/feed/

 

RSS of comments on articles of scriptarticle.com
http://www.scriptarticle.com/comments/feed/