Showing posts with label php tips. Show all posts
Showing posts with label php tips. Show all posts
| 0 comments ]

How to add or remove WWW on URLs using htaccess. Adding www to your site url using .htaccess

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

Removing www from your site url using .htaccess

RewriteCond %{HTTP_HOST} ^yoursite\.in$ [OR]
RewriteCond %{HTTP_HOST} ^www\.yoursite\.in$ [NC]
RewriteRule ^/?$ "http\:\/\/yoursite\.in\/" [R=301,L]

| 0 comments ]

Compressing HTML, CSS, Javascript using Apache There are two methods to available in apache to handle compression of webpage contents. They are mod_gzip and mod_deflate . Usually deflate comes pre-installed on servers. We can install both in our apache server. before we install, lets check is it availble in your server,

In order to check whether these apache directives are installed or not, we can create a test php file with calling function the phpinfo() function. From that we can see "Loaded Modules" setting in the "apache2handler" header.

From that we can see whether its installed or not. in the case of deflate, we can see "mod_deflate" under that section.

Install mod_deflate in your server

a2enmod deflate

the restart your apache with the following command

/etc/init.d/apache2 restart

We can enable this feature using .httacess file in the root directory

## Apache2 deflate support if available
##
## Important note: mod_headers is required for correct functioning across proxies.
##

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.[0678] no-gzip
BrowserMatch \bMSIE !no-gzip

 
Header append Vary User-Agent env=!dont-vary
 
 
# The following is to disable compression for actions. The reason being is that these
# may offer direct downloads which (since the initial request comes in as text/html and headers
# get changed in the script) get double compressed and become unusable when downloaded by IE.
SetEnvIfNoCase Request_URI action\/* no-gzip dont-vary
SetEnvIfNoCase Request_URI actions\/* no-gzip dont-vary
 


This is a simple version for the usage of mod_deflate.c in .httacces


 AddOutputFilterByType DEFLATE application/x-javascript text/css text/html text/xml


The another option is mod_gzip, it is usually 4 -6 times faster than deflate. But its needs too much server load compared to deflate. So its advised to use mod_gzip on low-traffic sites and in large traffic sites, its better to use deflate. The settings for mod_zip is following. its can be given in a .htaccess file.

# Turn on mod_gzip if available

    mod_gzip_on yes
    mod_gzip_dechunk yes
    mod_gzip_keep_workfiles No
    mod_gzip_minimum_file_size 1000
    mod_gzip_maximum_file_size 1000000
    mod_gzip_maximum_inmem_size 1000000
    mod_gzip_item_include mime ^text/.* 
    mod_gzip_item_include mime ^application/javascript$
    mod_gzip_item_include mime ^application/x-javascript$
    # Exclude old browsers and images since IE has trouble with this
    mod_gzip_item_exclude reqheader "User-Agent: .*Mozilla/4\..*\["
    mod_gzip_item_exclude mime ^image/.*


| 0 comments ]

* create_function :

This function will create a php function .This function returns a unique function name as a string, or FALSE on error on creation.

Syntax :create_function( string $argument_list , string $function_code )

for example
<?php
$addnumbers = create_function('$no1,$no1', 'return "sum = " . $no1+$no2;');
echo $addnumbers(12,100) . "\n";
?>

output

sum=112


* function_exists


This function can be used to check whether a function is defined or not .It teturn true if the function has been defined

for example


<?php

function myfunction(){
echo "Reached here";
}

$fun='myfunction';
echo function_exists($fun)?" function $fun exist <br>":" $fun doesn't exist <br>";

$fun='myfunction11';
echo function_exists($fun)?" function $fun exist <br>":" $fun doesn't exist <br>";
?>

output :
function myfunction exist
function myfunction11 doesn't exist


* is_callable()

this function checks whether a variable can be called as a function or not


* call_user_func

This function call a user function

syntax: call_user_func ( function ,parameter)


for example


<?php
function egfunction(&$age){
echo $name."\n";
$age++;
}
$age=22;
echo "my age before function call ".$age;
call_user_func('egfunction', $age);
echo "my age after function call ".$age;
?>

output :

my age before function call 22
my age after function call 23


* call_user_func_array

this function call a function with an array of parameters.
for example


<?php

function myfunction($no1, $no2) {
return $no1+ $no2;
};

$func='myfunction';
echo call_user_func_array($func, array(300,500));

?>

output

800


* func_num_args :

This function returns the number of arguments passed to the function,
This function can be used with func_get_arg() and func_get_args() to ensure that the right number of arguments have been passed to a function.

for example


<?php
function sampleFn()
{
$argNo = func_num_args();
echo "Number of arguments: $argNo \n";
}

sampleFn();
sampleFn('only one arg');
sampleFn('two', 'args');
sampleFn(1,2,3,4,5,6,7,8,9,10);
?>

output :

Number of arguments : 0
Number of arguments : 1
Number of arguments : 2
Number of arguments : 10

Note : in javascript we can use arguments.length to find the length
alert(arguments.length);


* func_get_arg

This function returns an item from the argument list.

syntax : func_get_arg ( $num )


<?php
function myfunction()
{
$No = func_num_args();
echo "Number of arguments: $No<br />\n";
if ($No >= 2) {
echo "Third argument is: " . func_get_arg(2) . "<br />\n";
}
}

myfunction ('v1','V2','V3','V4');
?>

output :
Third argument is V3


* func_get_arg

<?php
function myfunction()
{
$no = func_num_args();
echo "Number of arguments: $numargs<br />\n";
$args = func_get_args();
for ($i = 0; $i < $no; $i++) {
echo "Argument". $i+1." is: " . $args[$i] . "<br />\n";
}
}

myfunction ('v1','V2','V3','V4');
?>


output

Argument 1 is V1
Argument 2 is V2
Argument 3 is V3
Argument 4 is V4

| 1 comments ]

Some of the common php array functions are explained with simple examples

* array() :
Creates an array
* array_count_values():
It returns an array, with ,the parent array's values as keys, and the values is the number of occurrences.

Example:




$alphas = array('A', 'B', 'C', 'D', 'B', 'C', 'C', 'D', 'E');

$result = array_count_values($alphas);
print_r($results);
echo "
The array alphas have $result[A] A's, $result[B] B's, $result[C] C's,$result[D] D's and $result[E] E's";


?>

Output:


Array ( [A] => 1 [B] => 2 [C] => 3 [D]=>2 [E]=>1 )
The array alphas have 1 A's, 2 B's, 3 C's,2 D's and 1 E's


* array_change_key_case :
returns an array with all array keys in specified case.
the array Constants CASE_LOWER and CASE_UPPER used with this function. The former returns the array key values in lower case(default case) the later returns the array key values in upper case.

Example:


$parent=array("a"=>"apple","B"=>"boy","c"=>"cat","d"=>"doll");
$result=array_change_key_case($parent,CASE_UPPER);
?>

Output:


Array ( [A] => apple[B] => boy [C] => cat [D]=>doll)


*array_chunk() : splits an array into new arrays.
This function has 3 parameters one is array itself second one is size of chunk and third one is preserve_key which determines whether to preserve the parent key or not .
true value preserves the keys and false does not preserve the keys.False is the default one.

Example:


$array=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
$result1=array_chunk($array,2);
$result2=array_chunk($array,2,true);
echo "The result array1=> preserve_key=default ie false ";
print_r($result1);
echo "
The result array2=> preserve_key=true "

print_r($result2);
?>

Output:

The result array1=> preserve_key=default ie false
Array (
[0] => Array ( [0] => apple[1] => boy )
[1] => Array ( [0] => cat [1] => doll )
)
The result array2=> preserve_key=true

Array (
[0] => Array ( [a] => apple[b] => boy )
[1] => Array ( [c] => cat [d] => doll )
)

*array_flip :
this function will transposes the keys and values of an array

Example:

$array=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");

echo "Array before using the flip function
";

foreach($array as $key=>$value){

echo "
array[".$key."]=>".$value;

}
$flipped_array = array_flip($array);

echo "Array after using the flip function
";

foreach($flipped_array as $key=>$value){
echo "
flipped_array[".$key."]=>".$value;

}

Output:

Array before using the flip function

array[a]=>apple
array[b]=>boy
array[c]=>cat
array[d]=>doll

Array after using the flip function


flipped_array[apple]=>a
flipped_array[boy]=>b
flipped_array[cat]=>c
flipped_array[doll]=>d

* array_intersect :
this function returns an array containing elements that are present in all array arguments.
it returns with the key of first arry.

Example:

$array1 = array('apple', 'boy', 'cat', 'doll');
$array2 = array('doll','angel', 'bag', 'car');
$array3 = array('art', 'brain', 'doll', 'coal');
$intersect = array_intersect($array1, $array2, $array3);
echo "Intersection of array1, array2 and array3 is ";
print_r($intersection);
?>

output :
Intersection of array1, array2 and array3 is

Array
(
[3] => doll
)


* array_diff() :
this function returns an array with the keys and values from the first array, if the value is not present in the other arrays

* array_diff_assoc() :the function returns an array with the keys and values from the first array, only if they are not present in the other arrays

example :

$array1=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
$array2=array("a"=>"apple","b"=>"bag",c=>"doll","d"=>"cat");
$result=array_diff($array1,$array2);
echo "
out put by array_diff()";

print_r($result);
echo "
out put by array_diff_assoc() ";

print_r(array_diff_assoc($array1,$array2));
?>
output:

out put by array_diff()";

Array (
[b] => boy
)


out put by array_diff_assoc()

Array (
[b] => boy
[c]=>cat
[d]=>doll
)

* array_combine() :
creates an array by merging two other arrays, with the first array as the keys, and the other as the values

example:


$array1=array("a","b","c","d");
$array22=array("apple","boy","cat","doll");
$result=array_combine($array1,$array2);
echo "merged array";
print_r($result);
?>
.output:

merged array

Array (
[a] => apple
[b] => boy
[c] => cat
[d] => doll

)



* array_keys() :
returns all valid keys for the given array.
* array_values() : returns an array containing all the values of an array

example:


$array1=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
echo "
Array keys
", implode(", ", array_keys($array1));

echo "
Array values";

print_r(array_values($array1));

?>
Array keys

a, b,c,d

Array values
Array ( [0] =>apple [1] => boy [2] => cat [3]=>doll )

* array_merge()
:merges arrays into one array

example :

$array1=array("a"=>"apple","b"=>"doll");
$array2=array("c"=>"cat","b"=>"boy");
print_r(array_merge($array1,$array2));
?>
output

Array (
[a] => apple
[b] => boy
[c] => cat
)

* array_reverse() :returns an array in the reverse order .The second parameter determines whether to preserve the key of the parent array or not

example :

$array1=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
print_r(array_reverse($array1));
?>
output

Array (
[d] => doll
[c] => cat
[b] => boy
[a]=>apple
)


*array_walk() : runs each array element in a user-defined function


example


function userFn($value,$key)
{
echo "array1[".$key."]=>".$value;
}
$array1=array("a"=>"apple","b"=>"doll");
array_walk($array1,"userFn");
?>


output :

array1[a]=>apple
array1[b]=>doll


*array_slice : returns an array subset of consecutive elements from the parent array




$array=array(0=>"apple",1=>"boy",2=>"cat",3=>"doll");
print_r(array_slice($array,-2,1));
echo "
";

print_r(array_slice($array,1,2,true));
?>

Array ( [0] => cat )

Array ( [1] => boy [2] => cat )

* arsort() : sorts an array by the values in reverse order
* ksort() : Sorts an array by key
* krsort() : Sorts an array by key in reverse order


$array = $array1=array2=array("a"=>"cat",b"=>"boy","c"=>"apple","d"=>"doll");
echo "arsort
";

arsort($array );
print_r($array );
echo "asort
";

asort($array1 );
print_r($array1 );
echo "ksort
";

ksort($array2 );
print_r($array2 );
?>
output
arsort
Array
(
[d]=>doll
[a] => cat
[b] => boy
[c] => apple
)

asort
Array
(
[c] => apple
[b] => boy
[a] => cat
[d]=>doll
)

ksort
Array
(
[a] => cat
[b] => boy
[c] => apple
[d]=>doll
)
krsort
Array
(
[d]=>doll
[c] => apple
[b] => boy
[a] => cat



)



* sizeof() : Returns the number of array elements.
* range() : Automatically create an array containing a range of elements
* in_array() : Returns true or false if an array contains a specific value.

example:

$array = array("a"=>"cat",b"=>"boy","c"=>"apple","d"=>"doll");
echo "size of array:".sizeof($array );
echo "
";

if (in_array("apple",$array ))
{
echo "Apple is in array";
}
else
{
echo "Apple is not in array";
}
?>
output :
sizeof array :4
* extract() : Extracts list items into matched variable/value pairs
* list() : Assigns list values to variables.
* shuffle() : Shuffles an array


$array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
echo "Before shuffling ", implode(", ", $array1 ), "\n";
shuffle($array1 );
echo "After shuffling ", implode(", ", $array1 ), "\n";
?>

Output:

Before shuffling: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
After shuffling : 9, 4, 6, 3, 1, 5, 7, 8, 2, 10

| 1 comments ]

tips on error 'Allowed memory size of xxx bytes exhausted'

While working on php, the is chance to get following error "Allowed memory size of xxx bytes exhausted". The reason behind this error is that, Setting the memory limit using the memory limit on the server was exhausted. This is often happens with page with large data, or too many loops, condition checking, or large file uploading etc.

By default the memory limit is 8M we can change this value, by editing the php.ini file. if you are in a dedicated server, we can edit its value on php.ini file and then restart the appache server. But in shared hosting, this issue is very common. usually have no access to php.ini file.

if you have no access to php.ini, we can set these values through coding in php, for that we need to use the following function;

string ini_set(string $apache_variable,string $newvalue);

example :

ini_set('memory_limit','16M');

In some servers we could not do this, in that case we have have an alternative to do this , we just want to use the .htaccess file. we can describe the memory_limit on this file, if there is a .htaccess file, just edit the file and add the desired code.Other wise, create a new one by saving a text file with the name .htaccess, and put it into your working directory.

command

php_value memory_limit [new memory limit]

example

php_value memory_limit 32M

enjoy PHPing.....

| 0 comments ]

1)  set_time_limit();

function to limit the maximum execution time. we can give values starting from zero.the default value is 30 seconds or as per we set on the php.ini file settings. If we given 60 as the time limits the execution will stop when the time reach and return a fatal error.

If we doesn't want to stop the script execution, at any time limit, we can set the function as given below.

set_time_limit(0);


2)  register_shutdown_function('functionname');

The function is used to register a function, while shutdown, like browser closing. We can register multiple shutdown functions. but when we use a exit on any function the functions resisted after that will not execute.

a sample register shutdown function

<?php
function browserClosed()
{
   //we can specify the logout actions on browser closing      
   echo "logout";
}
?>

register_shutdown_function('browserClosed');


3)  ignore_user_abort(bool);

Used to set whether the script should abort, when the client disconnects. if it sets to false, it will abort the script, if its true, it will will not abort the script when the client disconnects.

We can use this function in a situation, when we want to close our browser before the execution completes.

Hope these tips are helpful to you all. Please comment about the posting, I always welcomes your feedback

Enjoy PHPing....