PHP – Variable Scope

PHP – Variable Scope ”; Previous Next In PHP, the scope of a variable is the context within which it is defined and accessible to the extent in which it is accessible. Generally, a simple sequential PHP script that doesn’t have any loop or a function etc., has a single scope. Any variable declared inside the “<?php” and “?>” tag is available throughout the program from the point of definition onwards. Based on the scope, a PHP variable can be any of these three types − Local Variables Global Variables Static Variables A variable in a main script is also made available to any other script incorporated with include or require statements. Example In the following example, a “test.php” script is included in the main script. main.php <?php $var=100; include “test.php”; ?> test.php <?php echo “value of $var in test.php : ” . $var; ?> When the main script is executed, it will display the following output − value of $var in test.php : 100 However, when the script has a user defined function, any variable inside has a local scope. As a result, a variable defined inside a function can”t be accessed outside. Variables defined outside (above) the function have a global scope. Example Take a look at the following example − <?php $var=100; // global variable function myfunction() { $var1=”Hello”; // local variable echo “var=$var var1=$var1” . PHP_EOL; } myfunction(); echo “var=$var var1=$var1″ . PHP_EOL; ?> It will produce the following output − var= var1=Hello var=100 var1= PHP Warning: Undefined variable $var in /home/cg/root/64504/main.php on line 5 PHP Warning: Undefined variable $var1 in /home/cg/root/64504/main.php on line 8 Note that a global variable is not automatically available within the local scope of a function. Also, the variable inside a function is not accessible outside. The “global” Keyword To enable access to a global variable inside local scope of a function, it should be explicitly done by using the “global” keyword. Example The PHP script is as follows − <?php $a=10; $b=20; echo “Global variables before function call: a = $a b = $b” . PHP_EOL; function myfunction() { global $a, $b; $c=($a+$b)/2; echo “inside function a = $a b = $b c = $c” . PHP_EOL; $a=$a+10; } myfunction(); echo “Variables after function call: a = $a b = $b c = $c”; ?> It will produce the following output − Global variables before function call: a = 10 b = 20 inside function a = 10 b = 20 c = 15 Variables after function call: a = 20 b = 20 c = PHP Warning: Undefined variable $c in /home/cg/root/48499/main.php on line 12 Global variables can now be processed inside the function. Moreover, any changes made to the global variables inside the function will be reflected in the global namespace. $GLOBALS Array PHP stores all the global variables in an associative array called $GLOBALS. The name and value of the variables form the key-value pair. Example In the following PHP script, $GLOBALS array is used to access global variables − <?php $a=10; $b=20; echo “Global variables before function call: a = $a b = $b” . PHP_EOL; function myfunction() { $c=($GLOBALS[”a”]+$GLOBALS[”b”])/2; echo “c = $c” . PHP_EOL; $GLOBALS[”a”]+=10; } myfunction(); echo “Variables after function call: a = $a b = $b c = $c”; ?> It will produce the following output − Global variables before function call: a = 10 b = 20 c = 15 PHP Warning: Undefined variable $c in C:xampphtdocshello.php on line 12 Variables after function call: a = 20 b = 20 c = Static Variable A variable defined with static keyword is not initialized at every call to the function. Moreover, it retains its value of the previous call. Example Take a look at the following example − <?php function myfunction() { static $x=0; echo “x = $x” . PHP_EOL; $x++; } for ($i=1; $i<=3; $i++) { echo “call to function :$i : “; myfunction(); } ?> It will produce the following output − call to function :1 : x = 0 call to function :2 : x = 1 call to function :3 : x = 2 Print Page Previous Next Advertisements ”;

PHP – Classes and Objects

PHP – Classes and Objects ”; Previous Next The concept of classes and objects is central to PHP’s object-oriented programming methodology. A class is the template description of its objects. It includes the properties and functions that process the properties. An object is the instance of its class. It is characterized by the properties and functions defined in the class. Defining a Class in PHP To define a class, PHP has a keyword “class“. Similarly, PHP provides the keyword “new” to declare an object of any given class. The general form for defining a new class in PHP is as follows − <?php class phpClass { var $var1; var $var2 = “constant string”; function myfunc ($arg1, $arg2) { [..] } [..] } ?> The keyword class is followed by the name of the class that you want to define. Class name follows the same naming conventions as used for a PHP variable. It is followed by a pair of braces enclosing any number of variable declarations (properties) and function definitions. Variable declarations start with another reserved keyword var, which is followed by a conventional $variable name; they may also have an initial assignment to a constant value. Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data. Functions inside a class are also called methods. Example Here is an example which defines a class of Book type − class Book { /* Member variables */ var $price; var $title; /* Member functions */ function setPrice($par){ $this->price = $par; } function getPrice(){ echo $this->price .”<br/>”; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title .” <br/>”; } } The pseudo-variable $this is available when a method is called from within an object context. $this refers to the calling object. The Book class has two member variables (or properties) – $title and $price. The member variables (also sometimes called instance variables) usually have different values for each object; like each book has a title and price different from the other. The Book class has functions (functions defined inside the class are called methods) setTitle() and setPrice(). These functions are called with reference to an object and a parameter, used to set the value of title and price member variables respectively. The Book class also has getTitle() and getPrice() methods. When called, they return the title and price of the object whose reference is passed. Once a class is defined, you can declare one or more objects, using new operator. $b1 = new Book; $b2 = new Book; The new operator allocates the memory required for the member variables and methods of each object. Here we have created two objects and these objects are independent of each other and they will have their existence separately. Each object has access to its member variables and methods with the “->” operator. For example, the $title property of b1 object is “$b1->title” and to call setTitle() method, use the “$b1->setTitle()” statement. To set the title and price of b1 object, $b1->setTitle(“PHP Programming”); $b1->setPrice(450); Similarly, the following statements fetch the title and price of b1 book − echo $b1->getPrice(); echo $b1->getTitle(); Example Given below is the complete PHP script that defines Book class, declares two objects and calls the member functions. <?php class Book { /* Member variables */ var $price; var $title; /* Member functions */ function setPrice($par){ $this->price = $par; } function getPrice(){ echo $this->price .”n”; } function setTitle($par){ $this->title = $par; } function getTitle(){ echo $this->title .”n”; } } $b1 = new Book; $b2 =new Book; $b1->setTitle(“PHP Programming”); $b1->setPrice(450); $b2->setTitle(“PHP Fundamentals”); $b2->setPrice(275); $b1->getTitle(); $b1->getPrice(); $b2->getTitle(); $b2->getPrice(); ?> It will produce the following output − PHP Programming 450 PHP Fundamentals 275 Print Page Previous Next Advertisements ”;

PHP – Comparison Operators

PHP – Comparison Operators Examples ”; Previous Next In PHP, Comparison operators are used to compare two values and determine their relationship. These operators return a Boolean value, either True or False, based on the result of the comparison. The following table highligts the comparison operators that are supported by PHP. 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 false < 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 false <= 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 Additionally, these operators can also be combined with logical operators (&&, ||, !) to form complex conditions for decision making in PHP programs. Example The following example shows how you can use these comparison operators in PHP − <?php $a = 42; $b = 20; if ($a == $b) { echo “TEST1 : a is equal to b n”; } else { echo “TEST1 : a is not equal to b n”; } if ($a > $b) { echo “TEST2 : a is greater than b n”; } else { echo “TEST2 : a is not greater than b n”; } if ($a < $b) { echo “TEST3 : a is less than b n”; } else { echo “TEST3 : a is not less than b n”; } if ($a != $b) { echo “TEST4 : a is not equal to b n”; } else { echo “TEST4 : a is equal to b n”; } if ($a >= $b) { echo “TEST5 : a is either greater than or equal to b n”; } else { echo “TEST5 : a is neither greater than nor equal to b n”; } if ($a <= $b) { echo “TEST6 : a is either less than or equal to b n”; } else { echo “TEST6 : a is neither less than nor equal to b”; } ?> It will produce the following output − TEST1 : a is not equal to b TEST2 : a is greater than b TEST3 : a is not less than b TEST4 : a is not equal to b TEST5 : a is either greater than or equal to b TEST6 : a is neither less than nor equal to b Print Page Previous Next Advertisements ”;

PHP – $_SERVER

PHP – $_SERVER ”; Previous Next $_SERVER is a superglobal in PHP. It holds information regarding HTTP headers, path and script location, etc. $_SERVER is an associative array and it holds all the server and execution environment related information. Most of the entries in this associative array are populated by the web server. The entries may change from one web server to other, as servers may omit some, or provide others. For a PHP script running on the command line, most of these entries will not be available or have any meaning. PHP will also create additional elements with values from request headers. These entries will be named “HTTP_” followed by the header name, capitalized and with underscores instead of hyphens. For example, the “Accept-Language” header would be available as $_SERVER[”HTTP_ACCEPT_LANGUAGE”]. PHP versions prior to 5.4.0 had $HTTP_SERVER_VARS which contained the same information but it has now been removed. The following table lists some of the important server variables of the $_SERVER array followed by the description of their values. Sr.No Server Variables & Description 1 PHP_SELF Stores filename of currently executing script. 2 SERVER_ADDR This property of array returns the IP address of the server under which the current script is executing. 3 SERVER_NAME Name of server host under which the current script is executing. In case of a server running locally, localhost is returned. 4 QUERY_STRING A query string is the string of key value pairs separated by the “&” symbol and appended to the URL after the “?” symbol. For example, http://localhost/testscript?name=xyz&age=20 URL returns trailing query string 5 REQUEST_METHOD HTTP request method used for accessing a URL, such as POST, GET, POST, PUT or DELETE. In the above query string example, a URL attached to query string with the “?” symbol requests the page with GET method 6 DOCUMENT_ROOT Returns the name of the directory on the server that is configured as the document root. On XAMPP apache server, it returns htdocs as the name of document root c:/xampp/htdocs 7 REMOTE_ADDR IP address of the machine from where the user is viewing the current page. 8 SERVER_PORT Port number on which the web server is listening to the incoming request. Default is 80 Example The following script invoked from document root of XAMPP server lists all the server variables − <?php foreach ($_SERVER as $k=>$v) echo $k . “=>” . $v . “n”; ?> It will produce the following output − MIBDIRS=>C:/xampp/php/extras/mibs MYSQL_HOME=>xamppmysqlbin OPENSSL_CONF=>C:/xampp/apache/bin/openssl.cnf PHP_PEAR_SYSCONF_DIR=>xamppphp PHPRC=>xamppphp TMP=>xampptmp HTTP_HOST=>localhost HTTP_CONNECTION=>keep-alive HTTP_SEC_CH_UA=>”Chromium”;v=”116″, “Not) A;Brand”;v=”24″, “Google Chrome”;v=”116″ HTTP_SEC_CH_UA_MOBILE=>?0 HTTP_SEC_CH_UA_PLATFORM=>”Windows” HTTP_DNT=>1 HTTP_UPGRADE_INSECURE_REQUESTS=>1 HTTP_USER_AGENT=>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 HTTP_ACCEPT=>text/html,application/xhtml+xml,application/xml; q=0.9,image/avif,image/webp,image/apng,*/*; q=0.8,application/signed-exchange;v=b3;q=0.7 HTTP_SEC_FETCH_SITE=>none HTTP_SEC_FETCH_MODE=>navigate HTTP_SEC_FETCH_USER=>?1 HTTP_SEC_FETCH_DEST=>document HTTP_ACCEPT_ENCODING=>gzip, deflate, br HTTP_ACCEPT_LANGUAGE=>en-US,en;q=0.9,mr;q=0.8 PATH=>C:Python311Scripts; C:Python311;C:WINDOWSsystem32; C:WINDOWS;C:WINDOWSSystem32Wbem; C:WINDOWSSystem32WindowsPowerShellv1.0; C:WINDOWSSystem32OpenSSH;C:xamppphp; C:UsersuserAppDataLocalMicrosoftWindowsApps; C:VSCodeMicrosoft VS Codebin SystemRoot=>C:WINDOWS COMSPEC=>C:WINDOWSsystem32cmd.exe PATHEXT=>.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW WINDIR=>C:WINDOWS SERVER_SIGNATURE=> Apache/2.4.56 (Win64) OpenSSL/1.1.1t PHP/8.0.28 Server at localhost Port 80 SERVER_SOFTWARE=>Apache/2.4.56 (Win64) OpenSSL/1.1.1t PHP/8.0.28 SERVER_NAME=>localhost SERVER_ADDR=>::1 SERVER_PORT=>80 REMOTE_ADDR=>::1 DOCUMENT_ROOT=>C:/xampp/htdocs REQUEST_SCHEME=>http CONTEXT_PREFIX=> CONTEXT_DOCUMENT_ROOT=>C:/xampp/htdocs SERVER_ADMIN=>postmaster@localhost SCRIPT_FILENAME=>C:/xampp/htdocs/hello.php REMOTE_PORT=>54148 GATEWAY_INTERFACE=>CGI/1.1 SERVER_PROTOCOL=>HTTP/1.1 REQUEST_METHOD=>GET QUERY_STRING=> REQUEST_URI=>/hello.php SCRIPT_NAME=>/hello.php PHP_SELF=>/hello.php REQUEST_TIME_FLOAT=>1694802456.9816 REQUEST_TIME=>1694802456 Print Page Previous Next Advertisements ”;

PHP – Open File

PHP – Open File ”; Previous Next PHP’s built-in function library provides fopen() function to open a file or any other stream and returns its “reference pointer”, also called as “handle”. The fopen() function in PHP is similar to fopen() in C, except that in C, it cannot open a URL. Syntax of fopen() The fopen() function has the following signature − fopen( string $filename, string $mode, bool $use_include_path = false, ?resource $context = null ): resource|false The $filename and $mode parameters are mandatory. Here’s the explanation of the parameters − $filename − This parameter is a string representing the resource to be opened. It may be a file in the local filesystem, or on a remote server with the scheme:// prefix. $mode − A string that represents the type of access given to the file/resource. $use_include_path − A Boolean optional parameter can be set to ”1” or true if you want to search for the file in the include_path, too. $context − A context stream resource. Modes of Opening a File PHP allows a file to be opened in the following modes − Modes Description r Open a file for read only. w Open a file for write only. creates a new file even if it exists. a Open a file in append mode x Creates a new file for write only. r+ Open a file for read/write. w+ Open a file for read/write. creates a new file even if it exists. a+ Open a file for read/write in append mode. x+ Creates a new file for read/write. c Open the file for writing, if it doesn’t exist. However, if it exists, it isn’t truncated (as in w mode). c++ Open the file for read/write, if it doesn’t exist. However, if it exists, it isn’t truncated (as in w mode). e Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems. If the fopen() function is successfully executed, it returns a “file pointer” or “handle” resource bound to the file stream. However, if it fails, it returns false with E_WARNING being emitted. $handle = fopen(”a.txt, ”r”); var_dump($handle); If the file exists in the current directory, the success is shown by the output − resource(5) of type (stream) If not, you get the following error message − Warning: fopen(a.txt): Failed to open stream: No such file or directory in a.php on line 2 bool(false) Examples The following examples show different usages of the fopen() function − <?php $handle = fopen(“hello.txt”, “w”); $handle = fopen(“c:/xampp/htdocs/welcome.png”, “rb”); $handle = fopen(“http://localhost/hello.txt”, “r”); ?> Note that this function may also succeed when the filename is a directory. In that case, you may need to use the is_dir() function to check whether it is a file before doing any read/write operations. Once a file is opened, you can write data in it with the help of functions such as fwrite() or fputs(), and read data from it with fread() and fgets() functions. Closing a File It is always recommended to close the open stream referenced by the handle − fclose($handle); Print Page Previous Next Advertisements ”;

PHP – Write File

PHP – Write File ”; Previous Next PHP’s built-in function library provides two functions to perform write operations on a file stream. These functions are fwrite() and fputs(). To be able to write data in a file, it must be opened in write mode (w), append mode (a), read/write mode (r+ or w+) or binary write/append mode (rb+, wb+ or wa). The fputs() Function The fputs() function writes a string into the file opened in a writable mode. fputs(resource $stream, string $string, int $length) Here, the $stream parameter is a handle to a file opened in a writable mode. The $string parameter is the data to be written, and $length is an optional parameter that specifies the maximum number of bytes to be written. The fputs() function returns the number of bytes written, or false if the function is unsuccessful. Example The following code opens a new file, writes a string in it, and returns the number of bytes written. <?php $fp = fopen(“hello.txt”, “w”); $bytes = fputs($fp, “Hello Worldn”); echo “bytes written: $bytes”; fclose($fp); ?> It will produce the following output − bytes written: 12 Example If you need to add text in an earlier existing file, it must be opened in append mode (a). Let us add one more string in the same file in previous example. <?php $fp = fopen(“hello.txt”, “a”); $bytes = fputs($fp, “Hello PHP”); echo “bytes written: $bytes”; fclose($fp); ?> If you open the “hello.txt” file in a text editor, you should see both the lines in it. Example In the following PHP script, an already existing file (hello.txt) is read line by line in a loop, and each line is written to another file (new.txt) It is assumed thar “hello.txt” consists of following text − Hello World TutorialsPoint PHP Tutorials Here is the PHP code to create a copy of an existing file − <?php $file = fopen(“hello.txt”, “r”); $newfile = fopen(“new.txt”, “w”); while(! feof($file)) { $str = fgets($file); fputs($newfile, $str); } fclose($file); fclose($newfile); ?> The newly created “new.txt” file should have exactly the same contents. The fwrite() Function The frwrite() function is a counterpart of fread() function. It performs binary-safe write operations. fwrite(resource $stream, string $data, ?int $length = null): int|false Here, the $stream parameter is a resource pointing to the file opened in a writable mode. Data to be written to the file is provided in the $data parameter. The optional $length parameter may be provided to specify the number of bytes to be written. It should be int, writing will stop after length bytes have been written or the end of data is reached, whichever comes first. The fwrite() function returns the number of bytes written, or false on failure along with E_WARNING. Example The following program opens a new file, performs write operation and displays the number of bytes written. <?php $file = fopen(“/PhpProject/sample.txt”, “w”); echo fwrite($file, “Hello Tutorialspoint!!!!!”); fclose($file); ?> Example In the example code given below, an existing file “welcome.png” in opened in binary read mode. The fread() function is used to read its bytes in “$data” variable, and in turn written to another file “new.png” − <?php $name = “welcome.png”; $file = fopen($name, “rb”); $newfile = fopen(“new.png”, “wb”); $size = filesize($name); $data = fread($file, $size); fwrite($newfile, $data, $size); fclose($file); fclose($newfile); ?> Run the above code. The current directory should now have a copy of the existing “welcome.png” file. Print Page Previous Next Advertisements ”;

PHP – $_POST

PHP – $_POST ”; Previous Next $_POST is one of the predefined or superglobal variables in PHP. It is an associative array of key-value pairs passed to a URL by the HTTP POST method that uses URLEncoded or multipart/form-data content-type in the request. $HTTP_POST_VARS also contains the same information as $_POST, but is not a superglobal, and now been deprecated. The easiest way to send data to a server with POST request is specifying the method attribute of HTML form as POST. Assuming that the URL in the browser is “http://localhost/hello.php”, method=POST is set in a HTML form “hello.html” as below − <html> <body> <form action=”hello.php” method=”post”> <p>First Name: <input type=”text” name=”first_name”/> </p> <p>Last Name: <input type=”text” name=”last_name” /> </p> <input type=”submit” value=”Submit” /> </form> </body> </html> The “hello.php” script (in the document root folder) for this exercise is as follows: <?php echo “<h3>First name: ” . $_POST[”first_name”] . “<br /> ” . “Last Name: ” . $_POST[”last_name”] . “</h3>”; ?> Now, open http://localhost/hello.html in your browser. You should get the following output on the screen − As you press the Submit button, the data will be submitted to “hello.php” with the POST method. You can also mix the HTML form with PHP code in hello.php, and post the form data to itself using the “PHP_SELF” variable − <html> <body> <form action=”<?php echo $_SERVER[”PHP_SELF”];?>” method=”post”> <p>First Name: <input type=”text” name=”first_name”/> </p> <br /> <p>Last Name: <input type=”text” name=”last_name” /></p> <input type=”submit” value=”Submit” /> </form> <?php echo “<h3>First Name: ” . $_POST[”first_name”] . “<br /> ” . “Last Name: ” . $_POST[”last_name”] . “</h3>”; ?> </body> </html> It will produce the following output − Print Page Previous Next Advertisements ”;

PHP – Copy File

PHP – Copy File ”; Previous Next You can copy an existing file to a new file in three different ways − Reading a line from one and writing to another in a loop Reading entire contents to a string and writing the string to another file Using PHP’s built-in function library includes copy() function. Method 1 In the first approach, you can read each line from an existing file and write into a new file till the existing file reaches the end of file. In the following PHP script, an already existing file (hello.txt) is read line by line in a loop, and each line is written to another file (new.txt) It is assumed that “hello.txt” contains the following text − Hello World TutorialsPoint PHP Tutorials Example Here is the PHP code to create a copy of an existing file − <?php $file = fopen(“hello.txt”, “r”); $newfile = fopen(“new.txt”, “w”); while(! feof($file)) { $str = fgets($file); fputs($newfile, $str); } fclose($file); fclose($newfile); ?> The newly created “new.txt” file should have exactly the same contents. Method 2 Here we use two built-in functions from the PHP library − file_get_contents( string $filename, bool $use_include_path = false, ?resource $context = null, int $offset = 0, ?int $length = null ): string|false This function reads the entire file into a string. The $filename parameter is a string containing the name of the file to be read The other function is − file_put_contents( string $filename, mixed $data, int $flags = 0, ?resource $context = null ): int|false The function puts the contents of $data in $filename. It returns the number of bytes written. Example In the following example, we read contents of “hello.txt” in a string $data, and use it as a parameter to write into “test.txt” file. <?php $source = “hello.txt”; $target = “test.txt”; $data = file_get_contents($source); file_put_contents($target, $data); ?> Method 3 PHP provides the copy() function, exclusively to perform copy operation. copy(string $from, string $to, ?resource $context = null): bool The $from parameter is a string containing the existing file. The $to paramenter is also a string containing the name of the new file to be created. If the target file already exists, it will be overwritten. The copy operation will return true or false based on the file being successfully copied or not. Example Let”s use the copy() function to make “text.txt” as a copy of “hello.txt” file. <?php $source = “a.php”; $target = “a1.php”; if (!copy($source, $target)) { echo “failed to copy $source…n”; } ?> Print Page Previous Next Advertisements ”;

PHP – File Handling

PHP – File Handling ”; Previous Next In PHP, a file is a resource object, from which data can be read or written to in a linear fashion. The term “file handling” refers to a set of functions in PHP that enable read/write operations on disk files with PHP code. A file object is classified as a stream. Any resource on which linear read/write operations are done is a stream. Other stream-like objects are the TCP sockets, standard input stream, i.e., a system keyboard represented by “php://stdin”, the standard output stream represented by “php://stdout”, and the error stream “php://stderr”. Note − Tthe constants STDIN, STDOUT, and STDERR stand for the respective standard streams. Although PHP is regarded as a server-side scripting language for developing web applications, PHP also has a command-line interface to perform console IO operations. Example The readline() function in PHP accepts the user input from a standard keyboard, and echo/print statements render the output on the console. <?php $str = readline(“Type something:”); echo $str; ?> It will produce the following output − C:xamppphp>php hello.php Type something: Are you enjoying this PHP tutorial? Are you enjoying this PHP tutorial? Example We can obtain the same effect by reading the input from “php://stdin” and outputting it to “php://stdout”. <?php $f = fopen(“php://stdin”, “r”); echo “Type something: “; $str = fgets($f); $f1 = fopen(“php://stdout”, “w”); fputs($f1, $str); ?> Here, the fopen() function is used to open the stdin stream for reading and the stdout stream for writing. Example PHP supports a variety of stream protocols for stream related functions such as fopen(), file_exists(), etc. Use php_get_wrappers() function to get a list of all the registered wrappers. <?php print_r(stream_get_wrappers()); ?> It will produce the following output − Array ( [0] => php [1] => file [2] => glob [3] => data [4] => http [5] => ftp [6] => zip [7] => compress.zlib [8] => compress.bzip2 [9] => https [10] => ftps [11] => phar ) The streams are referenced as “scheme://target”. For instance, the file stream is “file://xyz.txt”. The input data from the console is stored in the computer”s main memory (RAM) until the application is running. Thereafter, the memory contents from RAM are erased. We would like to store it in such a way that it can be retrieved whenever required in a persistent medium such as a disk file. Hence, instead of the standard streams (keyboard for input and the display device for output), we will use the disk files for reading the data, and destination for storing the data. In addition to the read and write modes as used in the above example (IO operations with standard streams), the file stream can be opened in various other modes like “r+” and “w+” for simultaneous read/write, “b” for binary mode, etc. To open a disk file for reading and obtain its reference pointer, use the fopen() function. $handle = fopen(”file://” . __DIR__ . ”/data.txt”, ”r”); The “file://” scheme is the default. Hence, it can be easily dropped, especially when dealing with local files. Note − It is always recommended to close the stream that was opened. Use the fclose() function for this purpose. fclose($handle); PHP has several built-in functions for performing read/write operations on the file stream. In the subsequent chapters, we shall explore the filesystem functions. Print Page Previous Next Advertisements ”;

PHP – Default Arguments

PHP – Default Arguments ”; Previous Next Like most of the languages that support imperative programming, a function in PHP may have one or more arguments that have a default value. As a result, such a function may be called without passing any value to it. If there is no value meant to be passed, the function will take its default value for processing. If the function call does provide a value, the default value will be overridden. function fun($arg1 = val1, $arg2 = val2) { Statements; } Such a function can be called in different ways − fun(); # Function will use defaults for both arguments fun($x); # Function passes $x to arg1 and uses default for arg2 fun($x, $y); # Both arguments use the values passed Example 1 Here we define a function called greeting() with two arguments, both having string as their default values. We call it by passing one string, two strings and without any argument. <?php function greeting($arg1=”Hello”, $arg2=”world”) { echo $arg1 . ” “. $arg2 . PHP_EOL; } greeting(); greeting(“Thank you”); greeting(“Welcome”, “back”); greeting(“PHP”); ?> It will produce the following output − Hello world Thank you world Welcome back PHP world Example 2 You can define a function with only some of the arguments with default value, and the others to which the value must be passed. <?php function greeting($arg1, $arg2=”World”) { echo $arg1 . ” “. $arg2 . PHP_EOL; } # greeting(); ## This will raise ArgumentCountError greeting(“Thank you”); greeting(“Welcome”, “back”); ?> It will produce the following output − Thank you World Welcome back The first call (without argument) raises ArgumentCountError because you must pass value for the first argument. If only one value is passed, it will be used by the first argument in the list. However, if you declare arguments with default before arguments without defaults, such function can be only called if values for both are passed. You cannot have a situation where the first argument uses the default, and the second using the passed value. The greeting() function now has $arg1 with default and $arg2 without any default value. function greeting($arg1=”Hello”, $arg2) { echo $arg1 . ” “. $arg2 . PHP_EOL; } If you pass a string “PHP” − greeting(“PHP”); with the intension to print the result as “Hello PHP”, the following error message will be displayed. PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function greeting(), 1 passed in hello.php on line 10 and exactly 2 expected Example 3 Let”s define a function percent() that calculates the percentage of marks in three subjects. Assuming that the marks in each subject are out of 100, the $total argument in the function definition is given a default value as 300. <?php function percent($p, $c, $m, $ttl=300) { $per = ($p+$c+$m)*100/$ttl; echo “Marks obtained: n”; echo “Physics = $p Chemistry = $c Maths = $m n”; echo “Percentage = $per n”; } percent(50, 60, 70); ?> It will produce the following output − Marks obtained: Physics = 50 Chemistry = 60 Maths = 70 Percentage = 60 However, if the maximum marks in each subject is 50, then you must pass the fourth value to the function, otherwise the percentage will be calculated out of 300 instead of 150. <?php function percent($p, $c, $m, $ttl=300) { $per = ($p+$c+$m)*100/$ttl; echo “Marks obtained: n”; echo “Physics = $p Chemistry = $c Maths = $m n”; echo “Percentage = $per n”; } percent(30, 35, 40, 150); ?> It will produce the following output − Marks obtained: Physics = 30 Chemistry = 35 Maths = 40 Percentage = 70 Print Page Previous Next Advertisements ”;