Archive for April, 2010

Various PHP Programming Tricks-For Beginers

Posted: April 28, 2010 in Uncategorized

Various PHP Programming Tricks

I’ll be presenting a couple of nice PHP Programming Tricks in this page. You can take a look at the various tricks in these sub pages.

Force a secure HTTP connection
if (!($HTTPS == “on”)) {
header (“Location: https://$SERVER_NAME$php_SELF”);
exit;
}

Get the date
$today = getdate();
$month = $today[‘month’];
$mday = $today[‘mday’];
$year = $today[‘year’];

Random Loading
You can load random stuff by using this code. For this example, I load random color code:
$selectnumber = rand (1, 5);
if($selectnumber==1) $pagebg=”#990000″;
if($selectnumber==2) $pagebg=”#0000FF”;
if($selectnumber==3) $pagebg=”#00AAAA”;
if($selectnumber==4) $pagebg=”#000099″;
if($selectnumber==5) $pagebg=”#DDDD00″;

Easy Way to List Directory Structure
$path = “/home/user/public/foldername/”;
$dir_handle = @opendir($path) or die(“Unable to open $path”);

while ($file = readdir($dir_handle)) {
if($file == “.” || $file == “..” || $file == “index.php” )
continue;
echo “<a href=\”$file\”>$file</a><br />”;
}
closedir($dir_handle);

Easy Way to Optimize Database Table
dbConnect()
$alltables = mysql_query(“SHOW TABLES”);

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

Create a password protect webpage
<?
$username = “someuser”;
$password = “somepassword”;

if ($_POST[‘txtUsername’] != $username || $_POST[‘txtPassword’] != $password) {?>
<h1>Login</h1>
<form name=”form” method=”post” action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>
<p><label for=”txtUsername”>Username:</label>
<br><input type=”text” title=”Enter your Username” name=”txtUsername”></p>

<p><label for=”txtpassword”>Password:</label>
<br><input type=”password” title=”Enter your password” name=”txtPassword”></p>
<p><input type=”submit” name=”Submit” value=”Login”></p>
</form>
<?} else {?>
<p>This is the protected page. Your private content goes here.</p>
<?}?>

Reference: http://www.osdw.org/Various_PHP_Tricks.html

Using Stored Procedures in MYSQL

Posted: April 28, 2010 in Uncategorized

Hi All,

I am really very glad to post this article. To avoid/restrict SQL injection, you must protect your SQL Codes (Specially DML Statements). It is similar to PL-SQL in SQL SERVER or ORACLE, with a little difference in syntax only. As you know, a procedure can take IN, OUT and INOUT parameters. Also, can return one or more values. I am providing a sample code, hope, it will help you;

CREATE DEFINER=`root`@`localhost` PROCEDURE `spr_country`(to_do varchar(20),cid integer,cname varchar(150),rid integer,out msg varchar(250),out result integer)
BEGIN
#Declaring Vriables
declare i int;
declare error int;
declare old_country_name varchar(150);
set error=0;
#Checking if empty
if trim(cname)=” then
set error=1;
set msg=’Region Name is found to be Empty !’;
set result=0;
end if;
if trim(rid)=” or trim(rid)=’0′  then
set error=1;
set msg=’Region Name is found to be Empty !’;
set result=0;
end if;
#For Task=add
if to_do=’add’ then
#checking if already exists
set i=(select count(*) from master_country where trim(lcase(country_name))=trim(lcase(cname)) and region_id=rid);
if i > 0 then
set error=1;
set msg=’COuntry Name Already Exists !’;
set result=0;
end if;
#Saving If No error
if error=0 then
insert into master_country(country_name,region_id,update_date) values(trim(cname),rid,now());
set msg=’New Country Saved Successfully !’;
set result=1;
end if;
end if;
#Add Task COmpleted
################################################################################
#For task=modify
#Find DUplicate Record If Exists ?
if to_do=’modify’ then
set old_country_name=(select country_name from master_country where country_id=cid);
set i=(select count(*) from master_country where trim(lcase(country_name))=trim(lcase(cname)) and trim(lcase(country_name)) != trim(lcase(old_country_name)));
if i > 0 then
set error=1;
set msg=’Country Name Already Exists !’;
set result=0;
end if;
if error=0 then
update master_country set country_name=trim(cname),region_id=rid,update_date=now() where country_id=cid;
set msg=concat(‘Region Successfully Updated to : ‘,cname);
set result=1;
end if;
end if;
#Modify Task Completed
#####################################################################################
#delete task
if to_do=’delete’ then
set i=(select count(*) from user_registration where country_id=cid);
if i > 0  then
set result=0;
set msg=’Sorry ! Country can not be deleted. Country in use …..’;
else
delete from master_country where country_id=cid;
set result=1;
set msg=’Country deleted from the database successfully !’;
end if;
end if;
#####################################################################################
#delete all
if to_do=’delete_all’ then
set i=(select count(*) from user_registration);
if i>0 then
set result=0;
set msg=’Sorry ! Some COuntries are in use for User Registration.’;
else
set result=1;
truncate table master_country;
end if;
end if;
END

CREATE DEFINER=`root`@`localhost` PROCEDURE `spr_country`(to_do varchar(20),cid integer,cname varchar(150),rid integer,out msg varchar(250),out result integer)BEGIN
#Declaring Vriablesdeclare i int;declare error int;declare old_country_name varchar(150);set error=0;
#Checking if emptyif trim(cname)=” thenset error=1;set msg=’Region Name is found to be Empty !’;set result=0;end if;
if trim(rid)=” or trim(rid)=’0′  thenset error=1;set msg=’Region Name is found to be Empty !’;set result=0;end if;
#For Task=addif to_do=’add’ then#checking if already existsset i=(select count(*) from master_country where trim(lcase(country_name))=trim(lcase(cname)) and region_id=rid);if i > 0 thenset error=1;set msg=’COuntry Name Already Exists !’;set result=0;end if;
#Saving If No errorif error=0 theninsert into master_country(country_name,region_id,update_date) values(trim(cname),rid,now());set msg=’New Country Saved Successfully !’;set result=1;end if;end if;#Add Task COmpleted#################################################################################For task=modify#Find DUplicate Record If Exists ?if to_do=’modify’ thenset old_country_name=(select country_name from master_country where country_id=cid);set i=(select count(*) from master_country where trim(lcase(country_name))=trim(lcase(cname)) and trim(lcase(country_name)) != trim(lcase(old_country_name)));if i > 0 thenset error=1;set msg=’Country Name Already Exists !’;set result=0;end if;
if error=0 thenupdate master_country set country_name=trim(cname),region_id=rid,update_date=now() where country_id=cid;set msg=concat(‘Region Successfully Updated to : ‘,cname);set result=1;end if;end if;#Modify Task Completed######################################################################################delete task if to_do=’delete’ then set i=(select count(*) from user_registration where country_id=cid); if i > 0  then set result=0; set msg=’Sorry ! Country can not be deleted. Country in use …..’; else delete from master_country where country_id=cid; set result=1; set msg=’Country deleted from the database successfully !’; end if; end if;######################################################################################delete all if to_do=’delete_all’ then set i=(select count(*) from user_registration); if i>0 then set result=0; set msg=’Sorry ! Some COuntries are in use for User Registration.’; else set result=1; truncate table master_country; end if; end if;END

PHP-Interview Questions

Posted: April 6, 2010 in Uncategorized

Given a line of text $string, how would you write a regular expression to strip all the HTML tags from it?

$stringOfText = “<p>This is a test</p>”; $expression = “/<(.*?)>(.*?)<\/(.*?)>/”; echo preg_replace($expression, “\\2”, $stringOfText); ….!

How can you block certain IP Addresses from accessing your site?

<?php $banned = array(“24.91.102.173”, “64.21.162.113”); if (in_array($_SERVER[‘REMOTE_ADDR’], $banned)) { echo “You have been banned.”; exit; } ?>   ….!

which is faster mysql_unbuffered_query or mysql_query ?
when we do the select queries that retrieve large data sets from MySQL, mysql_unbuffered_query in PHP is likely to give better performance than mysql_query. PHP manual says, it “sends a SQL query query to MySQL, without fetching and buffering the result rows automatically”.
What is the difference between char and varchar data types?
Set char to occupy n bytes and it will take n bytes even if u r storing avalue of n-m bytes Set varchar to occupy n bytes and it will take only the required space and will not use the n bytes eg. name char(10) will waste 5 bytes if we store ‘testname’, if each char takes a byteeg. name varchar(10) will just use 5 bytes if we store ‘testname’, if each char takes a byte. rest 5 bytes will be free. ….!

What will be the following script output?
<?php$a = 1;$a = $a— + 1;echo $a;?> A. 2B. 1C. 3D. 0E. Null Answer B is correct. ….!
What is the functionality of md5 function in PHP?
Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. ….!
Is it possible to set a time expire page in PHP.?
Yes it is Using header(“Expires: Mon, 26 Jul 2007 05:00:00 GMT”); <?php header(“Expires: Mon, 26 Jul 2007 05:00:00 GMT”); ?>
What are the different functions in sorting an array?
Ans: asort() arsort() ksort() krsort() uksort() sort() natsort() rsort() ….!

What is meant by Session Clustering?
The Session Manager session support allows multiple server instances to share a common pool of sessions, known as a session cluster Session clustering setting up methods : #1)First methods, is to have a NFS shared where session will be store. Setting this is quite easy, just a little modification on php.ini file to change the “session.save_path ? directive to point to the NFS share. The main problem with NFS is on high traffic, NFS share is really slow. So synchronisation and data corruption can arrive and ….!

What is Phishing?

In computing, phishing is a form of criminal activity using social engineering techniques. It is characterized by attempts to fraudulently acquire sensitive information, such as passwords and credit card details, by masquerading as a trustworthy person or business in an apparently official electronic communication. Phishing is typically carried out using email or an instant message. The term phishing derives from password harvesting and the use of increasingly sophisticated lures to “fish” for users’ financial information and passwords.

How can we know that a session is started or not?
A session starts by session_start() function.
This session_start() is always declared in header portion. it always declares first. then we write session_register().

What are the differences between  mysql_fetch_array(),  mysql_fetch_object(),  mysql_fetch_row()?
Answer 1:
mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
mysql_fetch_object() -> Fetch a result row as an object.
mysql_fetch_row() -> Fetch a result set as a regular array().

Answer 2:
The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row[‘name’], $row[’email’], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).

If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?
Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.

What are the MySQL database files stored in system ?
Data is stored in name.myd
Table structure is stored in name.frm
Index is stored in name.myi

What is the difference between PHP4 and PHP5?
PHP4 cannot support oops concepts and Zend engine 1 is used.

PHP5 supports oops concepts and Zend engine 2 is used.
Error supporting is increased in PHP5.
XML and SQLLite will is increased in PHP5.

Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?
Yes we can include that many times we want, but here are some things to make sure of:
(including abc.PHP, the file names are case-sensitive)
there shouldn’t be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php

What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
mysql_fetch_array – Fetch a result row as an associative array and a numeric array.

mysql_fetch_object – Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows

mysql_fetch_row() – Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

What is meant by nl2br()?
Anwser1:
nl2br() inserts a HTML tag <br> before all new line characters \n in a string.

echo nl2br(“god bless \n you”);

output:
god bless<br>
you

How can we encrypt and decrypt a data presented in a table using MySQL?
You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:

AES_ENCRYPT(str, key_str)
AES_DECRYPT(crypt_str, key_str)

How can I retrieve values from one database server and store them in other database server using PHP?
For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database.