Friday, 25 March 2016

Unlink() vs Unset() in PHP, Difference

Unlink() vs Unset() in PHP, Difference


Unlink() vs Unset() in PHP, Difference

These function are mainly asked in interviews, Here is the difference between these two functions.

Unlink


In PHP, unlink() is used to completely delete files from the directory.

Syntax: unlink(filename,context) 

filename Required. Specifies the file to delete
context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream


 Example: 

Create a file hello.txt with some content inside it and give permission wrx.

create a file name as filetest.php and paste the below content

<?php
$source         = "/var/www/myFolder/hello.txt";
unlink($source);
?>


Before running the script please change the file permission to rwx.
Now run this file in browser or php mytest.php for Linux user .

After performing the above operation you will see that the file you have created has deleted from the directory.


unset()


It is used to delete the content from a variable.

Syntax:  unset (var1, var2.... )

var1: name of variable to unset
var2: name of variable to unset[optional]

Example:

create a file name as filetest.php and paste the below content

<?php
$welcome_text = "Welcome to myblog";
unset($welcome_text);
if(isset($welcome_text)) 
{
    echo "My welcome text is:" . $welcome_text;
} else  
{
  echo "My welcome text is: empty";
}
?>


Before running the script please change the file permission to rwx.
Now run this file in browser or php mytest.php for Linux user .

When you run this script you see the output 


My welcome text is: empty


This is because you have unset the value of the variable 

After performing the above operation you will see that the file you have created has no contents inside it.



Please do comments if you have any query.







No comments:

Post a Comment