PHP, Wordpress

Useful .htaccess Tricks for WordPress

PHP Developers and WordPress developers some times comes across .htacess file.
this file is configuration file for for security and performance. here i will show few usefull tricks to do with .htacess file. This file is located at root of your website (/public_html/)

Before we start lets grab the .htacess file from FTP and keep one backup (Just for fail safe).
if you dont have any .htacess file in your root folder under public_html.

Protect

  1. Protect wp-config.php file
    1. It was most important to protect your wp-config file because it has all the information about your database. if anyone get this file they can easily connect to our data base. Here  is the code for protecting wp-config.php file
      <files wp-config.php>
      order allow,deny
      deny from all
      </files>
    2.  Protect wp-admin folder
      you can easly genarate login protect for wp-admin folder here is the link how to do it
      http://www.htaccesstools.com/htpasswd-generator/

Read More...

FAQ, PHP, PHP

PHP interview questions and answers

1)    What does a special set of tags <?= and ?> do in PHP?

2)    What’s the difference between include and require?

3)    I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

4)    Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?

5)    How do you define a constant?

6)    How do you pass a variable by value?

7)    Will comparison of string “10” and integer 11 work in PHP?

8)    When are you supposed to use endif to end the conditional statement?

9)    Explain the ternary conditional operator in PHP?

10) How do I find out the number of parameters passed into function?

11) If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?

12) What’s the difference between accessing a class method via -> and via ::?

13) Are objects passed by value or by reference?

14) How do you call a constructor for a parent class?

15) What’s the special meaning of __sleep and __wakeup?

16) Why doesn’t the following code print the newline properly?

17) Would you initialize your strings with single quotes or double quotes?

18) How come the code <?php print “Contents: $arr[1]”; ?> works, but <?php print “Contents: $arr[1][2]”; ?> doesn’t for two-dimensional array of mine?

19) What is the difference between characters 23 and x23?

20) With a heredoc syntax, do I get variable substitution inside the heredoc contents?

 

 Just press Like button to download Answers

 

Read More...

PHP

PHP Arrays

  1. An array is a concept of declaring a variable in which multiple values can be stored or
    An array stores multiple values in a single variable..
  2. an array in PHP is compound type.
  3. An array is actually an ordered map.
    A map is a type that maps values.
  4. Each element in array has its own index.
  5. It takes a certain number of comma separated Key =>value pairs
    Syntax:-
    Array(key=>value, key=>value, . . .)

Count(Array_name)

  1. It is a function of PHP used to get the size of an array
  2. The size of an array is number of elements present in the array

Ex: count($x)

Print_r (array_name)

It is Function used to display the entire content of array with key.

 

We have 3 types of arrays in PHP

  1. Numeric array
  2. Associative array
  3. array

Numeric Array

Numeric stores the each array element with a numeric index.

In PHP we have 2 techniques to create a array.

  1. Assign index automatically
    Ex:-
    $x = array(10,20,30,40)
  2. Assign index Manually
    $x = array();
    $x[0]=10;
    $x[1]=20;
    $x[2]=30;
    $x[3]=”psd2web”;

Loops in arrays

Foreach loop:-

  1. For each loop gives an easy way to iterate over arrays.
  2. foreach works only on arrays and objects.

Syntax 1 of foreach :-

foreach (array as $value)

{
Statements
}

for every iteration the value of current array element is assigned to $value and the array  pointer is moved to next element so on ..
On the next loop iteration it will be looking at next array value.

Syntax2 for foreach loop

foreach (array as $key=> value)
{
Statements
}
This loop is also does the same thing , but except that the current elements key index will be assigned to the variable $key on each loop iteration.

<? PHP
$x=array(10,20,30,”psd”,123.45);
Echo “size of array is “.count($x).”<br>”;
print_r($x);
echo”<br>”;
$y=array();
$y[0]=”html”;
$y[1]=”css”;
$y[2]=”PHP”;
echo”size of array is “.count($y).”<br>”;
foreach($x as $k=>$R)
echo$k.”=>”.$R”,”.”<br>”;
?>

Associative Array

  1. An array where each ID key is associated with a value is called assosiative array
  2. With assosiative arrays we can use the values as keys and assign values to them.
  3. when storing data about specific named values, a numerical array is not always the best way to do it.

Example :-

  1. $Ages = array(“x”=>20, “y”=>30, “z”=>40);

  2. $ages = array();
    $ages[“x”] = 20;
    $ages[“y”] = 30;
    $ages[“z”] = 40;

In the both of above examples the values in the variable remains same but we used different ways to store the data.

if you do not specify a key for given value then the maximum of integer indices is taken till there, and the new key will be that maximum value+1.

if you you specify a key value that already assigned that value will be overwritten.

Multi dimension array:

An array containing one or more arrays in a multi dimension at array, each element in the main array can also be an array and each element in the sub array and so on..

if you want to remove a value from the array you need to use the function unset();
syntax: unset($age[‘x’]);

Read More...

PHP

Data Types and Built in functions

PHP supports 8 data types

  1. scalar data types( A variable in which only one value can be stored at a time
    1. Boolean
    2. integer
    3. Float / Double
    4. String
  2. Compound data type (A variable in which multiple values can be stored)
    1. Array
    2. Object
  3. Special data types
    1. resource
    2. Null

The type of variable is not set by the programmer, rather it is decided at run type byPHP depending upon the context in which the variable is used.

Var_dump (Var_name):-

it is built in function of PHP used to getting the type of variable with content of variable

<?PHP 
$X= 10; 
var_dump($X); 
echo" <br>” 
$X= 10.65; 
var_dump($X); 
echo" <br>” 

$X= "PSD"; 
var_dump($X); 
echo" <br>” 

$X= true; 
var_dump($X); 
echo" <br>”

The output Will be :-
int(10)
float(10.65)
string(3)(PSD)
bool True

Gettype(var_name):
It is also an Built in function in PHP it is used to get the type of variable.

<?php
$a=10;
$b=11.23;
$c="PSD";
$d=true;
echo gettype($a)."--".gettype($b)."--".gettype($c)."--".gettype($d);
?>

The output will be :

integer--double--string--boolean

Settype(var_name)
It is also an Built in function in PHP it is used to change the type of variable.

<?php
< ?php $a=10; settype($a,"integer"); echo $a ."--".gettype($a); ?>

The output will be :
10--integer

I will explain about notice error in the next class

Unset(var_name)
It is also an Built in function in PHP it is used to removing the content from variable.

<?php
< ?php
$a="psd";
echo gettype($a)."
";
unset($a);
echo gettype($a);
?>

The output will be :
string
NULL

Read More...

PHP

variables and output statements in PHP

We have 2  functions for output in PHP those are echo() and Print ()

actually output statements used to send output to the client (browser)

differences between echo() and print() are

  1. echo() is faster than print() in execution
  2. print() is return an integer value where echo() dosent return a value

in PHP the semicolon (;) is used to separate the two statements or scripts in PHP

Comments in PHP

In PHP, we use // or # to make a one-line comment

/* and */ to make a comment block:

Variables in PHP

  1. variables are used used to store values like text, string, numbers,arrays,objects, etc..
  2. when a variable is set it can be used again and again in PHP program.
  3. all the variables in PHP starts with $.
  4. in PHP an variable dose not need to be declare before it being set.
  5. it is not necessary to tell PHP which data type is the variable.
  6. PHP automatically converts the variable into correct data type depending on the situation where it was being used.

Example:

<?php
$a=”abc”;
$b=”xyz”;
$c=”$a+$b;
echo $c;
?>

output will be “abcxyz”

Variable naming rules

  1. A variable name can have alphanumeric characters and underscore “_”.  That is all alphabets and numbers from 0 to 9.
  2. A variable name should start with a letter or “_”. We cant use number at starting of variable name.
  3. No spaces are allowed in variable names.
  4. variable names are case sensitive.
  5. It is advised not use the reserved keywords  of PHP as a variable name.Example : $firstname, $ last_name, $_age
  6. Dot operator (.) is concadination operator in PHP
<?PHP
$firstname = “PSD”;
$lastname = “WEB”;
$_con = “2”;
echo $firstname.”—“.$_con.”—“.$lastname.”<br>”;
echo “$firstname.—.$_con.—.$lastname.<br>”;
echo ‘$firstname.—.$_con.—.$lastname.<br>’;
?>

Note:If we a variable in double quotes (“ ”)self expansion of the variable will happen where the memory usage is more so we should not use variable in double quotes(“ ”)

 

“$firstname”  don’t use these type

Read More...

PHP

Operators in PHP

Operators are used to perform some operations on data operators are broadly classified into 2 categories

  1. Unary operators
    An operator  that requires only one operant in unary operator.
    Ex: $a++
    in the above statement a is operant and ++ is operator
  2. Binary Operator
    An operator that require two operant is called as binary operator.
    Ex: $a+$b

We have 8 types of operators in PHP those are

  1. Arithmetic operators
    1. +
    2. *
    3. /
    4. %
    <?php    
    echo(10/3)."<br>";
    
    echo(10%3)."<br>";
    echo(-10%3)."<br>";     
    echo(10%-3)."<br>";
    
    echo(-10%-3)."<br>";
    
    $a=5;
    $b="psd";    
    $c=$a+$b;      
    echo $c;      
    ?>
    the output is 
    
    3.3333333333333
    1
    -1
    1
    -1
    5
  2. Assignment operators
    1. =
    2. +=
    3. -=
    4. *=
    5. /=
    6. %=
    7. .=
    <?php
    $a=($b=4)+5;
    echo $a."
    <?php
    $a=($b=4)+5;
    echo$a;
    echo$b;
    ?>
    The output is

    9
    4

  3. increment and decrement Operators
    1. ++(increases value by one)
    2. –(Decrease value by one)
      <?php
            
      $x=10;      
      echo $x++."--".++$x;      
      ?>
      
            
      Output is      
      10--12
  4. Relation operators
    1. <
    2. >
    3. <=
    4. >=
    5. == (will check only for content is same or not)
    6. !=
    7. <>
    8. === (will check content and type of content also)
    9. !==
  5. Logical operators  (it was used to frame a compound condition)
    1. &&
    2. ||

      In case of logical operators all the expressions will not be evaluated every time . It is based on the result of first condition.(($a>$b)&&($a>$c))

       

  6. Negation operators

    it used to multiply a number with “-“ operator$a=10;

    $b=-$a;

  7. Error Control operators  (@)

    when prepended with an expression, any warning messages that is being generated will gets suppressed.

  8. Bitwise operators

    Bit wise operators are 3 they are

    1. AND –&
    2. OR    — |
    3. XOR  — ^

      In this case bit wise operators both operant will converted to binary form and corresponding bitwise operation will be performed.

  9. Shift Operators
    1. Left Shift operator (<<)
    2. Right shift operator (>>)

      In this case of shift operators the first operant will be converted to binary form and corresponding shifts will happen based on second number of operant.EX:–

      echo (100>>2);

      echo (100<<2);

      output will be

      25

      400

  10. String / Concadination operator
    1. .
    2. .=
  11. concadination / ternary operator
    1. ?:
  12. Type operator
    1. “insaneof”
  13. New Operator
    1. new
  14. Scope operator
    1. ::
  15. De-referencing operator
    1. ->

Read More...

PHP

Introduction to PHP

Hi Guys

Let me teach about PHP in easy steps. First of let me explain what is Programing Language.

“ A Programing language is artificial language used to express  computer that can be performed with a machine, particularly Computer.”

  1. PHP is recursive acronym stands for  Personal Home Page, it is now said to stand for PHP: Hypertext Preprocessor
  2. PHP Is used for developing 3 types of applications
    • Command Line scripting
    • Desktop (or) GUI
    • Web Applications
  3. The main purpose of introducing PHP is to develop Web applications.
  4. PHP programs saved with an extension of .PHP
  5. Actually all the web applications runs in an request and respond mechanism (or) client server mechanism.
  6. The Programs which present in the client machine are sending requests to the server and getting response from server is called client side programs.
    examples: Firefox, Chrome, Internet explorer
  7. All the PHP programs gets executed in server and will give a response back to the client (Browser) in pure HTM format.
  8. Every PHP program contains HTML Tags plain text and PHP scripts.
  9. A web server is an application running in the server machine.
  10. PHP programs can be Placed in most of web servers.
    Example: IIS, ApacheNGINX
  11. PHP can run almost any Database.
  12. PHP is platform independent.
  13. At the time of PHP script execution in webserver the PHP script converts into “opcode” (Operational code) and send it to interpreter.
  14. The PHP interpreter is ZEND it is also called PHP parser.
  15. This Interpreter converts the “opcode” to HTML.
  16. For more details about History Click here for Wikipedia.
  17. On Next Class we will discuss about Instalation of PHP.

Read More...

PHP

Installing PHP in local system with XAMPP

HI guys

If we want work with PHP we need following products in our system .

  1. PHP
  2. Database server
  3. mail Server
  4. FTP client (Used to upload and download the content to the server)
  5. A tool for remote Database administration.

The following installers can be used to install all the above products in our system.

  1. WAMP (WINDOWS, APACHE, MYSQL, PHP )
  2. LAMP  (LINUX, APACHE, MYSQL, PHP)
  3. MAMP (MACINTOSH, APACHE, PHP)
  4. XAMPP ( X PLATFORM, APACHE, MYSQL, PHP)

 

The above listed are different installers different operating systems.

in our case we are selecting XAMPP in this X means any operating system. (i am using windows operating system)

To download go the following URL

http://www.apachefriends.org/en/xampp-windows.html#641

and select the installer, by the time of publishing the XAMPP version is 1.8.0

Installing XAMPP

Double click on Downloaded file

Select language  Press OK

Select NEXT

Select the installation Folder, by default it will create a folder “XAMPP” in your operating system drive as shown above

In the next screen it will shows the options as shown like above

  1. Create desktop Icon (it is recommended )
  2. Create Apache Friends XAMPP folder in Start menu (It is also recommended )
  3. Next service section (SERVICE SECTION) If you select any one of them they will start automatically at the time of windows boot it is not preferable better don’t select
  4. Press Install

Now the XAMPP is going to install. it will take little time as per your system environment.

 

 

After the Installation complete XAMPP will ask for to start the Control Panel

Press yes you will get screen like above.

 

Ok Guys now the XAMPP has installed successfully on your system. to check this

start the APACHE  server by clicking on the “Start” button shown in the below image 

 

Now go to your browser and type as below

http://localhost/

now you will get the XAMPP default page.

OK GUYS IT WAS WORKING.

If you have problem to start the apache server

Check your System has Skype, Teamviewer, Oracle, or any testing tool softwares , if you found any softwares try to uninstall those

because apache by default runs in in port 80, i want to change it to 8082

If you dont want to uninstall and the softwares then change the port number for apache.

to do this follow this simple steps

Open c:\xampp\apache\conf\ open “httpd.conf” file with text editor (notepad)

search for the word which mentioned “Listen :80”

change the “listen 80” to another number Like “listen:8082

and also change the “ServerName localhost:80″ to “ServerName localhost:8082”

now save the “httpd.conf” file and restart the apache server

go to your web browser type “localhost:8082

now you will get XAMPP page it will ask for language selection

select your language and you will get xampp page it will shows the xampp version, PHP version , … it was installed

 

Read More...

PHP

Conditional Statement

Everybody knows how the Statement works in programing languages as PHP developed from C language lets directly go for sample programs.

We have 4 Conditional Statement in PHP they are

  1. Switch statement
  2. IF statement
    1. Simple If
    2. IF – else
    3. IF – elseIF – else
    4. Nested IF

Switch Statement:-

<?php

$X=”a”;

switch ($x)

{

Case “a”;

echo “A”;

break;

Case “B”;

echo “B”;

break;

Case “c”;

echo “C”;

break;

Default:

echo”D”;

}

?>

output will be

A

Control statements (or) Loops

  1. while loop
  2. do while loop
  3. for loop
  4. for each loop

While Loop:-

Write a program for to display the first 10 natural numbers ?

<?php

echo “The first 10 natural numbers are”.”<br>”;

$x=1;

while($x<=10)

{

Echo $x.”<br>”;

$x++;

}

?>

The first 10 natural numbers are

1

2

3

4

5

6

7

8

9

10

and now just check the below program what will be the out put.

<?php

$x=1;

while($x++<=5);

echo $x.”<br>”;

?>

predict what will be the output of the Program ????

Output will be

7

Excersises

  1. Write a program to to display first 10 even numbers ?
  2. Write a program to to display the multiplication table as shown below ?

    5 * 1 = 55 * 2 = 10

    upto

    5 * 10 = 50

  3. Write a program to to display odd numbers between x and y ?
  4. Write a program to to display to display reverse of a number ?

    ex: if we taken input “1234” the out has to be “4321”

  5. Write a program to to display numbers in words ?

    ex: if we taken number as “1234” the out has to be “ one two three four”

Read More...

PHP

Local and Global variables in PHP

Local variable:

  1. A variable which is specified in a function is known as local  variable.
  2. local variable is accessible only with in the function where it was declared.
  3. the life time of a local variable is with in the function.

Global Variable:

  1. A variable which is specified outside of a function is known as global variable.
  2. Global variable can be accessed anywhere in the program.

$_GLOBALS:

It was an built in multi dimension array in php that stores GETDATA,POSTDATA, cookies, uploader files, error messages occurred in execution and also stores global variables.

The variables present inside $_GLOBAL is called global variables.

Syntax:  $_GLOBALS[‘x’]

global:

Global is keyword of php used for declaring a global variable , a variable declared by using keyword global cant be initialized.

Example:

<?php
$x=10;
function fun()
{
$y=20;
$GLOBALS[‘y’]=20
global $z;
$z=30;
}
echo $x.”—”.$y.”<br>”;
fun();
print_r($GLOBALS);
echo <br>;
echo $x.”—”.$y.”—”.$z;
?>

Read More...

PHP

PHP Class abstraction and Interfaces

Class Abstraction
=================

PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

<?php
abstract class AbsClass
{
public $a=10,$b=20;
function addNum($x=0,$y=0)
{
echo "Sum = ".($x+$y)."<br>";
}
abstract function subNum($x=0,$y=0);
}
?>
<?php
class AbsImpl extends AbsClass
{
function subNum($x=0,$y=0)
{
echo "Diff = ".($x-$y);
}
}
?>
<?php
echo "<h1>";
$obj=new AbsImpl();
$obj->addNum(10,20);
$obj->subNum(11,22);
?>

Interfaces
==========

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

interface Inter1

{

}

Read More...

PHP

PHP String handling functions

we have a lot of php predefined constants for string handling. lets have a look on few of them

  1. strlen()
    this function was used to find the length of the string.
    Syntax: strlen(variable name)
  2. str_replace()
    used to replace a part of string with another string.
    Syntax: str_replace(search,replace,[number of replaces])
  3. str_ireplace()
    It was same as str_replace but it was case sensitive.
    Syntax: str_replace(search,replace,[number of replaces])
  4. trim()
    it was used to remove the empty space on both sides of a string
    Syntax: trim(variable name)
  5. strrev()
    It is used to reverse the string
    Syntax: strrev(variable name)
  6. strstr()
    it is used to search the first occurrence of string inside another string.
    Syntax: strstr(search, replace)
  7. stristr()
    same as strstr() but it was case sensitive.
    Syntax: strstr(search, replace)
  8. nl2br()
    Used to add line breaks (<br>) inside a string in place of  \n or \r
  9. str_split()
    used to split the string into an array
    Syntax: str-split(string [,length])
    lenghth is an optional, each character is stored as an array element default is 1.
  10. substr()
    used to collecting a part of String.
    syntax: substr(string, start index,[length])
  11. substr_count()
    for count occurrence of substring in main string
    syntax: str_count(string,substring,[start position],[length])
  12. str_repeat()
  13. used to repeating a string number of times.
    syntax: str-repeat(string, repeat count)
  14. strtolower()
    convert the string into lower case of alphabet.
    syntax: strtolower(string)
  15. strtoupper()
    convert the string into upper case of alphabet.
    syntax: strtoupper(string)
  16. strcasecmp()
    it was used to case insensitive comparison. this function returns “0” if both strings are equal otherwise it will return the numerical difference between first non matching characters.
    The value wil be +ve or -ve
    syntax:  strcasecmp(string1,string2)
  17. strcmp
    It was same as strcasecmp but it was case sensitive.
    it will return 0 if both are equal
    it will return 1 if string1>string2
    it will return -1 if string1<string2
  18. str_pad()
    it was used to add extra padding with specified length to the string.
    Syntax: str_pad(string,length,[pad string][pad_type])
    where PAD_TYPE is a constant of php it will be either of the php
    STR_PAD_LEFT(0)
    STR_PAD_RIGHT(1)
    STR_PAD_BOTH(2)
Example :

<?php
$x="psd2web ";

echo $x."<br>";
echo strlen($x)."<br>";
//echo str_replace(k,kk,$x)."<br>";
$str=" sunil \n kumar";
echo trim($str);
echo strlen($str)."<br>";
echo strrev($str)."<br>";
echo $z=$x.$str."<br>";
echo strstr($x,"i")."<br>";
echo nl2br($str)."<br>";
$k=str_split($x);
echo print_r($k)."<br>";
echo substr($x,3)."<br>";
echo substr_count($x,"u")."<br>";
echo str_repeat($x, 10)."<br>";
echo strtoupper($x)."<br>";
echo strtolower($x)."<br>";
echo strcmp("Sunil", "sunil")."<br>";
echo strcasecmp("Aunil", "Cunil")."<br>";
$new= str_pad($x,5);
echo $new.$x;

?>

more string functions…

Read More...

PHP

PHP reverse a number

PHP program to print a number in reverse order

<?php
$num=123456789; // Give the number which you want to print in reverse order
echo $num;
echo "<br>";
$revnum=0;
do{
 $revnum=($revnum *10)+($num % 10);
 $num=(int)($num / 10 );
}while($num>0);
echo $revnum;
?>

Read More...