Warning: Cannot modify header information - headers already sent by (output started at /home/vire0207/public_html/blog/index.php:3) in /home/vire0207/public_html/blog/wp-includes/feed-rss2.php on line 8
Virendra Yadav http://virendrayadav.com/blog Tue, 21 Feb 2017 05:02:41 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.2 http://virendrayadav.com/blog/wp-content/plugins/squirrly-seo/themes/default/css/sq_feed.css Array in php http://virendrayadav.com/blog/array-in-php/ http://virendrayadav.com/blog/array-in-php/#respond Tue, 21 Feb 2017 05:02:41 +0000 http://virendrayadav.com/blog/?p=149

What is PHP Arrays

Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. Let’s suppose you want to store colors in your PHP script.

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
  • Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

NOTE − Built-in array functions is given in function reference PHP Array Functions.

Numeric Array

These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>
   <body>
   
      <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

This will produce the following result −

Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five 

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE − Don’t keep associative array inside double quote while printing otherwise it would not return any value.

Example

<html>
   <body>
      
      <?php
         /* First method to associate create array. */
         $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
         
         /* Second method to create array. */
         $salaries['mohammad'] = "high";
         $salaries['qadir'] = "medium";
         $salaries['zara'] = "low";
         
         echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
         echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
         echo "Salary of zara is ".  $salaries['zara']. "<br />";
      ?>
   
   </body>
</html>

This will produce the following result −

Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.

<html>
   <body>
      
      <?php
         $marks = array( 
            "mohammad" => array (
               "physics" => 35,
               "maths" => 30,	
               "chemistry" => 39
            ),
            
            "qadir" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
            
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
         
         /* Accessing multi-dimensional array values */
         echo "Marks for mohammad in physics : " ;
         echo $marks['mohammad']['physics'] . "<br />"; 
         
         echo "Marks for qadir in maths : ";
         echo $marks['qadir']['maths'] . "<br />"; 
         
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />"; 
      ?>
   
   </body>
</html>

This will produce the following result −

Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

 

]]>
http://virendrayadav.com/blog/array-in-php/feed/ 0
control structures in php http://virendrayadav.com/blog/control-structures-in-php/ http://virendrayadav.com/blog/control-structures-in-php/#respond Thu, 09 Feb 2017 09:35:40 +0000 http://virendrayadav.com/blog/?p=146

Control Structures

Control Structures are loops, like for, and conditionals, such as if. Most of these will be familiar to the javascript programmer, and this page is basically a list. The following exist in php:

if and else

These are exactly the same as javascript and other languages.

if ($a==$b) {

print “The same”;

}

else {

print “They aren’t the same”;

}

There is an alternative way of writing the if statement. For instance:

<script type=“text/javascript”>

<?php
$a=5;
if(
$a==5):?>alert(“It’s five!”);
<?php
endif;
?>

//result: alert saying “It’s five”

</script>

The condition, if ($a==5) is followed by a colon (:), and the end of the block of statements is followed by endif (in php tags). In this way, the statement is not php, and in this case it is javascript.

In the alternative styles, instead of having two curly brackets {} the code replaces the first with a colon and the last with an end… in the case of if, it is endif. In other cases, endwhile, endfor, etc.

If there are other conditions, such as ifelse, then this new condition acts as the closing curly bracket for the if-statement, and the the endif, at the end of the block of code, acts as the final bracket. For instance:

if($a==5): //note colon
print”a equals 5″;
print”…”;
elseif($a==6): // the elseif effectively ends the if-statement and replaces a }
//note the colon after ifelse(…)!
print”a equals 6″;
print”!!!”;
else : //This acts as the end bracket } for the elseif
print”a is neither 5 nor 6″;
endif; // The endif acts as the final curly bracket for the BLOCK of statements

Below is a more complex example:

<script type=“text/javascript”>

<?php

$a=6;

if($a==5): //note colon

?>

document.write(“It’s five!”) ;

<?php

elseif($a==6): //colon!

?>

document.write(“It’s six!”);

<?php

else:

?>

document.write(“It’s neither six nor five”);

<?php

endif;

//result: It’s six!

?>

</script>

Fundamentally, you can put elseif within the if block between the colon (:) and endif;

elseif

elseif, which you can also write else if, gives you a second if-statement. The first if-condition, if met, is run, and any other elseif conditions, even if met are not run. So in the example below, the if-statement is met, so the program outputs Hello Tom, and not Hello Tom 2, even though the relevant elseif condition has been met. That is, elseif acts like a switch, and the control structure is exited at the first match.

$a=“Tom”;

if($a==“Tom”){

print“Hello Tom”;}

elseif($a==“Beryl”){

print“Hello Beryl”;

}

else if ($a==“Tom”){

print “Hello Tom 2”;

}

else {

print“I don’t know you!”;

}

//result: Hello Tom

while

The while loop is the same as in javascript:

$i=1;

while ($i<10){

print “Hello”;

$i++;

}

Ensure the while loop will exit! Forgetting $i++ means it will go on until the browser gets bored!

The next example uses the alternative style:

<?php

$i=1;

while($i<=10): //note the colon!

?>

Hello

<?php

$i++;

endwhile; // tells php the while is done

//result: HelloHelloHelloHelloHelloHelloHelloHelloHelloHello

?>

In the alternative style, the first bracket { is replaced with a colon: the final curly bracket } is replaced with endwhile.

do..while

The do..while loop is similar to the while loop, however, the while loop will not run if the condition is not met. The do..while loop, on the contrary, will always run at least once.

In the example below, the do..while loop runs once, even though the condition is never met (1 isn’t bigger than 100):

$i=0;

do{

print “The number is $i”;

}

while($i>100);

//result: The number is 0

for

The for loop is the same as javascript’s:

for($i=1;$i<=2;$i++){

print “This is $i<br>”;

}

//This is 1

//This is 2

The for loop can be written in various ways. One additional way is as follows:

for($i=1;$i<=3;print “This time it’s $i “,$i++);

//result: This time it’s 1 This time it’s 2 This time it’s 3

Quite neat isn’t it?

foreach

This is used to access the items in an array. For instance:

$arr=array(“cat”,“dog”,“aadvark”);

foreach($arr as $value){

echo“Value: $value<br>\n;

//Value: cat
//Value: dog
//Value: aadvark

This example shows the keys and values of an associative array:

$a=array(“fruit”=>“apple”,“meat”=>“ardvaak”,“vegetables”=>“potatoes”,“sweet”=>“pecan pie”);

foreach($a as $k=>$v){

print“\$a[$k]=>$v.\n;

};

//result: $a[fruit]=>apple. $a[meat]=>ardvaak. $a[vegetables]=>potatoes. $a[sweet]=>pecan pie.

break and continue

Break and continue are familiar to javascript programmers. Break exits a for, while, or switch structure. And continue exits the current pass in the loop and begins with the next. You can determine how many loops to break out of, or to continue from.

switch

The switch statement is also the same as the one in javascript. A switch statement will continue to, in the example below, print all the statements after finding one that is true, so breaks are used to prevent this. Each statement is followed by a break, usually.

$i=1;

switch($i){ //the variable is in brackets and the cases are in curly brackets

case 0:

print “zero”;

break;

case 1:

print “one”;

break;

default: //You can do a default case where the variable is something else!

print “whatever it is, it isn’t 0, 1 or 2”;

}

//result: one

The switch statement can deal with any simple type of data such as integers, floats and strings. This next example is the same as before in structure, except it uses strings:

$i=“tomatoes”;

switch ($i){

case “potatoes”:

print “spuds”;

break;

case “tomatoes”:

print “toms”;

break;

default:

print “Well, it could be anything!”;

}

//result: toms

Finally…


In this article we have covered the two types of Control Structures that PHP supports: Conditional Statements and Control Loops. These Structures are at the core of controlling program flow; the concepts introduced here will be used extensively from now on.

Next time, we will take take a look at pre-defined and user defined functions, which also play an important roll in the logical development and execution of a script.

Things to Remember:

  • Control Structures are at the core of programming flow, allowing you to branch the execution of scripts based on input and easily handle repeatitive tasks.
  • There are two types of Control Structures in PHP: Conditional Statements and Control Loops.
  • Conditional Statements and Loops having only one nested statement do not require brackets, however programmers frequently use them to make code more understandable. Nested statements are often indented for the same reason.
  • Break; can be used to end the execution of the current case. It can also be used to break out of for loops and while loops. Exit; terminates the execution entire script, and may be used anywhere within the script.

]]>
http://virendrayadav.com/blog/control-structures-in-php/feed/ 0
Operators In PHP http://virendrayadav.com/blog/operators-in-php/ http://virendrayadav.com/blog/operators-in-php/#comments Tue, 24 Jan 2017 17:57:05 +0000 http://virendrayadav.com/blog/?p=142

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. PHP language supports following type of operators.

  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
+ Adds two operands A + B will give 30
Subtracts second operand from the first A – B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
Decrement operator, decreases integer value by one A– will give 9

Comparison Operators

There are following comparison operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators

There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
and Called Logical AND operator. If both the operands are true then condition becomes true. (A and B) is true.
or Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A or B) is true.
&& Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

Assignment Operators

There are following assignment operators supported by PHP language −

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

Conditional Operator

There is one more operator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Operators Categories

All the operators we have discussed above can be categorised into following categories −

  • Unary prefix operators, which precede a single operand.
  • Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
  • The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
  • Assignment operators, which assign a value to a variable.

Precedence of PHP Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Unary ! ++ — Right to left
Multiplicative * / % Left to right
Additive + – Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left

 

]]>
http://virendrayadav.com/blog/operators-in-php/feed/ 3
PHP Variables and Constants http://virendrayadav.com/blog/php-variables-and-constants/ http://virendrayadav.com/blog/php-variables-and-constants/#comments Sat, 14 Jan 2017 17:33:14 +0000 http://virendrayadav.com/blog/?p=139

Variables are used for storing values that can change over the course of a script, whereas the constants are used for storing fixed values that doesn’t change.

The main way to store information in the middle of a PHP program is by using a variable.

Here are the most important things to know about variables in PHP.

  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
  • Variables used before they are assigned have default values.
  • PHP does a good job of automatically converting types from one to another when necessary.
  • PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables −

  • Integers − are whole numbers, without a decimal point, like 4195.
  • Doubles − are floating-point numbers, like 3.14159 or 49.1.
  • Booleans − have only two possible values either true or false.
  • NULL − is a special type that only has one value: NULL.
  • Strings − are sequences of characters, like ‘PHP supports string operations.’
  • Arrays − are named and indexed collections of other values.
  • Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
  • Resources − are special variables that hold references to resources external to PHP (such as database connections).

The first five are simple types, and the next two (arrays and objects) are compound – the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.

We will explain only simple data type in this chapters. Array and Objects will be explained separately.

Integers

They are whole numbers, without a decimal point, like 4195. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions, like so −

$int_var = 12345;
$another_int = -12345 + 12345;

Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.

For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places needed. For example, the code −

<?php
   $many = 2.2888800;
   $many_2 = 2.2111200;
   $few = $many + $many_2;
   
   print("$many + $many_2 = $few <br>");
?>

It produces the following browser output −

2.28888 + 2.21112 = 4.5

Boolean

They have only two possible values either true or false. PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE, which can be used like so −

if (TRUE)
   print("This will always print<br>");

else
   print("This will never print<br>");

Interpreting other types as Booleans

Here are the rules for determine the “truth” of any value not already of the Boolean type −

  • If the value is a number, it is false if exactly equal to zero and true otherwise.
  • If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”, and is true otherwise.
  • Values of type NULL are always false.
  • If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
  • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
  • Don’t use double as Booleans.

Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL

NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this −

$my_var = NULL;

The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed −

$my_var = null;

A variable that has been assigned NULL has the following properties −

  • It evaluates to FALSE in a Boolean context.
  • It returns FALSE when tested with IsSet() function.

Strings

They are sequences of characters, like “PHP supports string operations”. Following are valid examples of string

$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.

<?php
   $variable = "name";
   $literally = 'My $variable will not print!';
   
   print($literally);
   print "<br>";
   
   $literally = "My $variable will print!";
   print($literally);
?>

This will produce following result −

My $variable will not print!\n
My name will print

There are no artificial limits on string length – within the bounds of available memory, you ought to be able to make arbitrarily long strings.

Strings that are delimited by double quotes (as in “this”) are preprocessed in both the following two ways by PHP −

  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are −

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \” is replaced by a single double-quote (“)
  • \\ is replaced by a single backslash (\)

Here Document

You can assign multiple lines to a single string variable using here document −

<?php
   $channel =<<<_XML_
   
   <channel>
      <title>What's For Dinner</title>
      <link>http://menu.example.com/ </link>
      <description>Choose what to eat tonight.</description>
   </channel>
_XML_;
   
   echo <<<END
   This uses the "here document" syntax to output multiple lines with variable 
   interpolation. Note that the here document terminator must appear on a line with 
   just a semicolon. no extra whitespace!
   

END;
   
   print $channel;
?>

This will produce following result −

This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!

<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>

Variable Scope

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −

Variable Naming

Rules for naming a variable is −

  • Variable names must begin with a letter or underscore character.
  • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc

There is no size limit for variables.

]]>
http://virendrayadav.com/blog/php-variables-and-constants/feed/ 1
JSON encode and decode on PHP http://virendrayadav.com/blog/json-encode-and-decode-on-php/ http://virendrayadav.com/blog/json-encode-and-decode-on-php/#comments Wed, 04 Jan 2017 18:06:05 +0000 http://virendrayadav.com/blog/?p=136

JSON makes dealing with data in your app exceptionally easy and manageable. The best part about JSON is you can look at it and understand it. It’s not like the confusing spaghetti DOM that you get with XML, it’s a lean minimal representation of your data. If you’re dealing with chunks of data in your app, you want to be using JSON.

So while your app will happily eat up all the JSON you can throw at it, you still need to make it in the first place – and/or have a server side app that is capable of reading it. If, like me, you use PHP to handle things on a server then things are pretty straightforward. You can use PHP’s json_encode and json_decode functions. Encode will take your arrays, or objects, and create a JSON string of your data. While decode will take a JSON string, sent from your app, and turn it into an array or object.

JSON encode function

In PHP, json_encode() is used to convert PHP supported data type into JSON formatted string to be returned as a result of JSON encode operation. This function accepts the following set of arguments.

  • Data to be encoded.
  • Options with JSON encode constants to reflect effects on encoding behavior.
  • Depth limit for performing recursive encoding with nested levels of input.

Predefined JSON Constants

For PHP JSON encode, the following list of constants will be used for the options parameter of json_encode() function.

    • JSON_HEX_TAG – Used to encode HTML content by replacing < and > symbol with u003C and u003E.
    • JSON_HEX_AMP – Used to encode data by replacing ampersand symbol (&) with u0026.
    • JSON_HEX_APOS – encode apostrophe (‘) with u0027.
    • JSON_HEX_QUOT – converts double quotes (“) into u0022.
    • JSON_FORCE_OBJECT – Using this, json_encode will return object for given input data except associative array.
    • JSON_NUMERIC_CHECK – PHP JSON encode function will return numbers as a result of encoding given number with string data type.
    • JSON_BIGINT_AS_STRING – This constant is used to convert the log integer value as string.
    • JSON_PRETTY_PRINT – pretty print is used for adding white space with the JSON formatted data.
    • JSON_UNESCAPED_SLASHES – It prevents from escaping slashes (/).
    • JSON_UNESCAPED_UNICODE – It prevents from escaping unicode characters.

Example

The following example shows how to convert an array into JSON with PHP −

<?php
   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);
?>

While executing, this will produce the following result −

{"a":1,"b":2,"c":3,"d":4,"e":5}

The following example shows how the PHP objects can be converted into JSON −

<?php
   class Emp {
      public $name = "";
      public $hobbies  = "";
      public $birthdate = "";
   }
	
   $e = new Emp();
   $e->name = "sachin";
   $e->hobbies  = "sports";
   $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);
?>

While executing, this will produce the following result −

{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

Decoding JSON in PHP (json_decode)

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.

Syntax

mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Paramaters

  • json_string − It is an encoded string which must be UTF-8 encoded data.
  • assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.
  • depth − It is an integer type parameter which specifies recursion depth
  • options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.

Example

The following example shows how PHP can be used to decode JSON objects −

<?php
   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

While executing, it will produce the following result −

object(stdClass)#1 (5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

array(5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

Note: While passing associative array or object with key and value pair for json_decode(), the key value should be enclosed within double quotes. Otherwise, json_decode() will return NULL.

]]>
http://virendrayadav.com/blog/json-encode-and-decode-on-php/feed/ 2
User Login Session Timeout Logout in PHP http://virendrayadav.com/blog/user-login-session-timeout-logout-in-php/ http://virendrayadav.com/blog/user-login-session-timeout-logout-in-php/#comments Tue, 27 Dec 2016 18:13:46 +0000 http://virendrayadav.com/blog/?p=133

This PHP tutorial is used for setting user login session expiration time for the logged-in user. Once, this time is elapsed then the user no longer access the authenticated pages of the application. In previous tutorial, we have created session variables once an user logged in to our application.

In this tutorial we are going to add current logged-in timestamp to a session. Using this timestamp we are checking if the login session expiration time is reached. If so,  the user will be logged out.

HTML code for User Login

This code is for showing login form to the user.

<form name="frmUser" method="post" action="">
<?php if($message!="") { ?>
<div class="message"><?php echo $message; ?></div>
<?php } ?>
<table border="0" cellpadding="10" cellspacing="1" width="100%" class="tblLogin">
<tr class="tableheader">
<td align="center" colspan="2">Enter Login Details</td>
</tr>
<tr class="tablerow">
<td align="right">Username</td>
<td><input type="text" name="user_name"></td>
</tr>
<tr class="tablerow">
<td align="right">Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>

Creating User Login Session

In this code we are adding logged-in user id and logged-in time to a session variable. Then, we are invoking a PHP function to check if the login session expiration time is elapsed. If it is not reached, then the user will be redirected to the dashboard.

if(count($_POST)>0) {
	if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin") {
		$_SESSION["user_id"] = 1001;
		$_SESSION["user_name"] = $_POST["user_name"];
		$_SESSION['loggedin_time'] = time();  
	} else {
		$message = "Invalid Username or Password!";
	}
}

if(isset($_SESSION["user_id"])) {
	if(!isLoginSessionExpired()) {
		header("Location:user_dashboard.php");
	} else {
		header("Location:logout.php?session_expired=1");
	}
}

PHP Function for Checking Login Session Timeout

This function will be invoked at the begining of all authenticated pages. This function returns TRUE if the user login session is expired, FALSE otherwise.

function isLoginSessionExpired() {
	$login_session_duration = 10; 
	$current_time = time(); 
	if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){  
		if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){ 
			return true; 
		} 
	}
	return false;
}

User Login Session Expiration Logout

This logout.php page will unset logged-in user session and check for the status of session_expired flag. If it is set, then the login session timeout message will be displayed to the user.

session_start();
unset($_SESSION["user_id"]);
unset($_SESSION["user_name"]);
$url = "index.php";
if(isset($_GET["session_expired"])) {
	$url .= "?session_expired=" . $_GET["session_expired"];
}
header("Location:$url");

What will this code do?

First it take time from session that we have stored recently in above line, then it will take current time and subtract it from current time. If  the result is greater than 30 minutes (you can change as your wish) it will log out the user and redirect him to our login page and if the result is less than 30 minutes it will store new time in session that is our current time.

 

 

]]>
http://virendrayadav.com/blog/user-login-session-timeout-logout-in-php/feed/ 1
PHP include and require Statements http://virendrayadav.com/blog/php-include-and-require-statements/ http://virendrayadav.com/blog/php-include-and-require-statements/#respond Tue, 20 Dec 2016 17:56:43 +0000 http://virendrayadav.com/blog/?p=130

It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

  • require will produce a fatal error (E_COMPILE_ERROR) and stop the script
  • include will only produce a warning (E_WARNING) and the script will continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use the require statement to include a key file to the flow of execution. This will help avoid compromising your application’s security and integrity, just in-case one key file is accidentally missing.

Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with the following content.

<a href="http://www.tutorialspoint.com/index.htm">Home</a> - 
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> - 
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> - 
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />

Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.

<html>
   <body>
   
      <?php include("menu.php"); ?>
      <p>This is an example to show how to include PHP file!</p>
      
   </body>
</html>

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.

You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.

<html>
   <body>
   
      <?php include("xxmenu.php"); ?>
      <p>This is an example to show how to include wrong PHP file!</p>
      
   </body>
</html>

This will produce the following result −

This is an example to show how to include wrong PHP file!

Now lets try same example with require() function.

<html>
   <body>
       
       <?php require("xxmenu.php"); ?>
       <p>This is an example to show how to include wrong PHP file!</p>
   
   </body>
</html>

This time file execution halts and nothing is displayed.

NOTE − You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

]]>
http://virendrayadav.com/blog/php-include-and-require-statements/feed/ 0
PHP Tutorials for beginners http://virendrayadav.com/blog/php-tutorials-for-beginners/ http://virendrayadav.com/blog/php-tutorials-for-beginners/#respond Thu, 15 Dec 2016 17:32:07 +0000 http://virendrayadav.com/blog/?p=127

What is PHP?

PHP is probably the most popular scripting language on the web. It is used to enhance web pages. With PHP, you can do things like create username and password login pages, check details from a form, create forums, picture galleries, surveys, and a whole lot more. If you’ve come across a web page that ends in PHP, then the author has written some programming code to liven up the plain, old HTML.

PHP is known as a server-sided language. That’s because the PHP doesn’t get executed on your computer, but on the computer you requested the page from. The results are then handed over to you, and displayed in your browser. Other scripting languages you may have heard of are ASP, Python and Perl. (You don’t need to know any of these to make a start on PHP. In fact, these tutorials assume that you have no programming experience at all.)

 

Introduction

PHP, an acronym for Hypertext Preprocessor, is a widely-used open source general-purpose scripting language. It is a cross-platform, HTML-embedded server-side scripting language and is especially suited for web development.

Where

  • Server-side means that PHP scripts execute on the Web server, not within the browser on your local machine.
  • Cross-platform means that PHP scripts can run on many different operating systems and Web servers. PHP is available for the two most popular Web server configurations IIS and Apache.
  • HTML embedded scripting language means that PHP statements and commands are actually embedded in your HTML documents. When the Web server sees the PHP statements in the Web page, the server executes the statements and sends the resulting output along with the rest of the HTML. PHP commands are parsed by the server much like Active Server Pages or Cold Fusion tags.

The basic syntax of PHP is similar to C, Java, and Perl, and is easy to learn. PHP is used for creating interactive and dynamic web pages quickly, but you can do much more with PHP.

<html>
   <head>
      <title>First PHP example</title>      
   </head>
   
   <body>
      
      <?php
         echo "<h1>Hello, PHP!</h1>";
      ?>
   
   </body>
</html>

In the above example we have written a HTML script with some embedded code to display some text. The PHP code is enclosed in special start (<?php) and end (?>) tags that allows to go in and out of PHP mode. The extension of a php file is “.php”.

Benefits of PHP

  • PHP is an open source software.
  • PHP costs nothing, it is free to download and use.
  • PHP is a server-side scripting language and is used for websites and the web applications.
  • PHP scripts are executed on the server.
  • PHP supports a wide range of databases.
  • PHP runs on various platforms like Linux, Windows, Unix etc.
  • PHP supports most web servers (for example Apache, IIS).
  • PHP converses with several network protocols.

Features of the w3resource PHP tutorials

In this series of tutorials, we have covered PHP 5 in detail. While creating this, we have to take care that learners can master the basics of PHP and can be prepared to develop web based applications.

Here is a list of features we have included in all of the chapters :

1. We have started with a clear and simple description.

2. We have given a Syntax / Usage so that you can remember how to write it.

3. Example(s) to show how the associated concept is implemented.

4. We have shown the Output of the usage.

5. View the example in a browser.

6. Pictorial presentation to help you to understand the concept better.

]]>
http://virendrayadav.com/blog/php-tutorials-for-beginners/feed/ 0
5 Easy SEO Tips to Boost Your Site http://virendrayadav.com/blog/5-easy-seo-tips-to-boost-your-site/ http://virendrayadav.com/blog/5-easy-seo-tips-to-boost-your-site/#comments Sat, 03 Dec 2016 06:39:09 +0000 http://virendrayadav.com/blog/?p=117

You’ve created an awesome website – congrats! What you need to do now is bring people to it. For your website to come up high on search engines like Google and Bing,Yahoo you need to understand a little bit about the world of “Search Engine Optimization” or SEO.tips to boost seo

While many shy away from this topic, it’s actually not the scary monster many make it out to be. The first step in the right direction is to use the free SEO Wizard – a user-friendly tool that will take you step-by-step through the process of optimizing your website.

With so many websites on the web today, there is no way to guarantee that your site will rank first on Google – but there are plenty of simple things you can do to increase your site’s chances of ranking real well. Give us just an hour’s time (or less!) and we’ll show you everything you need to know about SEO and how to boost your site.

Choose the right URL

Before your website goes live, you need to select a URL. Also known as your domain name, it’s the address that visitors will type in to find your site. Like the giant sign above a storefront window, it’s one of the first things visitors see when they come to your site. That’s why it’s also the first place Google looks to understand what your site is about and decide how to rank it.

The ideal domain will include your business name and perhaps a keyword or two that are relevant to your business. For example, if you are a contractor, you might want to purchase a URL like www.xyz.com.

It’s also important to make sure your URLs are clean. This doesn’t mean dusting off the old ones but rather making sure the end or your link is as simple as the text on your site. No special characters. No hashbangs. No page ID. Want to clean your URLs in one click?tips to boost seo

Create titles and descriptions for each page

Did you know that you can write a unique title and description for each page on your website? These are brief texts that accurately and clearly describe what your business does, ideally with a few keywords and phrases mixed in.

Ever hovered over a tab on your browser? That short phrase that pops up under your mouse is the title of the page. While the description is not visible, it too is very important for search engines! In fact, the title and description are among the first things Google uses to determine your site’s rank. Plus – once your site does show up in a search results page, web surfers will read your title and description to learn what your site is about and decide whether or not to check it out.

Utilize anchor text

As you write the text for your website, consider where you can use anchor text within your site. Anchor what? No, it has nothing to do with sailing. Anchor text is simply text that visitors can click on to be taken directly to another web page, either on your site or anywhere on the Internet.

Effective anchor text should be used to help users navigate your website and find what they are looking for. It should also include keywords and phrases related to what you do. If you own a shoe store, for example, the words, “Check out our selection of children’s shoes,” on your homepage can link via anchor text to your online store that is stocked full of – you guessed it – children’s shoes.

Anchor text is a great way to boost your SEO, but keep in mind that excessive linking or anchors that don’t really help your readers can raise red flags with Google.

Add alt text to all your images

Search engines are great at reading text on your website, but they still haven’t quite figured out how to look at the images on your site. To understand what’s displayed in a photo or graphic, search engines look for “alt text,” a concise written description (just a few words) about each image on a website. When writing alt text, be sure to accurately describe what is shown in the image, but also try to include the name of your business or a few keywords related to what you do.

Pro Tip: You don’t need to write alt text for images that are purely functional or design related, such as a background image that is just shapes. If the image doesn’t have anything to do with the topic of your site, you can skip the alt text.

Connect your site to your social channels

Did you know that your Facebook page has an impact on how you rank on Google? In fact, being present (and active) on any social media site, from Twitter and Instagram to Facebook and (of course) Google is an essential part of boosting your SEO.

When you create your website, make sure to include prominent icons for each of your social networks, linking directly to your profile on each site. You also want to make it easy for your visitors to share the content on your site. As users share your content, traffic to your website will increase and, wouldn’t you know it, Google will take notice! Sites that generate a lot of social activity will come up more frequently in searches.

If after trying out these 5 easy steps you’re feeling a bit more confident and want to take your knowledge to the next level, be sure to check out this in-depth post about SEO.

]]>
http://virendrayadav.com/blog/5-easy-seo-tips-to-boost-your-site/feed/ 2
Top Article Directory Site List For USA http://virendrayadav.com/blog/top-article-directory-site-list-for-usa/ http://virendrayadav.com/blog/top-article-directory-site-list-for-usa/#comments Tue, 22 Nov 2016 10:44:55 +0000 http://virendrayadav.com/blog/?p=71

As an Internet marketer, Nobody dares to undervalue the content marketing to increase traffic for the website. If you thought so, Then you all finish.

For Increasing the website traffic, content marketing is the main source for a long term Success. In Content Marketing, The main part is Article marketing.article directories

What is Article Marketing & How Does it Work?

Article marketing where business creates quality content and Promote that content on high authority free article Submission sites, some of them give instant approval to archive higher amount of Referral traffic. There already lots of unique visitors those can view, comment, vote your article. While I was writing article submission sites post, I thought, Must include some beneficial links in this post regarding social bookmarking sites. It will be beneficial for you to browse more Data. So Here is The Complete lists of Social Bookmarking Sites for You.

Benefits of Article Submission Sites

At traffic point of View the benefits are by submitting an article in high pr free article submission sites, Increases the chances are more to Drive a large amount of Traffic, Spread Brand & Product Awareness which help to increase the direct traffic to the business.

Getting higher rankings in Search Engines (By submitting Articles you get the backlinks to the business from High pr dofollow article submission sites.

When Search engine crawler comes to that article & crawl the backlinks, You get the chances to get ranked high by that Anchor text). By reading the above information, It’s not difficult to recognize the Importance of Article Marketing.article directories

 

Top Free Article Submission Sites List

  • http://ezinearticles.com/
  • http://www.selfgrowth.com/
  • http://hubpages.com/
  • http://www.brighthub.com/
  • http://www.livejournal.com/
  • https://www.tumblr.com/
  • https://storify.com/
  • https://github.com/
  • http://www.merchantcircle.com/
  • https://www.quora.com/
  • https://evernote.com/
  • http://www.grindtv.com/
  • https://medium.com/
  • https://www.diigo.com/
  • https://www.behance.net/
  • https://carbonmade.com/
  • http://www.wikia.com/fandom
  • http://matadornetwork.com/
  • http://skyrock.com/
  • https://tutsplus.com/
  • http://www.houzz.com/
  • https://www.entrepreneur.com/
  • https://www.wattpad.com/
  • http://www.thewhir.com/
  • https://www.smore.com/
  • https://wistia.com/
  • https://www.constant-content.com/
  • http://www.infobarrel.com/
  • http://www.mylot.com/
  • http://www.articles.org/
  • http://www.myarticle.com/
  • http://www.storeboard.com/
  • http://www.readezarchive.com/
  • http://www.ehow.com/
  • https://www.biggerpockets.com/renewsblog/
  • http://www.buzzle.com/
  • http://www.axs.com/
  • https://knoji.com/articles/
  • https://www.textbroker.com/
  • https://www.thefreelibrary.com/
  • http://www.evancarmichael.com/
  • https://wizzley.com/
  • http://www.articleslash.net/
  • http://www.articledirectoryusa.com/article directories

article submission sites, article submission, article submission sites 2016, article sites, free article submission sites, article submission sites list, top article submission sites, free article submission, free article submission sites list 2016, article site, article posting sites, high pr article submission sites, article submission site, article upload sites, article submission websites, top article submission sites.

]]>
http://virendrayadav.com/blog/top-article-directory-site-list-for-usa/feed/ 3