Categories
php

How to Install Php Extension

The easiest way to install php extension is using pecl.

To install you have to run

pecl install extension_name

But if you have the sources of the php extension then.

cd extension_name_folder
phpize
./configure
make
make install

if you have php installed in another location. Lets assume php is installed in /opt/php
To install the extension you have to do is first download the extension and then unzip it and run the phpize and make and make install. Example commands to run

pecl download extenstion_name # you will see a .tgz / .zip / .tar.gz file
unzip  extension_name.zip # unzip  / untar it using tar xvfz extension_name.tar.gz
cd extension_name_folder
export PHP_PREFIX="/opt/php"
$PHP_PREFIX/bin/phpize
./configure --with-php-config=$PHP_PREFIX/bin/php-config
make
make install

Then to enable you have to add in your php.ini file

extension=extension_name.so
Categories
php

How to Execute Php in Html files

To execute php codes <?php ?> in your .html files you need to add the following lines in your .htaccess file

AddType application/x-httpd-php .html

You can make php code in any file executed by replacing the .html with that respective file extension in above code.

Categories
php

Unlimited Bandwidth is it possible?

Many web hosting companies advertise about unlimited bandwidth and unlimited disk space. Is it really possible for these companies who don’t even own their line to be able to provide unlimited bandwidth. Some companies find providing unlimited bandwidth possible as most of the webmasters bandwidth usage is below average hence providing the remaining bandwidth to others who require more (i.e, unlimited bandwidth). If your hosting company provides unlimited hosting bandwidth then first read the unlimited conditions given to provide such service, like your content should not take high CPU usage etc.. Bandwidth is one of the costliest resource. It is not cheap as they show.

Many of these unlimited bandwidth providers restrict video and audio files. These multimedia files consume huge hard disk space and bandwidth. The streaming video also takes heavy load. Unlimited disk space / bandwidth is just a trick to attract customers. I have seen one host saying that unlimited disk space and unlimited bandwidth only for 6$ /month (condition — if you pay for 10 years of service in advance). Are you stupid to tied up for a single webhost for years without knowing their credibility? Their service might go down hill over the span of 10 years and you have to bear with them for 10 years!!! WTF!!
So choose unlimited webhosting if you know your disk space and bandwidth usage. If you want to have a large site with numerous multimedia files unlimited is not an option because you will eventually run into trouble with them. As long as you know your website bandwidth & disk space requirements you are safe….

Categories
php

Basics in Php

Php Basics

Table of Contents.

 

Syntax of php

The php code block starts with <?php and ends with ?>.
In some some servers when shorhand is enables one can start the php code with <? but for compatibility its always recommended
to start a php block of scripts with <?php
[php]

<?php

echo “Hello World”;

?>
[/php]

The php files contains normal html tags like and php code comes in between. Here is an example of php file.

[php]
<html>

<head>

</head>

<body>

<?php

$title = $_GET[“title”];

echo $title;

?>

</body>

</html>

[/php]
Each of the php statement ends with a semicolon ; . It indicates the end of an instruction.

Return To Top

 

Echo and Print

The two commands “echo” and “print” are used to print or output strings. Both echo and print are used to output
strings but they have some basic differences. It is convinient to out put html codes using ‘print’ since the string is enclosed in single quotes ‘. as shown below

[php]
print ‘Hello World’;
[/php]
But if you use echo to print html code you need to escape the double quotes since the strings are enclosed by ” or double quotes.

[php]
echo “<a href=\”http://www.google.com\”>Google</a>”;
[/php]

the same code can be printed using print as

[php]
print ‘<a href=”http://google.com”>Google</>’;
[/php]

But if you are calling and printing values of variables you need to use echo which is more convenient.
The following example illustrates how easy it is to print values from variables using echo. You can to concatenate strings in case of print statement using ‘.’
[php]

<?php

$title = “Hello. THis is a php text”;

echo “Value of  variable title = $title”;

print ‘Value of  variable title =’.$title;

?php>

[/php]

Return To Top

Variables in Php

You can store data,strings,numbers and arrays in variables.

You can access these values again and again over all your script and
change the values.

variables in php starts with $ sign.

You declare a varialble like

[php]
$variable = values;
[/php]
There is no need to declare the type of variables in php.

It converts the data according to how it is declared.

The below example describes how variables are declared in php

[php]
<?php

$string-a = “how are you?”;

$numbers = 80;

?>
[/php]

Rules for Naming the Variables

  • The variable name can only contain alphabets,numbers and
    underscore. It can contain a-z,A-Z,0-9 and _.
  • The variable name must start with an alphabet or _
  • The variable name cannot contain any spaces and if there
    are two words in string one must use _ to connect them like $my_variable

Return To Top

Operators in Php

Operators in php are used to perform arithmetic and logical operations
on variables.

Here are the operators listed by groups

Arithmetic Operators

Operator Description Example Output
+ Addition $x=2

$x+3

5
Subraction $x=5

$x-3

2
* Multiplication $x=5

$x*2

10
/ division $x=10

$x/2

5
% Remainder in Division or Modulu $x=15

$x%14

1
Decrement $x=5

$x–

x = 4
++ Increment $x=1

$x++

x = 2

Logical Operators

Operator Description Example Output
&& and x=5

y=8

x<6&&y>7

returns True

|| or x=5 , y =8 (x<6||y<6)

Returns true

(x==6||y==9)

Returns False

! Not x=5

y=5

!(x==y)

Returns false

Comparision Operators

Operator Description Example Output
> Greater than x=5

y=6

x>y Returns false
< less than x=6

y=5

x<y Returns false
== is equal to x= 6

y = 6

(x==y) Returns true
>= greater than or equal to x=5

y=6

x>=y returns false
<= Less Than or equal to x=6

y=9

x<=y returns true
!= is not equal to x=5

y=6

x!=y returns true

Assignment Operators

These operators are used to assing values or change values of a
variable.

Operator Description Example
+= x+=y   increments x value by y x+=5. Increses x by 5
-= x-= y decreases x value by y x-=5 decreases x by 5
*= x*=y multiplies x with y x*=5 now x value is 5x
/= x/=y divides x by y x/=5 now x values is x/5
%= x%=y x value is remainder of division x/y x%=5 x values is remainder of division x/5
= x=y x values is same as y x=5 x values is 5
.= Concatenates strings.

x.=y

Return To Top

Categories
php

A primer on Strings in Php

Strings in Php

Table of Contents.

Declaring Strings

String are variables in which we can store text and manipulate text.
Here is an example of how string is declared in php.

[php]
<?php
$txt = “Hello World!”;
echo $txt;
?>
[/php]
Output is
[php]
Hello World!
[/php]

The text string is always enclosed in double quotes (“). There is no need to specify the data type. There are many functions to manipulate strings in php. Only some of the important are discussed here.

Return to Top

Concatenating Strings

In php we concatenate strings using dot (.) .It is the operator for joining two texts.

Example how to concatenate strings.

[php]
<?php

$txt1 = “php tutorials”;

$txt2 = ” best site”;

echo $txt1.”hello world<br>”;

echo “This is to join”.” strings<br>”;

echo $txt1.$txt2;

?>
[/php]

Output
[php]
php tutorialshello world

This is to join strings

php tutorials best site
[/php]
Return to Top

Splitting Strings

Function explode is used to split strings in php. It takes two inputs one is with criteria the string must be split and the input string.
Example
[php]

<?php

$txt = “Programming is fun”;

$pieces = explode(” “,$txt);

echo $pieces[0].”<br>”;

echo $pieces[1].”<br>”;

echo $pieces[2].”<br>”;

?>

[/php]
Output
[php]
Programming

is

fun

[/php]
Return to Top

How to find Length of String

Function strlen() gives you the Length of string.

[php]

<?php

$txt =”Hello”;

echo strlen($txt);

?>

[/php]

Output
[php]
5
[/php]

Return to Top

How to Get Substring of String

The function substr() is used to get the substring of a string in php.
Usage is substr($sourcetext,start,length).

You have to give three arguments to the substr function.

1)$sourcetext — the text from which you want to get the substring

2)start — integer.. the no of character from which you want the string

3)length — how many character you want to pickup (this argument is optional).

Example
[php]

<?php

$txt = “Hello World”;

$string = substr($txt,7,4);

echo $string;

?>

[/php]
Output
[php]
Worl
[/php]

Second type of usage.

substr($sourcetext,start-index)
.
If you donot specify the legnth of substring to be selected the function automatically selects the substring starting from the start index to the end of the string.
Example
[php]
<?php

$text = “what are you doing”;

echo substr($text,6);

?>
[/php]

Output
[php]
re you doing
[/php]
Return to Top

Comparing two Strings in php

Use function strcmp to compare two strings in php.
Usage

[php]

strcmp($string1,$string2).

[/php]
Here we are comparting two texts $string1 and $string2.
The function returns zero if both of them are equal and non zero if both of them are not equal. This function is case sensitive.
If you are looking for case insensitive comparision you have to use function strcasecmp. The usage is same as that of strcmp function and it returns zero (0) if both strings are equal and non-zero values if they are not.

Return to Top

Search for a string in another string.

We use strpos for searching for one string in another string.
Usage

[php]
strpos($sourcestring,$texttobefound)

[/php]
Here $sourcestring is the string in which we are searching and $textobefound is the text for which we are searching for.
This function returns the postion of the first occurance of the string or text we are searching for. If the text is not found it returns boolean value FALSE.

Example
[php]

<?php

$source = “I am an Indian”;

$search1 = “am”;

$search2 = “noid”;

echo strpos($source,$search1);

echo “<br>”;

if(!strpos($source,$search2)){

echo “string is not present”;

}

echo strpos($source,”India”);

?>
[/php]
Output
[php]
2

string is not present
8
[/php]

Return to Top

Replacing Characters in a String

We use function str_replace to replace a sequence of characters in a string.

Usage is

[php]

str_replace($search,$replace,$string)

[/php]

Here $search is the sequence of characters for which we want to replace in the string. $replace is the sequence of characters with which we want to replace the $search. $string is the text in which we want to make the changes.

Example
[php]

<?php

echo str_replace(“i”,”x”,”Aerospace is one of growing industries”);

?>

[/php]
Output is
[php]
Aerospace xs one of growxng xndustrxes
[/php]
Here we are replacing ‘i’ with ‘x’. This replacement is case sensitive. If you are looking for case insensitive function use str_ireplace.

Return to Top

Functions to change Case

The following functions are genreally used to convert strings from one case to other.

All of the below functions returns the string after making appropriate changes. You must rewrite the original string value with the changed one like $stringtoconvert = ucwords($stringtoconvert)
[php]
ucwords($stringtoconvert)— Capitalizes first alphabet of every word in the string or text

ucfirst($stringtoconvert)— Capitalizes only first alphabet of string
strtolower($stringtoconvert)— Converts all alphabets to small.

strtoupper($stringtoconvert)— Capitalizes every alphabet in the string.

[/php]

Return to Top

Categories
php

Php Function To Count No of Rows In a Table

Occasionally you bump into a situation where you have to count the no of rows in a table in database.

There is one quick n dirty method to do that..

$noofrows = mysql_num_rows(mysql_query("select * from table"));

This method is inefficient and wont show errors while executing.

Alternatively you can use a  function which returns the no of rows in the table.. it takes table name and db connection handle as input and returns the row count or number of rows present in that table. Most of the time i use this function in pagination scripts.

function getnoofrows($table,$con){
  if($result = mysql_query("select count(*) as rowcount from table",$con)){
    $row = mysql_fetch_array($result);
    return $row['rowcount'];
  } else {
    //show MySQL error
    die(mysql_error());
  }
}

usage:

$noofrows = getnoofrows($table,$con);
Categories
php

Singleton Database Class for Beginners

What is A Singleton Class?

Singleton class is a class for which there exists only one object instance during the run time of the script (in php).

What is the use of singleton class?

It prevents the wastage of resources, if you have already established a connection to the database it retrieves that instance which already exists and reuses it. So there is no need to open a new connection.

How singleton class works?
First it searches for any object instance in the the run time of the script and returns it. If there is no object instance of this class it creates a new one…

Here is the database class which i normally use in my projects..
[php]
class Database{
// Store the single instance of Database
private static $instance;
private static $con;
private function __construct() {
//setup database.
//echo “constructor called”;

// use your server name , sql username and password db name here

$this->con=mysql_connect (“host”, “user”, “password”);
mysql_select_db (“database”,$this->con);
}
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new Database();
}

return self::$instance;
}
public static function closeInstance()
{
if (!(!self::$instance))
{
$inst = self::$instance;
mysql_close($inst->con);
}
}
// Function to run query
public function query($sql)
{
//echo “query run”;
return mysql_query($sql,$this->con);
}
}

[/php]
Usage:
Call a class using

[php]$db = Database::getInstance();[/php]

Query database

[php]$result = $db->query(‘sql statement here’);[/php]

Close Db Connection

[php]Database::closeInstance();[/php]

Thats all for now about the database class.. you no need to know how it works to use it but you need to study if you want to develop this.

Categories
php

List of Php Resources

This is the list of websites that are useful for learning php and has useful info for beginners. By the way the best method to learn php is to create a website yourself..

Tutorial Websites

  1. Php.net
  2. W3 Schools Php Section
  3. Tizag Php
  4. Php Freaks

Scripts Websites

These website have php scripts that of great use for all of you.

  1. Php Scripts
  2. Php Resource Index
  3. Php Classes Org

This list will grow. Please submit a new site or link  in the comments.

We will add after checking them.

Categories
php

PHP Function to list contents of a directory

Many times you need to get the list of contents of a directory in php scripts. You can get list of files and directories in a directory by using following function. It returns the list of items as an array.
[php]
function getdirlist($dir){

return array_diff( scandir( $dir ), Array( “.”, “..” ) );

}

[/php]
This function works in php5 environment only.

But if there are too many files in the folder you can use the below function to list each of them.

[php]

function getlist($directory){
$results = array();

// create a handler for the directory
//$directory=”.”;
$handler = opendir($directory);

// keep going until all files in directory have been read
while ($file = readdir($handler)) {

// if $file isn’t this directory or its parent,
// add it to the results array
if ($file != ‘.’ && $file != ‘..’){
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);

return $results;

}

[/php]

 

Categories
functions php

PHP: Function to replace pattern of characters in a String

The functions str_replace is used to replace particular sequence of characters in a string.
Usage
[php]
str_replace(find,replace,str)
[/php]
here
find –> sequence of characters to be replaced
replace –> sequence of characters with which it is to be replaced
str –> the string inwhich modifications must be done.

example
[php]
str_replace(“ad”,”br”,”google ads”);
[/php]
the out put will be
[php]
google brs
[/php]