Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Php Validation | Form Validation in php

To validate the input provided by the user from form is a common requirement now days. For example, it must be check

1. mandatory fields must be properly filled
2. age must contain numeric value
3. email provided by user must be a valid email
4. Date of Birth must be a valid date.

These are just examples to tell you how the data of the form should be validated.
Most of the web developer just uses javascript to validate the form data. Javascript is a client side language and interpreted on client's computer and it is interpreted by web browser such as Internet Explorer, Firefox, Opera, Google Chrome, etc. If javascript code is properly written to validate the form data then user cannot go to next page unless he/she provides the correct data. But javascript has a major drawback and its drawback is IF JAVASCRIPT IS DISABLE IN WEB BROWSER THEN USER CAN ENTER ANY VALUE WHAT HE/SHE WANTS AND YOUR DATABASE CAN BE DEMAGED DUE TO THE DATA PROVIDED BY THE USER. So it is better to validate the form data by using client side language(javascript) as well as server side language such as PHP, so incase if javascript is disable then server side validation prevents the user to enter the wrong data and restrict user to provide valid data.

Form Validation in php

I am going to develop a php page that just contains a form and after hitting the submit button I will validate the data provided by user using PHP.



Form Validation






























First Name
Last Name
Email Address
Username
Date (mm/dd/yy)
Age




action attribute of form(action="verify.php") contains the name of the web page in which i have written php code to validate the form data. Here's the code to validate the form data.

Verify.php

$fname=trim($_POST['fname']);
$lname=$_POST['lname'];
$email=trim($_POST['email']);
$age=trim($_POST['age']);
$date_user=trim($_POST['date_user']);
$username=trim($_POST['username']);
$age_len=trim(strlen($age));

if(empty($fname))
{
header("location:form.php?msg=pleaseenteremail");
}

//Now email validation using Regular Expressions
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
header("location:form.php?msg=emailnotvalid");
}

//Now performing numeric data validation for Age Field
if(!is_numeric($age))
{
header("location:form.php?msg=agenotvalid");
}

//Now checking the length of the data provided by user as his/her age
if($age_len>3)
{
header("location:form.php?msg=agenotvalid");
}

//Now performing Date Validation for Date Field
$arr=split("/",$date_user); // splitting the array
$mm=$arr[0]; // first element of the array is month
$dd=$arr[1]; // second element is date
$yy=$arr[2]; // third element is year
if(!checkdate($mm,$dd,$yy)){
header("location:form.php?msg=datenotvalid");
}

?>
trim() function is used to remove the spaces before and after the data.
empty() function is a Boolean function that checks whether the data in the form of its argument is empty or not?
is_numeric() function is also a Boolean function that returns whether the data in the form of its argument is numeric or not?
strlen() function provides the length of the string.
checkdate() function is a built in function that checks whether date provided is valid or not. It also takes care of leap year checking. It is also a Boolean function and return true if date is correct and return false if date is false.
Now let's understand the code that is performing validation of form data.
First of all I am getting form data using $_POST because form data coming from previous page is using the post method. Then i remove extra spaces to the form data by using trim() and assign that data to the different variables.

$age_len=trim(strlen($age));
for checking the length of age data, i first of all remove the extra spaces before/after the age data provided by the user and then check the length of age data using strlen() function.

if(empty($fname))
{
header("location:form.php?msg=pleaseenteremail");
}
Then i check whether the first name is empty or not. If empty then returns to the prevous page with a query string that indicates the error.
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
header("location:form.php?msg=emailnotvalid");
}
To validate email address, i use regular expression. Again if email is not a valid email then I redirect page to the previous page with a query string.

if(!is_numeric($age))
{
header("location:form.php?msg=agenotvalid");
}
To check whether age provided is numeric or not i use the is_numeric() function because age can be numeric like 23 not the characters abc.
To perform date validation i use the built in php Boolean function which is checkdate() that takes three arguments which is month, day and year. Now its up to you whether you provide date like this way 02/10/09 or like this way 02/10/2009, this powerful built in function can validate both form of dates. To get month, day and year from the date provided by the user I use split() function to split the date and get the month, day and year and then provide these three to checkdate() function to validate the date.
So this is a practical example to perform form validation in php.

How to solved column error in php | Out of range value adjusted for column error in php

To avoid this error Out of range value adjusted for column there are possible three solutions but I prefer solution 1 and solution 2.

Solution 1

Use functionality of SQL_MODE

Just Login to the mysql shell and use this command to avoid the error

SET GLOBAL SQL_MODE=”;

It will fix your problem.

Solution 2

Modification in insert query

Sometimes our website hosting company (incase if website is hosted by website hosting company) doesn’t give us permission to use SQL_MODE or sometimes we want to quicker solve this error without contacting the hosting company of our website then use insert query like this

$sql="insert into student values('Adeel', 'Fakhar')";

Instead of $sql="insert into student values('', 'Adeel', 'Fakhar')";

How to use stripos function | strpos and stripos function to perform search process on strings in php

By default php has a function strpos that searches string within a string. Sometime during development of website in php you might need to search for a phrase within a string then using this built-in strpos function you can perform search process easily.

Sometimes you may want to check existence of something within a string so that after confirming whether it exists or not you will apply some condition in your code. This is just a scenario now it’s up to you where you will use this strpos function.

Let’s have a look over example given below to see the use of strpos function in php.

$string_to_search="Adeel Fakhar";
$sentence="Hello every body, wish you all best of luck, Regards, Adeel Fakhar";

if(strpos($sentence, $string_to_search))
{
echo "$string_to_search exists inside $sentence";
}
else{
echo "not found";
}
?>


This is just an example you can directly assign the content coming from database to the $sentence variable and then perform your search process using this built-in php strpos function.

Now there is a drawback of strpos function and its only drawback is that it is case sensitive. Means if you want to search “Adeel Fakhar” within “Hello every body, wish you all best of luck, Regards, Adeel Fakhar” then it will work fine but if you will search “adeel fakhar” within ”Hello every body, wish you all best of luck, Regards, Adeel Fakhar” then strpos is unable to find this, to get rid of this case sensitivity issue we have a built-in php function stripos that works same like strpos but additionally it is case insensitive. Let’s have a look over example given below

$string_to_search="adeel fakhar";
$sentence="Hello every body, wish you all best of luck, Regards, Adeel Fakhar";

if(stripos($sentence, $string_to_search))
{
echo "stripos function works";
}
else{
echo "not found";
}
?>

In the above example it will print stripos function works.

So this is the way to perform search process of a string within a string in php using strpos and stripos.

Find random numbers in php | Generating random numbers in php

$Random_number=rand();

echo $Random_number;

?>

When you run this php script, every time you will get a random number but what about if you want to get random number within a range???? To get a random number within a range is also a quite easy method just you need to pass the two arguments to the rand() function. First argument will be the starting number of the range and second argument will be the ending number of the range, now every time you will get a random number that will lie in this range, let’s have a look over example to clearly understand what I try to explain

$Random_number =rand(1,5);


echo $Random_number;

Now some time you will get 1, some time 2 and some time 3, etc. It will not give you any number less than 1 or greater than 5
So this is the way to generate random numbers in php.

How to increase PHP performance | PHP performance tips and tricks

1) Don't use varaibles when there is no need of them

Most of the times the php developer try to clean his/her code by assigning the values of predefined variables to the variable created by him/her of shorter name. This can also become the way of better understanding of php code but it double consume the memory without any need becuase first you will declare the variable and then you will assign the values of predefined variables to those custom variables. Let's have a look over the example to better understand what i mean.

Wrong
$comments=$_POST['comments'];
echo $comments;

Correct
echo $_POST['comments'];

In the above example if the malicious user had inserted the spam text in the comments textarea of 512KB worth of characters then it would use the memory of 1MB without any need.

2) Make habit to Use single-quotes for strings

In PHP you can use both single and double-quotes for string variables but there are some differences between both of them. Using double-quotes for strings tell the engine of php to first read the content of string and then look for variables and then replace variables with their values. So if the string contains no variable then please use single-quote instead of double-quote. Let's have a look over the example

Wrong
$name="My name is Adeel Fakhar";

Correct
$name='My name is Adeel Fakhar';

It is better to use concatenation then double-quotes for string. Let's have a look over the example

Wrong
$name='Adeel Fakhar';
$myname="My name is $name";

Correct
$name='Adeel Fakhar';
$myname='My name is'.$name.' Ok';

Make habit to use echo to print

Use echo to print the results in better readability and better performance.

Wrong
print $name;

Correct
echo $name;

I will also write a post for difference between echo and print.

Don't try to use the concatenation with echo

Most of the novice php programmers don't know that they can pass multiple variables to the echo, seprating with commas, instead of concatenating them first.

Wrong
$firstname='Adeel';
$lastname='Fakhar';

echo 'My name is'.$firstname.$lastname.' OK my dear';

Correct
$firstname='Adeel';
$lastname='Fakhar';

echo 'My name is',$firstname,$lastname,' OK my dear';

Try to use switch/case instead of if/else

If there is a single variable in your php code for comparison purpose then please try to use switch/case instead of if/else for better performance and readability. Let's have a look over the example

Wrong
if($_POST['action'] == 'sum')
{
sumFunction();
}
elseif ($_POST['action'] == 'sub')
{
subFunction ();
}
elseif ($_POST['action'] == 'mul')
{
mulFunction ();
}
else {
defaultFunction();
}
Correct
switch($_POST['action'])
{
case 'sum':
sumFunction();
break;

case 'sub':
subFunction ();
break;

case 'mul':
mulFunction ();
break;

default:
defaultFunction();
break;
}
It’s my suggestion to first understand the language, clear your logic then apply these above mentioned steps,techniques,tips and tricks, what ever you say to enhance the performance of your development. As you have seen that the tutorials I have written in my blog, I haven’t follow any of these techniques because my purpose was to solve your problem quickly rather than to teach you how to write code but in professional coding life you must follow these steps in order to enhance your development performance.
If you like this post of PHP performance tips and tricks then you must thankful to code.google.com because I have read these performance enhancement techniques there and then I decided to write a post for this on my blog.

File extension in php | Getting file extension in php

There are different ways to do this. Let's have a look over each of them


1) Using explode()

The simplest and easiest way of getting file extension is to use the php built-in function explode.

The explode() function breaks a string into an array.

It takes three parameters in which two of them are required and one is optional.

a) The first required parameter is separator that specifies where to break the string.
b) The second required parameter is string that specifies the string to split.
c) The optional parameter is limit that specifies the maximum number of array elements to return.

So let's have a look over how to get the file extension using explode() method.

$filename="picture.jpg";
$fileArray=array();
$fileArray =explode('.',$filename);
$file_extension=$fileArray[1];
echo $file_extension;
?>

or you can made a custom php function and call explode() method in it and in the end return the value

function get_file_extension($file_name)
{
return end(explode('.',$file_name));
}

$filename="picture.jpg";
$file_extension=get_file_extension($filename);
echo $file_extension;
?>

2) Using PATHINFO_EXTENSION

Another way to get the file extension is to use the pathinfo which is an array that contains dirname, basename, extension and file name. Right now we are only interested in the file extension so I am going to call it directly.

$filename="picture.jpg";
$file_extension = pathinfo($filename,PATHINFO_EXTENSION);
echo $file_extension;
?>

Or you can do like this

function get_file_extension($file_name)
{
return pathinfo($file_name, PATHINFO_EXTENSION);
}

$filename="picture.jpg";
$file_extension =get_file_extension($filename);
echo $file_extension;
?>

3) Using substring and string char

You can use substring and string char to determine the file name length and position to get the file extension. Let’s have a look over how to do this

function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}

$filename="picture.jpg";
$file_extension =get_file_extension($filename);
echo $file_extension;
?>

So these are the different ways to get the file extension in php.

How to Send email in PHP | Send email with CC and BCC in php

function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "CC: sombodyelse@gmail.com\r\n";
$headers .= "BCC: hiddenemail@gmail.com\r\n";
//set content type to HTML
$headers .= "Content-type: text/html\r\n";
if ( mail($to,$subject,$message,$headers) )
{
header("location:yourdesirepage.php?msg=sent");

}
else
{
header("location:yourdesirepage.php?msg=notsent");
}
}
//Function ends here
$from_email="fromyou@gmail.com";
$to_email="tosomeone@gmail.com";
$subject="Subject of Email";
$message.="";
$message.="Your message here will be look bold when visible to reader";
$message.="Some more message";
$message.="";
send_email($from_email,$to_email,$subject,$message);

In the send_email() function, i used two more headers CC and BCC to send email with CC and BCC in php.
1. $headers .= "CC: sombodyelse@gmail.com\r\n";
CC means Carbon Copy. A comma separated list of more recipients that will be seen by all other recipients.
2. $headers .= "BCC: hiddenemail@gmail.com\r\n";
BCC means Blind Carbon Copy. A comma separated list of more recipients that will not be seen by any other recipients.

Working with IP address in php | How to get the IP address in php

function getIpAddress()
{
if (trim($_SERVER['HTTP_CLIENT_IP'])!="") //checking ip address from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
else if (trim($_SERVER['HTTP_X_FORWARDED_FOR'])!="") //checking whether ip address is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}

$ip_address = getIpAddress(); // Get the visitor's IP Address
echo $ip_address;

The above code snippet first tries to get the direct IP address of visitor’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is not available too then it will finally get the IP address using REMOTE_ADDR. So that's it.

How to Redirect page in PHP | Redirection after some time delay in php

Use Header Function

  1. header("refresh:5;url=somepage.php");

Use Meta tag in echo or print statement

1. print "";

Write Comments in php | How to use comments in php

comments in php


comments are used to stop execution of thst line
commenst are two type
1) single coments
2)multiline comments

single line comments:- etp the execution of a single line

we are using # or // to comments

multilile comments

How to use ECHO Command in php

ECHO
php print using echo

This function can print multiple statement at once .
compare with print it is faster because it won't rerturns any value.

Tags in Php | How to use tags in php

php Tags


// universal style tag


short open tag

//asp style tag

<%

//php script
%>


// script type tag

By default Xampp 1.7.2 will not execute asp style tags and short open tags .Because php.ini we have to configuration direction related to this tags those are
1) Asp_tags , short_open_tags , the value of this tag is off by change this value to "ON" we can execute this tag.
If we change the value of php.ini , php.conf direction we have to save the files then restart the web server.


<%

print("asp style");
%>

How to use print_r in php with examples

Print_r:-
Used to display the all elements of an array properties of an object.
for example take a program

/*output
Array ( [0] => 10 [1] => 20 [2] => 30 )
*/

Errors in php with solutions

Notice : Notice is a message to the end user it won't stop the execution of the script .
ex:=if we are trying to acess undefined variables , then output is notice.
we can't see the notice on web page directly because in php.ini we have one configuration directives that is
erro_reporting, the value of this directive id is E_ALL
.
error_reporting_(e_all)

/*output
100
Notice: Undefined variable: b in F:\xampp\new\htdocs\php\var_dump.php on line 5
*?
but it will not stop the execution .


//error_reporting(E_ALL); put it into comments
$=100;
echo $a;
echo $b;
?>
/* output
100
*/

warning:-
warning message will not stop the execution of the script , if we are trying to access the undefined constant
the output is warning.


/*output

100 // executed
Warning: constant() [function.constant]: Couldn't find constant city in F:\xampp\new\htdocs\php\var_dump.php on line 4 // showing error
scott // executed
*/

Fatal error;

fatal error stops the execution of rest of the script if we are trying to call undefined function the output is Fatal error.

/*output
Executable line
From function 1 execution
Fatal error: Call to undefined function fun2() in F:\xampp\new\htdocs\php\var_dump.php on line 9
*/


fun2();
echo "firt executable line form function 1";
function fun1()
{
echo "From function 1";
}
echo (fun1());
?>
/*output
Fatal error: Call to undefined function fun2() in F:\xampp\new\htdocs\php\var_dump.php on line 2

Important Interview questions for Php

1,2,3...50 questions are there but that is equal to 500 Php questions

What are the differences between Get and post methods in form submitting, give the case where we can use get and we can use post methods?
Who is the father of PHP and explain the changes in PHP versions?
How can we submit a form without a submit button?
In how many ways we can retrieve the date in the result set of mysql using PHP?
What is the difference between mysql_fetch_object and mysql_fetch_array?
What is the difference between $message and $$message?
How can we create a database using PHP and mysql?
What are the differences between require and include, include_once?

What are the different tables present in mysql, which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10)) ?
Functions in IMAP, POP3 AND LDAP?
How can I execute a PHP script using command line?

some other technical important questions


Shopping cart online validation i.e. how can we configure Paypal, etc.?
What is meant by nl2br()?
Draw the architecture of Zend engine?
What are the current versions of apache, PHP, and mysql?
What are the reasons for selecting lamp (linux, apache, mysql, PHP) instead of combination of other software programmes, servers and operating systems?
How can we encrypt and decrypt a data present in a mysql table using mysql?
How can we encrypt the username and password using PHP?
What are the features and advantages of object-oriented programming?
What are the differences between procedure-oriented languages and object-oriented languages?
What is the use of friend function?
What are the differences between public, private, protected, static, transient, final and volatile?
What are the different types of errors in PHP?
What is the functionality of the function strstr and stristr?
What are the differences between PHP 3 and PHP 4 and PHP 5?
How can we convert asp pages to PHP pages?
What is the functionality of the function htmlentities?
How can we get second of the current time using date function?
How can we convert the time zones using PHP?
What is meant by urlencode and urldocode?
What is the difference between the functions unlink and unset?
How can we register the variables into a session?
How can we get the properties (size, type, width, height) of an image using PHP image functions?
How can we get the browser properties using PHP?
What is the maximum size of a file that can be uploaded using PHP and how can we change this?
How can we increase the execution time of a PHP script?
How can we take a backup of a mysql table and how can we restore it. ?
How can we optimize or increase the speed of a mysql select query?
How many ways can we get the value of current session id?
How can we destroy the session, how can we unset the variable of a session?
How can we destroy the cookie?
How many ways we can pass the variable through the navigation between the pages?
What is the difference between ereg_replace() and eregi_replace()?
What are the different functions in sorting an array?
How can we know the count/number of elements of an array?
What is the PHP predefined variable that tells the What types of images that PHP supports?
How can I know that a variable is a number or not using a JavaScript?
List out some tools through which we can draw E-R diagrams for mysql.
How can I retrieve values from one database server and store them in other database server using PHP?
List out the predefined classes in PHP?
How can I make a script that can be bilanguage (supports English, German)?
What are the difference between abstract class and interface?
How can we send mail using JavaScript?

Code to calculate Area, Square using php script

How to calculate Area and Perimeter of Rectangle ,Triangle , and Square.
Logic to develop Code in Php.

How to use sqrt in php.




echo"

RECTANGLE

";
$l=30;
$b=40;
$area=$l*$b;
$peri=2*($l+$b);
echo "AREA: ".$area."
";
echo "PERIMETER: ".$peri."
";

echo"

SQUARE

";

$S=30;

$peri=4*$s;

$area=$s*$s;
echo "AREA: ".$area."
";
echo "PERIMETER: ".$peri."
";

echo"

TRIANGLE

";

$s1=30;
$s2=40;
$s3=50;

$peri= $s1 + $s2 + $s3;

$s=0.5*$peri;
$area=sqrt($s*($s-$s1)*($s-$s2)*($s-$s3));
echo "AREA: ".$area."
";
echo "PERIMETER: ".$peri."
";

?>