Category Archives: Validation & functions

Search Engine Spider and User Agent Identification with “Ultimate User Agent Blacklist”

Search Engine Spider and User Agent Identification with “Ultimate User Agent Blacklist”

 

A user-agent is software (a software agent) that is acting on behalf of a user.
In many cases, a user-agent acts as a client in a network protocol used in communications within a client–server distributed computing system.

 

For more information view wiki
http://en.wikipedia.org/wiki/User_agent

 

Automated Agents is called as Bots.
http://user-agents.org has a complete list of all latest spiders/bots/user agents.
There are some more and those are anonymous (not known and have very different names).

 

If you develop a website and want to make the site accessible by some specific user agent or bots of a country, then you can update the information in your root .htaccess file.

 

As, Bot blocking blacklists are useless in some way as some rogue spiders just generate random user-agent strings so we will never have them in our list to start with, but We have tried list out as much as we can in the below zip file.

 

Ultimate User Agent Blacklist

 

What you have to done is, unzip the file and paste the code in your root .htaccess file, it will protect your website from unwanted crawling/indexing by anonymous bots.

 

If your website uses WordPress open-source, then can also use “Better WP Security” plug-in.
Just need to download and install the plug-in and go to “Better WP Security – Ban Users” Tab and enable “Enable Default Banned List”, you can also update the list according to your needs.

 

But please be careful before doing same, as it may affect your website’s core files and plug-in, So before doing this backup your website’s files and database.

 

30 Top PHP Tips and Tricks & 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(‘[email protected]’, 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;
}
?>

 

 

Customize JQuery UI datepicker with From and To date

I think you have used the JQuery UI datepicker many times and you have also faced trouble when there are 2 date text-boxes and you have to use datepicker in both with taking care that one text-box date value always less than the 2nd one.

 

I think you have got my point, what I want to say.
Like you have two date fields named as FROM and TO and FROM date should always less then TO date.

 

For solving the same you have to make a trick in the datepicker function.
Below is the same you can use.

 

Just add below three lines to include CSS and JS  in your document head as below.

 

Head Section:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>

 

JavaScript Code:

<script type="text/javascript">
$(document).ready(function(){

	$("#datepicker").datepicker({
	
		dateFormat : 'dd/mm/yy',
		minDate    : new Date(),
		maxDate    : '+1Y',
		defaultDate: "+1w",
		changeMonth: true,
		onSelect   : function(selected){
		
			var arr = selected.split("/");
			var spares = [arr[2], arr[1],parseInt(parseInt(arr[0])+1)];
			var joint = spares.join("/");
			var minDate2 = new Date(joint);
			$("#datepicker2").datepicker("option","minDate", minDate2);
		
		}
	
	});
	
	$("#datepicker2").datepicker({
	
		dateFormat : 'dd/mm/yy',
		minDate    : "+1",
		defaultDate: "+1w",
		maxDate    : '+1Y',
		changeMonth: true,
		onSelect   : function(selected) {
		
			$( "#datepicker" ).datepicker( "option", "maxDate", selected );
		
		}
	
	});

});
</script>

 

HTML Code:

<table width="100%" border="0" cellspacing="2" cellpadding="2">
  <tr>
    <td colspan="2">From Date:</td>
    <td><input type="text" value="" name="indate" id="datepicker" /></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td colspan="2">To Date:</td>
    <td><input type="text" value="" name="outdate" id="datepicker2" /></td>
    <td>&nbsp;</td>
  </tr>
</table>

 

For further reference you can go through the JQuery UI library by the below URL.

JQuery UI datepicker

 

I hope this all will help you.

Let me know by comments, if you still face any issue related to above.

 

PHP: What is the difference between split and explode php?

Difference between split and explode php

Do you know what is the main difference between split() and explode()?

No worries 🙂 , the main difference in split() and explode is the way, it uses to splitting a large string.

 

Both the functions are used to Split a string. However, Split is used to split a string using a regular expression. On the other hand, Explode is used to split a string using another string.

 

The split() function splits the string into an array using a regular expression and returns an array.
Ex: split (:India:Nepal:Srilanka); returns an array that contains India, Nepal, Srilanka.

 

The explode () function splits the string by string.
Ex: explode (and India and Nepal and Srilanka); returns an array that contains India, Nepal, Srilanka.

 

Have a look by below example.

split (":", "i:am:reading:scriptarticle.com");

returns an array that contains i,am,reading,scriptarticle.com.

 

 

The explode () function splits the string by string.

explode ("I", "I am reading scriptarticle.com");

returns an array that contains

array (
0 => ”,
1 => ‘ am reading scriptarticle.com’,
)

Note: split () function has been DEPRECATED as of PHP 5.3.0.

 

It’s been deprecated because

 

  • explode() is substantially faster because it doesn’t split based on a regular expression, so the string doesn’t have to be analyzed by the regex parser
  • preg_split() is faster and uses PCRE regular expressions for regex splits

 

join() and implode() are aliases of each other and therefore don’t have any differences.

 

Hope it helps!!

Test and debug your code online

During program or code development we face lot of issues and bugs and in between we need some debugging.
In PHP there is not a easy way to debug the page line by line, so you have to use ‘echo’,’die’,’print_r’,’var_dump’ like functions for debugging.

 

It take a little bit more time to open the page add these function and then view that page again by refreshing the browser.

 

Here on internet you have lot of websites the providing the same functionality to check the variable in very less time and without reviewing code again and again.

 

I am listing out some of these as follows:

1. json_encode and json_decode parser online tool
http://json.parser.online.fr/

2. base64_decode and base64_encode

3. Array serialize and unserialize

4. Format date and date related function

5. md5,preg_replace ,preg_match

6. String related functions
http://www.tools4noobs.com/online_php_functions/

 

7. Count characters in a string and words in a sentence
http://allworldphone.com/count-words-characters.htm

 

8. JS beautifier (to format your JavaScript file)
http://jsbeautifier.org/

 

9. Format your HTML page (format your HTML page)
http://www.freeformatter.com/html-formatter.html

 

10. W3C validate
http://validator.w3.org/#validate_by_input

 

RUN/Execute your small php code online with any version of PHP.
http://sandbox.onlinephpfunctions.com/

 

RUN/Execute your JavaScript code to view the result online.
http://writecodeonline.com/javascript/

 

RUN/Execute jQuery code online to test
http://jsfiddle.net/

 

List of All PHP Functions
http://php.net/manual/en/indexes.functions.php
http://php.net/quickref.php

 

Okay guys, Try out these hope these will help you in debugging the code.
All the best!!

 

 

How to get more records or data on scroll down of page in PHP like facebook?

Do you know How to display more records while scrolling the page down using JQuery and PHP?

If you are familiar with jQuery and PHP, then it is not hard nut to crack.

Have a look on below code and you can do the same. Include JQuery library File:

Include JQuery library File:
<script type=’text/javascript’ src=’http://code.jquery.com/jquery-1.7.2.js’></script>

 

Create or call using a simple jQuery function in JS file (If you want to make the code separate).


$(window).scroll(function(){
	scrollFunc(); 
});


function scrollFunc()
{
   if($(window).scrollTop() == ($(document).height() - $(window).height())){	  
   
   var offset = $('[id^=&quot;dataRow_&quot;]').length; 
   var records = $(&quot;.totNum&quot;).text();
   
   $(window).unbind(&quot;scroll&quot;);
   
   if(records != offset){
   
	   $(&quot;#loaderImg&quot;).html('&lt;img src=&quot;images/ajax-loader.gif&quot; /&gt;');	   
	   loadMoreRecords(offset); 
	   
   }
   
   }

}


function loadMoreRecords(offset){
	
	// here we call ajax to add more records in our page.
	$.ajax({
	
		type: 'get',
		url: 'loadMyPageRecords.php',
		data: 'offset='+offset,
		
		success: function(data){
		
			$(&quot;#loaderImg&quot;).html();
			$(&quot;.loadData :last&quot;).after(data);
			
		},
		
		error: function(data){
		 alert(&quot;ajax response error...&quot;+data);
		}
		
		}).done(function(){
		
		$(window).bind(&quot;scroll&quot;,function(){
			scrollFunc();					
			   
		});
	});	

}

 

How simple !! Isn’t it?

If you still face any issue, post your comments.