PHP – PDO Extension

PHP – PDO Extension ”; Previous Next PDO is an acronym for PHP Data Objects. PHP can interact with most of the relational as well as NOSQL databases. The default PHP installation comes with vendor-specific database extensions already installed and enabled. In addition to such database drivers specific to a certain type of database, such as the mysqli extension for MySQL, PHP also supports abstraction layers such as PDO and ODBC. The PDO extension defines a lightweight, consistent interface for accessing databases in PHP. The functionality of each vendor-specific extension varies from the other. As a result, if you intend to change the backend database of a certain PHP application, say from PostGreSql to MySQL, you need to make a lot of changes to the code. The PDO API on the other hand doesn’t require any changes apart from specifying the URL and the credentials of the new database to be used. Your current PHP installation must have the corresponding PDO driver available to be able to work with. Currently the following databases are supported with the corresponding PDO interfaces − Driver Name Supported Databases PDO_CUBRID Cubrid PDO_DBLIB FreeTDS / Microsoft SQL Server / Sybase PDO_FIREBIRD Firebird PDO_IBM IBM DB2 PDO_INFORMIX IBM Informix Dynamic Server PDO_MYSQL MySQL 3.x/4.x/5.x/8.x PDO_OCI Oracle Call Interface PDO_ODBC ODBC v3 (IBM DB2, unixODBC and win32 ODBC) PDO_PGSQL PostgreSQL PDO_SQLITE SQLite 3 and SQLite 2 PDO_SQLSRV Microsoft SQL Server / SQL Azure By default, the PDO_SQLITE driver is enabled in the settings of php.ini, so if you wish to interact with a MySQL database with PDO, make sure that the following line is uncommented by removing the leading semicolon. extension=pdo_mysql You can obtain the list of currently available PDO drivers by calling PDO::getAvailableDrivers() static function in PDO class. PDO Connection An instance of PDO base class represents a database connection. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any). The following snippet is a typical way of establishing connection with a MySQL database − <?php $dbh = new PDO(”mysql:host=localhost;dbname=test”, $user, $pass); ?> If there is any connection error, a PDOException object will be thrown. Example Take a look at the following example − <?php $dsn=”localhost”; $dbName=”myDB”; $username=”root”; $password=””; try{ $dbConn= new PDO(“mysql:host=$dsn;dbname=$dbName”,$username,$password); Echo “Successfully connected with $dbName database”; } catch(Exception $e){ echo “Connection failed” . $e->getMessage(); } ?> It will produce the following output − Successfully connected with myDB database In case of error − Connection failedSQLSTATE[HY000] [1049] Unknown database ”mydb” PDO Class Methods The PDO class defines the following static methods − PDO::beginTransaction After obtaining the connection object, you should call this method to that initiates a transaction. public PDO::beginTransaction(): bool This method turns off autocommit mode. Hence, you need to call commit() method to make persistent changes to the database Calling rollBack() will roll back all changes to the database and return the connection to autocommit mode.This method returns true on success or false on failure. PDO::commit The commit() method commits a transaction. public PDO::commit(): bool Since the BeginTransaction disables the autocommit mode, you should call this method after a transaction. It commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction. This method returns true on success or false on failure. PDO::exec The exec() method executes an SQL statement and return the number of affected rows public PDO::exec(string $statement): int|false The exec() method executes an SQL statement in a single function call, returning the number of rows affected by the statement. Note that it does not return results from a SELECT statement. If you have a SELECT statement that is to be executed only once during your program, consider issuing PDO::query(). On the other hand For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute(). The exec() method need a string parameter that represents a SQL statement to prepare and execute, and returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0. PDO::query The query() method prepares and executes an SQL statement without placeholders public PDO::query(string $query, ?int $fetchMode = null): PDOStatement|false This method prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object. PDO::rollBack The rollback() method rolls back a transaction as initiated by PDO::beginTransaction(). public PDO::rollBack(): bool If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction. Note that some databases, including MySQL, automatically issue an implicit COMMIT when a DDL statement such as DROP TABLE or CREATE TABLE is issued within a transaction, and hence it will prevent you from rolling back any other changes within the transaction boundary. This method returns true on success or false on failure. Example The following code creates a student table in the myDB database on a MySQL server. <?php $dsn=”localhost”; $dbName=”myDB”; $username=”root”; $password=””; try{ $conn= new PDO(“mysql:host=$dsn;dbname=$dbName”,$username,$password); Echo “Successfully connected with $dbName database”; $qry = <<<STRING CREATE TABLE IF NOT EXISTS STUDENT ( student_id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, marks

PHP – Filtered unserialize()

PHP – Filtered unserialize() ”; Previous Next In PHP, the built-in function unserialize() is available from PHP version 4 onwards. With PHP 7, a provision to pass a list of allowed classes has been added. This allows the untrusted source to be filtered out. The unserialze() function unserializes the data from only the trusted classes. In PHP, serialization means generation of a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure. The built-in serialize() function is used for this purpose. serialize(mixed $value): string The unserialze() function gives a PHP value from the serialized representation. From PHP 7 onwards, the unserialize() function follows the format below − unserialize(string $data, array $options = [ ]): mixed The $data parameter is the serialized string which you want to unserialize. The $options parameter has been newly introduced. It is an associative array of following keys − Sr.No Name & Description 1 allowed_classes an array of class names which should be accepted, or false to accept no classes, or true to accept all classes. Omitting this option is the same as defining it as true 2 max_depth The maximum depth of structures permitted during unserialization. Example Take a look at the following example − <?php class MyClass { var int $x; function __construct(int $x) { $this->x = $x; } } class NewClass { var int $y; function __construct(int $y) { $this->y = $y; } } $obj1 = new MyClass(10); $obj2 = new NewClass(20); $sob1 = serialize($obj1); $sob2 = serialize($obj2); // default behaviour that accepts all classes // second argument can be ommited. // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object $usob1 = unserialize($sob1 , [“allowed_classes” => true]); // converts all objects into __PHP_Incomplete_Class object except those of MyClass and NewClass $usob2 = unserialize($sob2 , [“allowed_classes” => [“MyClass”, “NewClass”]]); echo $usob1->x . PHP_EOL; echo $usob2->y . PHP_EOL; ?> It will produce the following output − 10 20 Print Page Previous Next Advertisements ”;

PHP – Expectations

PHP – Expectations ”; Previous Next Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails. assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested. Configuration Directives for assert() The following table lists down the configuration directives for the assert() function − Directive Default value Possible values zend.assertions 1 1 − generate and execute code (development mode) 0 − generate code but jump around it at runtime -1 − do not generate code (production mode) assert.exception 0 1 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided. 0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour) Parameters Assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed. Description − An optional description that will be included in the failure message, if the assertion fails. Exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled. Return Values FALSE if the assertion is false, TRUE otherwise. Example Take a look at the following example − <?php ini_set(”assert.exception”, 1); class CustomError extends AssertionError {} assert(false, new CustomError(”Custom Error Message!”)); ?> It will produce the following output − PHP Fatal error: Uncaught CustomError: Custom Error Message! In test.php:6 Print Page Previous Next Advertisements ”;

PHP – AJAX XML Parser

PHP – AJAX XML Parser ”; Previous Next Using PHP with AJAX, we can parse an XML document from local directory as well as on a server. The following example demonstrates how to parse XML with web browser. The client-end script renders a HTML form and defines a JavaScript function for sending a HTTP request to the server with XMLHttpRequest object. On the server, a PHP script loads the DOM object from the required XML document, fetches the selected course from $_REQUEST variable, and renders the details of the course chosen as the response back to the client. Step 1 The following XML document is stored on the document root of the XAMPP server. <?xml version = “1.0” encoding = “utf-8”?> <CATALOG> <SUBJECT> <COURSE>Android</COURSE> <COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY> <PRICE>$10</PRICE> <YEAR>2015</YEAR> </SUBJECT> <SUBJECT> <COURSE>Html</COURSE> <COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY> <PRICE>$15</PRICE> <YEAR>2015</YEAR> </SUBJECT> <SUBJECT> <COURSE>Java</COURSE> <COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY> <PRICE>$20</PRICE> <YEAR>2015</YEAR> </SUBJECT> <SUBJECT> <COURSE>Microsoft</COURSE> <COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY> <PRICE>$25</PRICE> <YEAR>2015</YEAR> </SUBJECT> </CATALOG> Step 2 The AJAX code below has a HTML form and a JavaScript function to raise HTTP request through XMLHttpRequest object. <html> <head> <script> function showCD(str) { if (str == “”) { document.getElementById(“txtHint”).innerHTML = “”; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById(“txtHint”).innerHTML = xmlhttp.responseText; } } xmlhttp.open(“GET”,”hello.php?q=”+str,true); xmlhttp.send(); } </script> </head> <body> <form> Select a Course: <select name = “cds” onchange = “showCD(this.value)”> <option value = “”>Select a course:</option> <option value = “Android”>Android </option> <option value = “Html”>HTML</option> <option value = “Java”>Java</option> <option value = “Microsoft”>MS technologies</option> </select> </form> <div id = “txtHint”><b>Course info will be listed here…</b></div> </body> </html> Step 3 The server-side PHP script to search within the XML document is as follows − <?php $q = $_GET[“q”]; $xmlDoc = new DOMDocument(); $xmlDoc->load(“test.xml”); $x = $xmlDoc->getElementsByTagName(”COURSE”); for ($i = 0; $i<=$x->length-1; $i++) { if ($x->item($i)->nodeType == 1) { if ($x->item($i)->childNodes->item(0)->nodeValue == $q) { $y = ($x->item($i)->parentNode); } } } $cd = ($y->childNodes); for ($i = 0;$i<$cd->length;$i++) { if ($cd->item($i)->nodeType == 1) { echo(“<b>” . $cd->item($i)->nodeName . “:</b> “); echo($cd->item($i)->childNodes->item(0)->nodeValue); echo(“<br>”); } } ?> Visit “http://localhost/example.php” to let the user select a course. Upon selection, the relevant details are fetched from the server and displayed as below − Print Page Previous Next Advertisements ”;

PHP – IntlChar

PHP – IntlChar ”; Previous Next In PHP7, a new IntlChar class has been introduced. It provides access to a number of utility methods that can be used to access information about Unicode characters. There are a number of static methods and constants in Intl class. They adhere closely to the names and behavior used by the underlying ICU (International Components for Unicode) library. Note that you need to enable the Intl extension in the PHP installation in your system. To enable, open php.ini file and uncomment (remove the leading semicolon from the line) extension=intl Some static functions from Intl class are explained with examples as below − IntlChar::charAge This function gets the “age” of the code point public static IntlChar::charAge(int|string $codepoint): ?array The “age” is the Unicode version when the code point was first designated (as a non-character or for Private Use) or assigned a character. Example Take a look at the following example − <?php var_dump(IntlChar::charage(“u{2603}”)); ?> It will produce the following output − array(4) { [0]=> int(1) [1]=> int(1) [2]=> int(0) [3]=> int(0) } IntlChar::charFromName The charFromName() function finds Unicode character by name and return its code point value public static IntlChar::charFromName(string $name, int $type = IntlChar::UNICODE_CHAR_NAME): ?int The type parameter sets of names to use for the lookup. Can be any of these constants − IntlChar::UNICODE_CHAR_NAME (default) IntlChar::UNICODE_10_CHAR_NAME IntlChar::EXTENDED_CHAR_NAME IntlChar::CHAR_NAME_ALIAS IntlChar::CHAR_NAME_CHOICE_COUNT Example Take a look at the following example − <?php var_dump(IntlChar::charFromName(“LATIN CAPITAL LETTER A”)); var_dump(IntlChar::charFromName(“SNOWMAN”)); ?> It will produce the following output − int(65) int(9731) IntlChar::charName The charName() function retrieves the name of a Unicode character public static IntlChar::charName(int|string $codepoint, int $type = IntlChar::UNICODE_CHAR_NAME): ?string Example Take a look at the following example − <?php var_dump(IntlChar::charName(“.”, IntlChar::UNICODE_CHAR_NAME)); var_dump(IntlChar::charName(“u{2603}”)); ?> It will produce the following output − string(9) “FULL STOP” string(7) “SNOWMAN” IntlChar::isalpha The isalpha() function determines whether the specified code point is a letter character. true for general categories “L” (letters). public static IntlChar::isalpha(int|string $codepoint): ?bool Example Take a look at the following example − <?php var_dump(IntlChar::isalpha(“A”)); var_dump(IntlChar::isalpha(“1″)); ?> It will produce the following output − bool(true) bool(false) The Intl class defines similar static methods such as isdigit(), isalnum(), isblank(), etc. IntlChar::islower The islower() function determines whether the specified code point has the general category “Ll” (lowercase letter). public static IntlChar::islower(int|string $codepoint): ?bool Example Take a look at the following example − <?php var_dump(IntlChar::islower(“A”)); var_dump(IntlChar::islower(“a”)); ?> It will produce the following output − bool(false) bool(true) Similarly, there are functions such as isupper(), istitle(), iswhitespace() etc. IntlChar::toupper The given character is mapped to its uppercase equivalent. public static IntlChar::toupper(int|string $codepoint): int|string|null If the character has no uppercase equivalent, the character itself is returned. Example Take a look at the following example − <?php var_dump(IntlChar::toupper(“A”)); var_dump(IntlChar::toupper(“a”)); ?> It will produce the following output − string(1) “A” string(1) “A” Print Page Previous Next Advertisements ”;

PHP – CSPRNG

PHP – CSPRNG ”; Previous Next The acronym CSPRNG stands for Cryptographically Secure Pseudorandom Number Generator. PHP function library includes many functions that generate random numbers. For example − mt_rand() − Generate a random value via the Mersenne Twister Random Number Generator mt_srand() − Seeds the Mersenne Twister Random Number Generator rand() − Generate a random integer. Example The following code shows how you can use the function mt_rand() to generate random numbers − <?php # Generates random integer between the range echo “Random integer: ” . rand(1,100) . PHP_EOL; # Generate a random value via the Mersenne Twister Random Number Generator echo “Random number: ” . mt_rand(1,100); ?> It will produce the following output − Random integer: 45 Random number: 86 Note that the output may vary every time the code is executed. However, random numbers generated by these functions are not cryptographically safe, as it is possible to guess their outcome. PHP 7, introduced a couple of functions that generate secure random numbers. The following functions which are cryptographically secure, are newly added − random_bytes() − Generates cryptographically secure pseudo-random bytes. random_int() − Generates cryptographically secure pseudo-random integers. The random_bytes() Function random_bytes() generates an arbitrary-length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors. string random_bytes ( int $length ) Parameters length − The length of the random string that should be returned in bytes. The function returns a string containing the requested number of cryptographically secure random bytes. If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If an invalid length of bytes is given, an Error will be thrown. Example Take a look at the following example − <?php $bytes = random_bytes(5); print(bin2hex($bytes)); ?> It may produce the following output (it may differ every time) − 6a85eec950 The random_int() Function random_int() generates cryptographic random integers that are suitable for use where unbiased results are critical. int random_int ( int $min , int $max ) Parameters min − The lowest value to be returned, which must be PHP_INT_MIN or higher. max − The highest value to be returned, which must be less than or equal to PHP_INT_MAX. The function returns a cryptographically secure random integer in the range min to max, inclusive. If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If max is less than min, an Error will be thrown. Example Take a look at the following example − <?php print(random_int(100, 999)); print(“n”); print(random_int(-1000, 0)); ?> It may produce the following output (it differs every time) − 495 -563 Print Page Previous Next Advertisements ”;

PHP – Swapping Variables

PHP – Swapping Variables ”; Previous Next PHP doesn’t provide any built-in function with which you can swap or interchange values of two variables. However, there are a few techniques which you can use to perform the swap. One of the most straightforward approaches is to use a third variable as a temporary place holder to facilitate swapping. Using the arithmetic operators in a specific order also is very effective. You can also use the binary XOR operator for swapping purpose. In this chapter, we shall implement these swapping techniques in PHP Temporary Variable This is logically the most obvious and the simplest approach. To swap values of “a” and “b”, use a third variable “c”. Assign the value of “a” to “c”, overwrite “a” with existing value of “b” and then set “b” to the earlier value of “a” that was stored in “c”. Example Take a look at the following example − <?php $a = 10; $b = 20; echo “Before swapping – $a = $a, $b = $b”. PHP_EOL; $c = $a; $a = $b; $b = $c; echo “After swapping – $a = $a, $b = $b”. PHP_EOL; ?> It will produce the following output − Before swapping – $a = 10, $b = 20 After swapping – $a = 20, $b = 10 Using addition (+) Operator This solution takes the advantage of the fact that subtracting a number from the sum of two numbers gives back the second number. In other words, “sum(a+b) – a” is equal to “b” and vice versa. Example Let us take advantage of this property to swap “a” and “b” − <?php $a = 10; $b = 20; echo “Before swapping – $a = $a, $b = $b”. PHP_EOL; $a = $a + $b; $b = $a – $b; $a = $a – $b; echo “After swapping – $a = $a, $b = $b”. PHP_EOL; ?> It will produce the following output − Before swapping – $a = 10, $b = 20 After swapping – $a = 20, $b = 10 You can also use the other arithmetic operators – subtraction (-), multiplication (*) and division (/) in a similar manner to perform swapping. Using list() Function The list() function in PHP unpacks the array in separate variables. This helps in our objective of performing swap between two variables. To do that, build an array of “a” and “b”, and then unpack it to “b” and “a” variables to obtain “a” and “b” with interchanged values. Example Take a look at the following example − <?php $a = 10; $b = 20; echo “Before swapping – $a = $a, $b = $b”. PHP_EOL; $arr = [$a, $b]; list($b, $a) = $arr; echo “After swapping – $a = $a, $b = $b”. PHP_EOL; ?> It will produce the following output − Before swapping – $a = 10, $b = 20 After swapping – $a = 20, $b = 10 Bitwise XOR The bitwise XOR (^) operator can also be used to swap the value of two variables “x” and “y”. It returns 1 when one of two bits at same position in both operands is 1, otherwise returns 0. Example Take a look at the following example − <?php $a = 10; $b = 20; echo “Before swapping – $a = $a, $b = $b”. PHP_EOL; $a = $a ^ $b; $b = $a ^ $b; $a = $a ^ $b; echo “After swapping – $a = $a, $b = $b”. PHP_EOL; ?> It will produce the following output − Before swapping – $a = 10, $b = 20 After swapping – $a = 20, $b = 10 Print Page Previous Next Advertisements ”;

PHP – is_null() Function

PHP is_null() Function ”; Previous Next PHP defines NULL as one of its special data types. It indicates that a certain variable has not been assigned a value any specific data type. It is a built-in constant in PHP and is used to indicate the intentional absence of any object or value. A variable can be explicitly assigned NULL or its value been set to null by using the unset() function. The is_null() Function PHP provides a Boolean function is_null() to check if a variable is indeed of NULL type. is_null(mixed $value): bool Example 1 If any variable is explicitly assigned NULL, obviously the is_null() function returns true. <?php $x = NULL; echo “Variable $x is null? “; var_dump(is_null($x)); ?> It will produce the following output − Variable $x is null? bool(true) Example 2 If a variable with a certain value is unset, then too the is_null() function returns true, but with a warning <?php $x = “Hello”; unset($x); echo “Variable $x is null?n”; var_dump(is_null($x)); ?> It will produce the following output − Variable $x is null? bool(true) PHP Warning: Undefined variable $x in /home/cg/root/89262/main.php on line 5 Example 3 Similarly, if you just declare a variable, without assigning any value to it, the is_null() function returns true with a warning − <?php $y; echo “Variable $y is null?n”; var_dump(is_null($y)); ?> It will produce the following output − Variable $y is null? bool(true) Warning: Undefined variable $y in hello.php on line 9 Example 4 You can also use the equality operator (==) to check if a variable is NULL. <?php $x = NULL; if ($x === NULL) { echo ”$x is NULL”; } else { echo ”$x is not NULL”; } ?> It will produce the following output − $x is NULL Example 5 A null string “” is not considered equal to NULL. Hence, the is_null() function as well as the “==” operator return false. Take a look at the following example − <?php $y = “”; if ($y === NULL) { echo ”$y is NULL”; } else { echo ”$y is not NULL”; } echo “$y is null?n”; var_dump(is_null($y)); ?> It will produce the following output − $y is not NULL is null? bool(false) Two other functions in PHP that are relevant to is_null() function are the isset() function and the empty() function. The isset() Function The isset() function determines if a variable is declared and is different than NULL. isset(mixed $var, mixed …$vars): bool Example A variable that is assigned NULL is considered as unset. <?php $x = NULL; echo ”$x is set? ”; var_dump(isset($x)); ?> It will produce the following output − $x is set? bool(false) Note that a null character (“”) is not equivalent to the PHP null constant. The empty() Function The empty() function checks if a variable is considered to be empty. A variable is considered empty if it does not exist or if its value is NULL. empty() does not generate a warning if the variable does not exist. Example 1 Take a look at the following example − <?php $x = NULL; echo ”$x is empty? ”; var_dump(empty($x)); $y; echo ”$y is empty? ”; var_dump(empty($y)); ?> It will produce the following output − $x is empty? bool(true) $y is empty? bool(true) Example 2 The empty() function returns true if a variable is set to “0”, NULL, or is not set at all. <?php $var = 0; if (empty($var)) { echo ”$var is either 0, empty, or not set at all”; } ?> It will produce the following output − $var is either 0, empty, or not set at all Print Page Previous Next Advertisements ”;

PHP – System Calls

PHP – System Calls ”; Previous Next PHP”s library of built-in function includes a category of functions that deal with invoking operating system utilities and external programs from within the PHP code. In this chapter, we shall discuss the PHP functions used to perform system calls. The system() Function The system() function is similar to the system() function in C that it executes the given command and outputs the result. system(string $command, int &$result_code = null): string|false The system() call tries to automatically flush the web server”s output buffer after each line of output if PHP is running as a server module. It returns the last line of the command output on success, and false on failure. Example The following PHP snippet invokes DIR command of Windows OS and displays the list of files in the current directory. <?php echo ”<pre>”; // Outputs all the result of DOS command “dir”, and returns // the last output line into $last_line. Stores the return value // of the shell command in $retval. $last_line = system(”dir/w”, $retval); // Printing additional info echo ” </pre> <hr />Last line of the output: ” . $last_line . ” <hr />Return value: ” . $retval; ?> It will produce the following output − Volume in drive C has no label. Volume Serial Number is 7EE4-E492 Directory of C:xampphtdocs [.] [..] applications.html bitnami.css [dashboard] employee.csv favicon.ico hello.csv hello.html hello.php homepage.php [img] index.php [Langi] menu.php myform.php myname.php new.png new.txt test.php test.zip [TPcodes] uploadfile.php [webalizer] welcome.png [xampp] 18 File(s) 123,694 bytes 8 Dir(s) 168,514,232,320 bytes free Last line of the output: 8 Dir(s) 168,514,232,320 bytes free Return value: 0 The shell_exec() Function The shell_exec() function is identical to PHP’s backtick operator. It executes the given command via shell and return the complete output as a string shell_exec(string $command): string|false|null The function returns a string containing the output from the executed command, false if the pipe cannot be established or null if an error occurs or the command produces no output. Example In the following code, we use shell_exec() function to obtain a list of files with “.php” as the extension in the current directory − <?php $output = shell_exec(”dir *.php”); echo “<pre>$output</pre>”; ?> It will produce the following output − Volume in drive C has no label. Volume Serial Number is 7EE4-E492 Directory of C:xampphtdocs 10/26/2023 08:27 PM 73 hello.php 10/12/2023 10:40 AM 61 homepage.php 07/16/2015 09:02 PM 260 index.php 10/12/2023 10:39 AM 49 menu.php 09/25/2023 01:43 PM 338 myform.php 10/12/2023 10:49 AM 51 myname.php 10/26/2023 02:00 PM 369 test.php 09/25/2023 01:42 PM 555 uploadfile.php 8 File(s) 1,756 bytes 0 Dir(s) 168,517,771,264 bytes free The exec() Function The exec() function executes the given command as a string argument. exec(string $command, array &$output = null, int &$result_code = null):string|false The $output parameter, if specified, is an array that will be filled with every line of output from the command. Example In this case, we use exec() function to call whoami command from inside the program. The whoami command returns the username. <?php // outputs the username that owns the running php/httpd process // (on a system with the “whoami” executable in the path) $output=null; $retval=null; exec(”whoami”, $output, $retval); echo “Returned with status $retval and output:n”; var_dump($output); ?> It will produce the following output − Returned with status 0 and output: array(1) { [0]=> string(13) “gnvbgl3mlath” } The passthru() Function The passthru() function executes an external program and display raw output. Though the passthru() function is similar to the exec() or system() function in that it executes a command, it should be used in their place when the output from the OS command is binary data which needs to be passed directly back to the browser. Example A PHP program that uses passthu() function to display the contents of system PATH environment variable passthru(string $command, int &$result_code = null): ?false <?php passthru (”PATH”); ?> It will produce the following output − PATH=C:Python311Scripts;C:Python311;C:WINDOWSsystem32;C:WINDOWS; C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0; C:WINDOWSSystem32OpenSSH;C:xamppphp;C:UsersmlathAppDataLocal MicrosoftWindowsApps;C:VSCodeMicrosoft VS Codebin Backtick Operator PHP supports one execution operator: backticks (“). (they are not single-quotes!) PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned. Use of the backtick operator is identical to shell_exec(). Example Take a look at the following example − <?php $output = `dir *.php`; echo “<pre>$output</pre>”; ?> It will produce the following output − Volume in drive C has no label. Volume Serial Number is 7EE4-E492 Directory of C:xampphtdocs 10/26/2023 08:42 PM 61 hello.php 10/12/2023 10:40 AM 61 homepage.php 07/16/2015 09:02 PM 260 index.php 10/12/2023 10:39 AM 49 menu.php 09/25/2023 01:43 PM 338 myform.php 10/12/2023 10:49 AM 51 myname.php 10/26/2023 02:00 PM 369 test.php 09/25/2023 01:42 PM 555 uploadfile.php 8 File(s) 1,744 bytes 0 Dir(s) 168,471,289,856 bytes free The backtick operator is disabled when shell_exec() is disabled. Print Page Previous Next Advertisements ”;

PHP – File Permissions

PHP – File Permissions ”; Previous Next The concept of permissions is at the core of Unix/Linux file system. The permissions determine who can access a file and how one can access a file. File permissions in Linux are manipulated by the chmod command, which can be run inside the Linux terminal. PHP provides the chmod() function with which you can handle file permissions programmatically. PHP’s chmod() function is effective only when you are working on a Linux OS. It doesn’t work on Windows, as Windows OS has a different mechanism of controlling file permissions. To view the permissions enabled on a file, obtain the list of files using the “ls -l” command (long listing) mvl@GNVBGL3:~$ ls -l -rwxr-xr-x 1 mvl mvl 16376 May 5 21:52 a.out -rw-r–r– 1 mvl mvl 83 May 5 21:52 hello.cpp -rwxr-xr-x 1 mvl mvl 43 Oct 11 14:50 hello.php -rwxr-xr-x 1 mvl mvl 43 May 8 10:01 hello.py drwxr-xr-x 5 mvl mvl 4096 Apr 20 21:52 myenv The first column contains permission flags of each file. Third and fourth columns indicate the owner and group of each file, followed by size, date and time, and the file name. The permissions string has ten characters, their meaning is described as follows − Position Meaning 1 “d” if a directory, “-” if a normal file 2, 3, 4 read, write, execute permission for user (owner) of file 5, 6, 7 read, write, execute permission for group 8, 9, 10 read, write, execute permission for other (world) The characters in the permission string have following meaning − Value Meaning – Flag is not set. r File is readable. w File is writable. For directories, files may be created or removed. x File is executable. For directories, files may be listed. If you consider the first entry in the above list − -rwxr-xr-x 1 mvl mvl 16376 May 5 21:52 a.out The “a.out” file is owned by the user “mvl” and group “mvl”. It is a normal file with “read/write/execute” permissions for the owner, and “read/ execute” permissions for the group as well as others. The binary and octal representation of permission flags can be understood with the following table − Octal Digit Binary Representation (rwx) Permission 0 000 none 1 001 execute only 2 010 write only 3 011 write and execute 4 100 read only 5 101 read and execute 6 110 read and write 7 111 read, write, and execute (full permissions) The chmod() Function The chmod() function can change permissions of a specified file. It returns true on success, otherwise false on failure. chmod(string $filename, int $permissions): bool The chmod() function attempts to change the mode of the specified file ($filename) to that given in permissions. The second parameter $permissions is an octal number with four octal digits. The first digit is always zero, second specifies permissions for the owner, third for the owner”s user group and fourth for everybody else. Each digit is the sum of values for each type of permission. 1 Execute Permission 2 Write Permission 4 Read Permission The default value of $permissions parameters is 0777, which means the directory is created with execute, write and read permissions enabled. Example Take a look at the following example − <?php // Read and write for owner, nothing for everybody else chmod(“/PhpProject/sample.txt”, 0600); // Read and write for owner, read for everybody else chmod(“/PhpProject/sample.txt”, 0644); // Everything for owner, read and execute for everybody else chmod(“/PhpProject/sample.txt”, 0755); // Everything for owner, read for owner”s group chmod(“/PhpProject/sample.txt”, 0740); ?> The chown() Function The chown() function attempts to change the owner of the file filename to a new user. Note that only the superuser may change the owner of a file. chown(string $filename, string|int $user): bool Example Take a look at the following example − &lt?php // File name and username to use $file_name= “index.php”; $path = “/PhpProject/backup: ” . $file_name ; $user_name = “root”; // Set the user chown($path, $user_name); // Check the result $stat = stat($path); print_r(posix_getpwuid(fileowner($path))); ?> The chgrp() Function The chgrp() function attempts to change the group of the file filename to group. chgrp(string $filename, string|int $group): bool Only a superuser may change the group of a file arbitrarily; other users may change the group of a file to any group of which that user is a member. Example Take a look at the following example − <?php $filename = “/PhpProject/sample.txt”; $format = “%s”s Group ID @ %s: %dn”; printf($format, $filename, date(”r”), filegroup($filename)); chgrp($filename, “admin”); clearstatcache(); // do not cache filegroup() results printf($format, $filename, date(”r”), filegroup($filename)); ?> It will produce the following output − /PhpProject/sample.txt”s Group ID @ Fri, 13 Oct 2023 07:42:21 +0200: 0 /PhpProject/sample.txt”s Group ID @ Fri, 13 Oct 2023 07:42:21 +0200: 0 Print Page Previous Next Advertisements ”;