SEED – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Tue, 26 May 2020 13:23:42 +0000 en-US hourly 1 https://wordpress.org/?v=6.9 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg SEED – Shishir Kant Singh https://shishirkant.com 32 32 187312365 PHP Cookies https://shishirkant.com/php-cookies/?utm_source=rss&utm_medium=rss&utm_campaign=php-cookies Tue, 26 May 2020 13:23:39 +0000 http://shishirkant.com/?p=849 What is a Cookie

Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.

In this tutorial, we will discuss how to use Cookies in PHP. We have several examples in this tutorial which will help you to understand the concept and use of a cookie.

Uses of cookie

Cookies are often used to perform following tasks:

  • Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
  • User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is ‘Retargetting’. A concept used in online marketing, where depending upon the user’s choice of content, advertisements of the relevant product, which the user may buy, are served.
  • Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.

How to create a cookie in PHP

PHP has a setcookie() function to send a cookie. We will discuss this function in detail now.

Usage:

setcookie(name, value, expire, path, domain, secure, httponly)

Parameters:

setcookie() has several parameters. Following table discusses those.

ParameterDescriptionWhich type of data
nameName of the cookie.String
valueValue of the cookie, stored in clients computer.String
expireUnix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch).Integer
pathServer path in which the cookie will be available.String
domainTo which domain the cookie is available.String
secureIf set true, the cookie is available over a secure connection only.Boolean
httponlyIf set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won’t be able to access the cookie.Boolean

setcookie() returns boolean.

Example:

Following example shows how to create a cookie in PHP. Code first and then some explanation.

<?php
$cookie_value = "shishirkant tutorials";
setcookie("shishirkant", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
if (isset($_COOKIE['cookie']))
echo $_COOKIE["shishirkant"];
?>

So, what does the code above does? The first parameter sets the name of the cookie as ‘w3resource’, the second parameter sets the value as ‘w3resource tutorials’, the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server ‘/home/your_name’ where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.

echo $_COOKIE["shishirkant"]; simply prints the cookie value. This way you can retrieve a cookie value.

Output:

shishirkant tutorials

How to create a cookie without urlencoding the cookie value

The setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use setrawcookie().

This function has all the parameters which setcookie() has, and the return value is also boolean.

PHP $_COOKIE autoglobal

If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.

The following code shows how to use $_COOKIE.

<?php
$cookie_value = "shishirkant tutorials";
setcookie("shishirkant", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
echo 'Hi ' . htmlspecialchars($_COOKIE["shishirkant"]);
?>

If you wish to retreive all the cookies, you may use the following command

<?php
print_r($_COOKIE);
?>

headers already sent problem because of cookies

PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like “…headers already sent….”.

To get rid of the problem, you may use “Output buffering functions”. Following code shows how to add an output buffering function.

<?php
ob_start(); //at the begining of the php script
//your code goes here
//add these two lines at the end of the script
$stuff = ob_get_clean();
echo $stuff;
?>

How to delete a cookie

To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.

<?php
$cookie_value = "shishirkant  tutorials";
setcookie("shishirkant", $cookie_value, time()-3600, "/home/your_usename/", "example.com", 1, 1);
?>

Javascript cookies vs php cookies

This may confuse you if you are just starting out with web programming. But in practice, Cookies are defined by RFC 2965. It is a standard which can be used any programming language. It has nothing to do with PHP vs JavaScript. In PHP, as we have seen in the first example of this tutorial, that cookies can be set such a way that it can’t be accessed by client side JavaScript, but that is a programming feature only.

Cookies vs Sessions

Both cookies and sessions are used for storing persistent data. But there are differences for sure.

Sessions are stored on server side. Cookies are on the client side.

Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

Sessions are safe that cookies. Because, since stored on client’s computer, there are ways to modify or manipulate cookies.

Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.

]]>
849
PHP Arrays https://shishirkant.com/php-arrays/?utm_source=rss&utm_medium=rss&utm_campaign=php-arrays Tue, 26 May 2020 08:48:35 +0000 http://shishirkant.com/?p=827 What is a PHP Array?

A PHP array is a variable that stores more than one piece of related data in a single variable.

Think of an array as a box of chocolates with slots inside.

The box represents the array itself while the spaces containing chocolates represent the values stored in the arrays.

The diagram below illustrates the above syntax.
 

Numeric Arrays

Numeric arrays use number as access keys.

An access key is a reference to a memory slot in an array variable.

The access key is used whenever we want to read or assign a new value an array element.

Below is the syntax for creating numeric array in php. Array Example

<?php
$variable_name[n] = value;
?>

Or

<?php
$variable_name = array(n => value, …);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let’s now look at an example of a numeric array.

Suppose we have 5 movies that we want to store in array variables.

We can use the example shown below to do that.

<?php

$movie[0] = 'Shaolin Monk';
$movie[1] = 'Drunken Master';
$movie[2] = 'American Ninja';
$movie[3] = 'Once upon a time in China';
$movie[4] = 'Replacement Killers';

?>

Here,

PHP Array

Each movie is given an index number that is used to retrieve or modify its value. Observe the following code-

<?php
$movie[0]="Shaolin Monk";
$movie[1]="Drunken Master";
$movie[2]="American Ninja";
$movie[3]="Once upon a time in China";
$movie[4]="Replacement Killers";
echo $movie[3];
$movie[3] = " Eastern Condors";
echo $movie[3];
?>

Output:

Once upon a time in China Eastern Condors

As you can see from the above examples, working with arrays in PHP when dealing with multiple values of the same nature is very easy and flexible.

Alternatively, the above array variables can also be created using the following code.

<?php
$movie = array(0 => "Shaolin Monk",
               1 => "Drunken Master",
               2 => "American Ninja",
               3 => "Once upon a time in China",
               4 =>"Replacement Killers" );
echo $movie[4];
?>

Output:

Replacement Killers

PHP Associative Array

Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.

Below is the syntax for creating associative array in php.

<?php
$variable_name['key_name'] = value;

$variable_name = array('keyname' => value);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[‘key_name’]” is the access index number of the element
  • “value” is the value assigned to the array element.

  Let’s suppose that we have a group of persons, and we want to assign the gender of each person against their names.

We can use an associative array to do that.The code below helps us to do that.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");
print_r($persons); 
echo ""; 
echo "Mary is a " . $persons["Mary"];
?>

 HERE,

PHP Array

Output:

Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

Associative array are also very useful when retrieving data from the database.

The field names are used as id keys.


PHP Multi-dimensional arrays

These are arrays that contain other nested arrays.

The advantage of multidimensional arrays is that they allow us to group related data together.

Let’s now look at a practical example that implements a php multidimensional array.

The table below shows a list of movies by category.

Movie titleCategory
Pink PantherComedy
John EnglishComedy
Die HardAction
ExpendablesAction
The Lord of the ringsEpic
Romeo and JulietRomance
See no evil hear no evilComedy

The above information can be represented as a multidimensional array. The code below shows the implementation.

<?php
$movies =array(
"comedy" => array("Pink Panther", "John English", "See no evil hear no evil"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"Romance" => array("Romeo and Juliet")
);
print_r($movies);
?>

  HERE,

PHP Array

Output:

Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => See no evil hear no evil ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array ( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

Another way to define the same array is as follows

<?php
$film=array(

                "comedy" => array(

                                0 => "Pink Panther",

                                1 => "john English",

                                2 => "See no evil hear no evil"

                                ),

                "action" => array (

                                0 => "Die Hard",

                                1 => "Expendables"

                                ),

                "epic" => array (

                                0 => "The Lord of the rings"

                                ),

                "Romance" => array

                                (

                                0 => "Romeo and Juliet"

                                )

);
echo $film["comedy"][0];
?>

Output:

Pink Panther

  Note: the movies numeric array has been nested inside the categories associative array

PHP Arrays: Operators

OperatorNameDescriptionHow to do itOutput
x + yUnionCombines elements from both arrays<?php
$x = array(‘id’ => 1);
$y = array(‘value’ => 10);
$z = $x + $y;
?>
Array([id] => 1 [value] => 10)
X == yEqualCompares two arrays if they are equal and returns true if yes.<?php
$x = array(“id” => 1);
$y = array(“id” => “1”);
if($x == $y)
{
echo “true”;
}
else
{
echo “false”;
}
?>
True or 1
X === yIdenticalCompares both the values and data types<?php
$x = array(“id” => 1);
$y = array(“id” => “1”);
if($x === $y)
{
echo “true”;
}
else
{
echo “false”;
}
?>
False or 0
X != y, x <> yNot equal <?php
$x = array(“id” => 1);
$y = array(“id” => “1”);
if($x != $y)
{
echo “true”;
}
else
{
echo “false”;
}
?>
False or 0
X !== yNon identical <?php
$x = array(“id” => 1);
$y = array(“id” => “1”);
if($x !== $y)
{
echo “true”;
}
else
{
echo “false”;
}
?>
True or 1

PHP Array Functions

Count function

The count function is used to count the number of elements that an php array contains. The code below shows the implementation.

<?php
$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");
echo count($lecturers);
?>

Output:

3

is_array function

The is_array function is used to determine if a variable is an array or not. Let’s now look at an example that implements the is_array functions.

<?php
$lecturers = array("Mr. Jones", "Mr. Banda", "Mrs. Smith");
echo is_array($lecturers);
?>

Output:

1

Sort

This function is used to sort arrays by the values.

If the values are alphanumeric, it sorts them in alphabetical order.

If the values are numeric, it sorts them in ascending order.

It removes the existing access keys and add new numeric keys.

The output of this function is a numeric array

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

sort($persons);

print_r($persons);
?>

Output:

Array ( [0] => Female [1] => Female [2] => Male )

ksort

This function is used to sort the array using the key. The following example illustrates its usage.

<?php
$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

ksort($persons);

print_r($persons);
?>

Output:

Array ( [John] => Male [Mary] => Female [Mirriam] => Female )

asort

This function is used to sort the array using the values. The following example illustrates its usage.

<?php

$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

asort($persons);

print_r($persons);

?>

Output:

Array ( [Mary] => Female [Mirriam] => Female [John] => Male )

Why use arrays?

  • Contents of Arrays can be stretched,
  • Arrays easily help group related information such as server login details together
  • Arrays help write cleaner code.


  • Arrays are special variables with the capacity to store multi values.
  • Arrays are flexibility and can be easily stretched to accommodate more values
  • Numeric arrays use numbers for the array keys
  • PHP Associative array use descriptive names for array keys
  • Multidimensional arrays contain other arrays inside them.
  • The count function is used to get the number of items that have been stored in an array
  • The is_array function is used to determine whether a variable is a valid array or not.
  • Other array functions include sort, ksort, assort etc.
]]>
827
PHP Loop https://shishirkant.com/php-loop/?utm_source=rss&utm_medium=rss&utm_campaign=php-loop Tue, 26 May 2020 08:38:53 +0000 http://shishirkant.com/?p=824 PHP while loop

The while is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.

This is the general form of the while loop:

while (expression):
    statement

The while loop executes the statement when the expression is evaluated to true. The statement is a simple statement terminated by a semicolon or a compound statement enclosed in curly brackets.

whilestm.php

<?php

$i = 0;

while ($i < 5) {
    echo "PHP language\n";
    $i++;
}
?>

In the code example, we repeatedly print “PHP language” string to the console.

The while loop has three parts: initialization, testing, and updating. Each execution of the statement is called a cycle.

$i = 0;

We initiate the $i variable. It is used as a counter in our script.

while ($i < 5) {
   ...
}

The expression inside the square brackets is the second phase, the testing. The while loop executes the statements in the body until the expression is evaluated to false.

$i++;

The last, third phase of the while loop is the updating; a counter is incremented. Note that improper handling of the while loop may lead to endless cycles.

$ php whilestm.php 
PHP language
PHP language
PHP language
PHP language
PHP language

The program prints a message five times to the console.

The do while loop is a version of the while loop. The difference is that this version is guaranteed to run at least once.

dowhile.php

<?php

$count = 0;

do {
    echo "$count\n";
} while ($count != 0) 

First the iteration is executed and then the truth expression is evaluated.

The while loop is often used with the list() and each() functions.

seasons.php

<?php

$seasons = ["Spring", "Summer", "Autumn", "Winter"];

while (list($idx , $val) = each($seasons)) {
    echo "$val\n";
}
?>

We have four seasons in a $seasons array. We go through all the values and print them to the console. The each() function returns the current key and value pair from an array and advances the array cursor. When the function reaches the end of the array, it returns false and the loop is terminated. The each() function returns an array. There must be an array on the left side of the assignment too. We use the list() function to create an array from two variables.

$ php seasons.php 
Spring
Summer
Autumn
Winter

This is the output of the seasons.php script.

PHP for keyword

The for loop does the same thing as the while loop. Only it puts all three phases, initialization, testing and updating into one place, between the round brackets. It is mainly used when the number of iteration is know before entering the loop.

Let’s have an example with the for loop.

forloop.php

<?php

$days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", 
              "Saturday", "Sunday" ];

$len = count($days);

for ($i = 0; $i < $len; $i++) {
    echo $days[$i], "\n";
}
?>

We have an array of days of a week. We want to print all these days from this array.

$len = count($days);

Or we can programmatically figure out the number of items in an array.

for ($i = 0; $i < $len; $i++) {
   echo $days[$i], "\n"; 
}

Here we have the for loop construct. The three phases are divided by semicolons. First, the $i counter is initiated. The initiation part takes place only once. Next, the test is conducted. If the result of the test is true, the statement is executed. Finally, the counter is incremented. This is one cycle. The for loop iterates until the test expression is false.

$ php forloop.php 
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

This is the output of the forloop.php script.

PHP foreach statement

The foreach construct simplifies traversing over collections of data. It has no explicit counter. The foreach statement goes through the array one by one and the current value is copied to a variable defined in the construct. In PHP, we can use it to traverse over an array.

foreachstm.php

<?php

$planets = [ "Mercury", "Venus", "Earth", "Mars", "Jupiter", 
                 "Saturn", "Uranus", "Neptune" ];

foreach ($planets as $item) {
    echo "$item ";
}

echo "\n";
?>

In this example, we use the foreach statement to go through an array of planets.

foreach ($planets as $item) {
    echo "$item ";
}

The usage of the foreach statement is straightforward. The $planets is the array that we iterate through. The $item is the temporary variable that has the current value from the array. The foreach statement goes through all the planets and prints them to the console.

$ php foreachstm.php 
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 

Running the above PHP script gives this output.

There is another syntax of the foreach statement. It is used with maps.

foreachstm2.php

<?php 

$benelux =  [ 'be' => 'Belgium',
              'lu' => 'Luxembourgh',
              'nl' => 'Netherlands' ];

foreach ($benelux as $key => $value) {
    echo "$key is $value\n";
}
?>

In our script, we have a $benelux map. It contains domain names mapped to the benelux states. We traverse the array and print both keys and their values to the console.

$ php foreachstm2.php 
be is Belgium
lu is Luxembourgh
nl is Netherlands

This is the outcome of the script.

PHP break, continue statements

The break statement is used to terminate the loop. The continue statement is used to skip a part of the loop and continue with the next iteration of the loop.

testbreak.php

<?php

while (true) {

    $val = rand(1, 30);
    echo $val, " ";
    if ($val == 22) break;
}

echo "\n";
?>

We define an endless while loop. There is only one way to jump out of a such loop—using the break statement. We choose a random value from 1 to 30 and print it. If the value equals to 22, we finish the endless while loop.

$ php testbreak.php 
6 11 13 5 5 21 9 1 21 22 

We might get something like this.

In the following example, we print a list of numbers that cannot be divided by 2 without a remainder.

testcontinue.php

<?php

$num = 0;

while ($num < 1000) {

    $num++;
    if (($num % 2) == 0) continue;

    echo "$num ";

}

echo "\n";
?>

We iterate through numbers 1..999 with the while loop.

if (($num % 2) == 0) continue;

If the expression $num % 2 returns 0, the number in question can be divided by 2. The continue statement is executed and the rest of the cycle is skipped. In our case, the last statement of the loop is skipped and the number is not printed to the console. The next iteration is started.

]]>
824