PHP Cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Create Cookies

setcookie() method contains different parameters but in the below example we will only use 4 parameters, Cookie Name, Cookie Value, Time in Seconds and Path.

                    

<?php

	$cookie_name="color";
	$cookie_value="black";
	
	setcookie($cookie_name,$cookie_value,time()+86400,"/");
	
?>

Read Cookie

As php have different Global arrays like $_POST, $_GET and etc. same PHP contains $_COOKIE array to access/set cookies values.

                    

<?php

	//read the cookie data
	if(isset($_COOKIE['color'])){
		echo $_COOKIE['color'];
	}else{
		echo 'No Cookie Found';
	}
?>

PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages. Session values are stored at server and contains separate values for every users.

When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

Start Session & Assign Values

Before any data operation(read/write/unset) on session array, initiate the session with session_start() method

                    

<?php

	//Start the Session for current User
	session_start();
	$_SESSION['Username']='abc@gmail.com';
	$_SESSION['Auth']=true;
?>

Retrieve the Sessions Values

                    

<?php

	session_start();
	
	echo $_SESSION['Username']."
"; echo $_SESSION['Auth']."
"; ?>

Unset & Destroy Session

Good Practice is to unset/destroy the session when they are no more required. it comes under good resource management.

                    

<?php

	session_start();
	
	//remove the Values of $_SESSION
	session_unset();
	
	//close & destroy the complete Session for Current User
	session_destroy();
?>


PHP MySql Delete

PHP Have Query Method for all types of SQL Operations.

MySQL Delete (Object Oriented)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=new mysqli($server,$username,$password,$db);

if($conn->connect_error){
	die("Error:".$conn->connect_error);
}

$DeleteQuery="DELETE FROM Customers WHERE CustomerID=1";
 
$result=$conn->query($DeleteQuery);
if($result===true){
	echo 'Successfully Record Deleted.';
}else{
	echo 'Error:'.$conn->error;
}

$conn->close();
?>

MySQL Delete (Procedural)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=mysqli_connect($server,$username,$password,$db);

if(!$conn){
	die("Error:".mysqli_connect_error());
}
 
$DeleteQuery="DELETE FROM Customers WHERE CustomerID=1";
 
$result=mysqli_query($conn,$DeleteQuery);
if($result===true){
	echo 'Successfully Record Deleted.';
}else{
	echo 'Error:'.mysql_error($conn);
}


mysqli_close($conn);
?>


PHP MySql Update

PHP Have Query Method for all types of SQL Operations.

MySQL Update (Object Oriented)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=new mysqli($server,$username,$password,$db);

if($conn->connect_error){
	die("Error:".$conn->connect_error);
}

$UpdateQuery="UPDATE Customers SET PhoneNumber=03451234567 WHERE CustomerID=1";
 
$result=$conn->query($UpdateQuery);
if($result===true){
	echo 'Successfully Record Updated.';
}else{
	echo 'Erro:'.$conn->error;
}

$conn->close();
?>

MySQL Update (Procedural)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=mysqli_connect($server,$username,$password,$db);

if(!$conn){
	die("Error:".mysqli_connect_error());
}

$UpdateQuery="UPDATE Customers SET PhoneNumber=03451234567 WHERE CustomerID=1";
 
$result=mysqli_query($conn,$UpdateQuery);
if($result===true){
	echo 'Successfully Record Updated.';
}else{
	echo 'Error:'.mysql_error($conn);
}


mysqli_close($conn);
?>

PHP MySql Select

PHP Have Query Method for all types of SQL Operations.

MySQL Select (Object Oriented)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=new mysqli($server,$username,$password,$db);

if($conn->connect_error){
	die("Error:".$conn->connect_error);
}

$SelectQuery="SELECT FirstName,LastName,PhoneNumber FROM Customers";
 
$result=$conn->query($SelectQuery);
if($result->num_rows>0){
	//Output
	while($row=$result->fetch_assoc()){
		echo 'First Name:'.$row['FirstName'].'Last Name:'.$row['LastName'].'Phone#'.$row['PhoneNumber']."<br />";
	}
}else{
	echo 'No Record Found.';
}

$conn->close();
?>

MySQL Select (Procedural)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=mysqli_connect($server,$username,$password,$db);

if(!$conn){
	die("Error:".mysqli_connect_error());
}

$SelectQuery="SELECT FirstName,LastName,PhoneNumber FROM Customers";
 
$result=mysqli_query($conn,$SelectQuery);
if(mysqli_num_rows($result)>0){
	//Output
	while($row=mysqli_fetch_assoc($result)){
		echo 'First Name:'.$row['FirstName'].'Last Name:'.$row['LastName'].'Phone#'.$row['PhoneNumber']."<br />";
	}
}else{
	echo 'Erro:'.mysql_error($conn);
}

mysqli_close($conn);
?>

PHP MySql Insert

PHP Have Query Method for all types of SQL Operations.

MySQL Insert (Object Oriented)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=new mysqli($server,$username,$password,$db);

if($conn->connect_error){
	die("Error:".$conn->connect_error);
}

$InsertQuery="INSERT INTO Customers (FirstName,LastName,PhoneNumber,Address,Email)
 VALUES ('abc','xyz',0321000000,'abcd xyz','customer@gmail.com')";
 
$result=$conn->query($InsertQuery);
if($result===true){
	echo 'Successfully Record Inserted';
}else{
	echo 'Erro:'.$conn->error;
}

$conn->close();
?>

MySQL Insert (Procedural)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=mysqli_connect($server,$username,$password,$db);

if(!$conn){
	die("Error:".mysqli_connect_error());
}

$InsertQuery="INSERT INTO Customers (FirstName,LastName,PhoneNumber,Address,Email)
 VALUES ('abc','xyz',0321000000,'abcd xyz','customer@gmail.com')";
 
$result=mysqli_query($conn,$InsertQuery);
if($result===true){
	echo 'Successfully Record Inserted';
}else{
	echo 'Erro:'.mysql_error($conn);
}


mysqli_close($conn);
?>


PHP MySql Connect & Close

PHP have 3 ways to connect with Mysql and other Databases. below examples will demonstrate the MySqli (Object Oriented) and Mysqli Procedural Methods.

MySQL Connect & Close (Object Oriented)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=new mysqli($server,$username,$password,$db);

if($conn->connect_error){
	die("Error:".$conn->connect_error);
}

echo 'Successfully Connected:)';

$conn-close();
?>

MySQL Connect & Close (Procedural)

                    

<?php

$server="localhost";
$username="root";
$password="";
$db="e-commerce";

$conn=mysqli_connect($server,$username,$password,$db);

if(!$conn){
	die("Error:".mysqli_connect_error());
}

echo 'Successfully Connected:)';

mysqli_close($conn);
?>

PHP MySQL Database

PHP connect with Different Databases like Oracel, MS SQL Server, Mysql and etc.

Due to MySQL Performance & Speed Maximum PHP Apps are using MySQL.

What is MySQL

  • MySQL is a database system used on the web
  • MySQL is a database system that runs on a server and it is cross platform.
  • MySQL is ideal for both small and large applications
  • MySQL is very fast, reliable, and easy to use
  • MySQL uses standard SQL
  • MySQL is free to download and use and is developed, distributed, and supported by Oracle Corporation
  • MySQL is named after co-founder Monty Widenius’s daughter: My

The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows.

Databases are useful for storing information categorically. A E-commerce platform may have a database with the following tables:

  • Customers
  • Products
  • Shippers
  • Orders

MySQL Query

Standard SQL Queries Text Base which contains Some Special Keywords with Table name and tables fields. below is the example of Simple Select Query

                    

SELECT FirstName,LastName,PhoneNumber FROM Customers

PHP File Functions

PHP have plenty of other functions related to file operations. below section will describe some of important file functions.

Copy File Function

PHP Provides copy function which will move files from one directory to another and etc. copy function can also rename the file.

                    

	<?php
	//Copy file
	copy("file.txt","data/file1.txt") or die("File not found");
	?>

File Exists Function Example

File Exists function provide the functionality to check whether files exists or not before performing any operation on file.

                    

	<?php
	//Check File Exists or not ?
	if(file_exists("file.txt")){
		echo 'file exists';
	}else{
		echo 'file does not exists';
	}
	?>

File Move/Rename Function Example

PHP Copy function also provide the functionality to rename the file but the proper method to rename/move the file is rename function.

                    

	<?php
	//Move or Rename the file
	rename("file.txt","data/file1.txt") or die("File not found");
	?>

File Delete Function

PHP provides the delete function to remove the file during runtime.

                    

	<?php
	//Deleting the file
	if(unlink("file.txt")){
		echo "File has been deleted";
	}else{
		echo "unable to delete file";
	}
	?>


PHP File Open/Write

This section will provide details about php write functions.

Writing data to file

This example will demonstrate how to write data into a file.

                    

	<?php
	//Write a File
	$fh=fopen("file.txt",'w') or die("file not found"); //First Step Open a file with Write Mode
	$text="Line 1 \r\nLine 2 \r\nLine 3 \r\nLine 4"; //Prepare the data for file
	fwrite($fh,$text) or die('Unable to write to File');//Write the file by $fh object and string
	fclose($fh); //Close the File Object
	?>