PHP – Error Handling ”; Previous Next Error handling in PHP refers to the making a provision in PHP code to effectively identifying and recovering from runtime errors that the program might come across. In PHP, the errors are handled with the help of − The die() function The Error Handler Function The die() Function The die() function is an alias of exit() in PHP. Both result in termination of the current PHP script when encountered. An optional string if specified in the parenthesis, will be output before the program terminates. die(“message”); Example The following code is a typical usage of die() in a PHP script. It displays the File not found message if PHP doesn’t find a file, otherwise proceeds to open it for subsequent processing. <?php if(!file_exists(“nosuchfile.txt”)) { die(“File not found”); } else { $file = fopen(“nosuchfile”,”r”); print “Opend file sucessfully”; // Rest of the code here. fclose($file); } ?> It will produce the following output − File not found Using above technique, you can stop your program whenever it errors out and display more meaningful and user friendly message, rather than letting PHP generate fatal error message. The Error Handler Function Using die() for error handling is considered an ungainly and poor program design, as it results in an ugly experience for site users. PHP offers a more elegant alternative with which you can define a custom function and nominate it for handling the errors. The set_error_handler() function has the following parameters − set_error_handler(?callable $callback, int $error_levels = E_ALL): ?callable The first parameter is a user defined function which is called automatically whenever an error is encountered. The custom error handler callback function should have the following parameters − handler( int $errno, string $errstr, string $errfile = ?, int $errline = ?, array $errcontext = ? ): bool Parameters Parameter Importance Description errno Required It specifies the error level for the user-defined error. It must be numerical value. errstr Required It specifies the error message for the user-defined error. errfile Optional It specifies the filename in which the error occurred. errline Optional It specifies the line number at which the error occurred. errcontext Optional It specifies an array containing variables and their values in use when the error occurred. If the callback function returns false, the default error will be called. The $errno is an integer corresponding to the predefined error levels. Sr.No Constant & Description Value 1 E_ERROR (int) Fatal run-time errors that can not be recovered from. Execution of the script is halted. 1 2 E_WARNING (int) Run-time warnings (non-fatal errors). Execution of the script is not halted. 2 3 E_PARSE (int) Compile-time parse errors. Parse errors should only be generated by the parser. 4 4 E_NOTICE (int) Run-time notices. Something that could indicate an error, but could also happen in the normal course of running a script. 8 5 E_CORE_ERROR (int) Fatal errors that occur during PHP”s initial startup. This is like an E_ERROR 16 6 E_CORE_WARNING (int) Warnings (non-fatal errors) that occur during PHP”s initial startup. This is like an E_WARNING, 32 7 E_COMPILE_ERROR (int) Fatal compile-time errors. This is like an E_ERROR. 64 8 E_COMPILE_WARNING (int) Compile-time warnings (non-fatal errors). This is like an E_WARNING. 128 9 E_USER_ERROR (int) User-generated error message. This is like an E_ERROR, generated in PHP code by using the PHP function trigger_error(). 256 10 E_USER_WARNING (int) User-generated warning message. This is like an E_WARNING, generated in PHP code by using the function trigger_error(). 512 11 E_USER_NOTICE (int) User-generated notice message. This is like an E_NOTICE generated in PHP code by using the function trigger_error(). 1024 12 E_STRICT (int) Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. 2048 13 E_RECOVERABLE_ERROR (int) Catchable fatal error. If the error is not caught by a user defined handler, the application aborts as it was an E_ERROR. 4096 14 E_DEPRECATED (int) Run-time notices. Enable this to receive warnings about code that will not work in future versions. 8192 15 E_USER_DEPRECATED (int) User-generated warning message. This is like an E_DEPRECATED, generated in PHP code by using the function trigger_error(). 16384 16 E_ALL (int) All errors, warnings, and notices. 32767 Example Take a look at the following example − <?php error_reporting(E_ERROR); function myerrorhandler($errno, $errstr) { echo “error No: $errno Error message: $errstr” . PHP_EOL; echo “Terminating PHP script”; die(); } set_error_handler(“myerrorhandler”); $f = fopen(“nosuchfile.txt”, “r”); echo “file opened successfully”; // rest of the code fclose($f); ?> It will produce the following output − error No: 2 Error message: fopen(nosuchfile.txt): Failed to open stream: No such file or directory Terminating PHP script PHP’s error class hierarchy starts from throwable interface. All the predefined Error classes in PHP are inherited from Error class. The ArithmeticError Class The ArithmeticError class is inherited from the Error class. This type of error may occur while performing
Category: php
PHP – Read File
PHP – Read File ”; Previous Next There are a number of options in PHP for reading data from a file that has been opened with the fopen() function. The following built-in functions in PHP’s library can help us perform the read operation − fgets() − gets a line from the file pointer. fgetc() − returns a string with a single character from the file pointer. fread() − reads a specified number of bytes from the file pointer. fscanf() − reads data from the file and parses it as per the specified format. The fgets() Function The fgets() function can return a line from an open file. This function stops returning on a new line at a specified length or EOF, whichever comes first and returns false on failure. fgets(resource $stream, ?int $length = null): string|false Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with read or read/write mode, and $length is an optional parameter specifying the number of bytes to be read. The read operation ends when “length-1” bytes are read or a newline is encountered, whichever is first. Example The following code reads the first available line from the “hello.txt” file − <?php $file = fopen(“hello.txt”, “r”); $str = fgets($file); echo $str; fclose($file); ?> It will produce the following output − Hello World Example You can put the fgets() function in a loop to read the file until the end of file is reached. <?php $file = fopen(“hello.txt”, “r”); while(! feof($file)) { echo fgets($file). “<br>”; } fclose($file); ?> It will produce the following output − Hello World TutorialsPoint PHP Tutorials Here, we have used the feof() function which returns true if the file pointer is at EOF; otherwise returns false. The fgetc() Function The fgetc() function returns a single character read from the current position of the file handle. It returns false when EOF is encountered. fgetc(resource $stream): string|false Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with read or read/write mode. Example The following code displays the first character read from the “hello.txt” file − <?php $file = fopen(“hello.txt”, “r”); $str = fgets($file); echo $str; fclose($file); ?> It will produce the following output − H Example You can also put the fgetc() function inside a loop to read the file character by character until it reaches EOF. <?php $file = fopen(“hello.txt”, “r”); while(! feof($file)) { $char = fgetc($file); if ($char == “n”) echo “<br>”; echo $char; } fclose($file); ?> It will produce the following output − Hello World TutorialsPoint PHP Tutorials The fread() Function The fread() function in PHP is a binary-safe function for reading data from a file. While the fgets() function reads only from a text file, the fread() function can read a file in binary mode. fread(resource $stream, int $length): string|false Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with binary read or read/write mode (rb or rb+). The $length parameter specifies number of bytes to be read. If the $length parameter is not given, PHP tries to read the entire file until EOF is reached, subject to the chunk size specified. Example The following code reads a text file − <?php $name = “hello.txt”; $file = fopen($name, “r”); $data = fread($file, filesize($name)); echo $data; fclose($file); ?> It will produce the following output − Hello World TutorialsPoint PHP Tutorials Example You can also read a non-ASCII file such as an image file opened in rb mode. <?php $name = “welcome.png”; $file = fopen($name, “rb”); $data = fread($file, filesize($name)); var_dump($data); fclose($file); ?> The browser displays the “var_dump” information as the following − The fscanf() Function The fscanf() function in PHP reads the input from a file stream and parses it according to the specified format, thereby converts it into the variables of respective types. Each call to the function reads one line from the file. fscanf(resource $stream, string $format, mixed &…$vars): array|int|false|null Here, the $stream parameter is the handle to the file opened with the fopen() function and in read mode. And, $format is a string containing one or more of the following formatting specifiers − %% − Returns a percent %b − Binary number %c − The character according to the ASCII value %f − Floating-point number %F − Floating-point number %o − Octal number %s − String %d − Signed decimal number %e − Scientific notation %u − Unsigned decimal number %x − Hexadecimal number for lowercase letters %X − Hexadecimal number for uppercase letters $vars is an optional parameter that specifies variables by reference which will contain the parsed values. Assuming that the “employees.txt” file is available in the same directory in which the PHP script given below is present. Each line in the text file has name, email, post and salary of each employee, separated by tab character. Example The following PHP script reads the file using the format specifiers in fscanf() function − <?php $fp = fopen(“employees.txt”, “r”); while ($employee_info = fscanf($fp, “%st%st%st%dn”)) { list ($name, $email, $post, $salary) = $employee_info; echo “<b>Name</b>: $name <b>Email</b>: $email <b>Salary</b>: Rs. $salary <br>”; } fclose($fp); ?> It will produce the following output − Name: Ravishankar Email: [email protected] Salary: Rs. 40000 Name: Kavita Email: [email protected] Salary: Rs. 25000 Name: Nandkumar Email: [email protected] Salary: Rs. 30000 Print Page
PHP – Cloning Objects
PHP – Cloning Objects ”; Previous Next A PHP statement such as “$obj1 = $obj2” merely creates another reference to the same object in memory. Hence, changes in attribute reflect both in original and duplicate object. The clone keyword in PHP creates a shallow copy of an object. $obj2 = $obj1 Changes in the original object do not reflect in the shallow copy. Example Take a look at the following example − <?php class foo { var $var1 = ”Hello”; } $x = new foo(); $y = $x; # reference copy echo $x->var1 . ” ” . $y->var1 . PHP_EOL; $x->var1 = “Hello World”; echo $x->var1 . ” ” . $y->var1 . PHP_EOL; ?> It will produce the following output − Hello Hello Hello World Hello World In the first case, $y is just a reference copy of $x. Hence, any change in var1 property reflects in both. However, if we declare $y as a clone of $x, then any change in the original object is not reflected in its shallow copy. Example Take a look at the following example − <?php class foo { var $var1 = ”Hello World”; } $x = new foo(); # shallow copy $y = clone $x; echo $x->var1 . ” ” . $y->var1 . PHP_EOL; $x->var1 = “Hello PHP”; echo $x->var1 . ” ” . $y->var1 . PHP_EOL; ?> It will produce the following output − Hello World Hello World Hello PHP Hello World Example In the following code, myclass has one of attributes as object of address class. An object of myclass is duplicated by assignment. Any change in the value of its embedded address object is reflected in both the objects, but change in the name property is not effected in the cloned object. <?php class address { var $city=”Nanded”; var $pin=”431601″; function setaddr($arg1, $arg2) { $this->city=$arg1; $this->pin=$arg2; } } class myclass { var $name=”Raja”; var $obj; function setname($arg) { $this->name=$arg; } } $obj1=new myclass(); $obj1->obj=new address(); echo “original objectn”; print_r($obj1); echo “n”; $obj2=$obj1; # reference copy $obj1->setname(“Ravi”); $obj1->obj->setaddr(“Mumbai”, “400001”); echo “after change: Original objectn”; print_r($obj1); echo “nCopied objectn”; print_r($obj2); ?> It will produce the following output − original object myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 431601 ) ) after change: Original object myclass Object ( [name] => Ravi [obj] => address Object ( [city] => Mumbai [pin] => 400001 ) ) Copied object myclass Object ( [name] => Ravi [obj] => address Object ( [city] => Mumbai [pin] => 400001 ) ) Using the “clone” Keyword In a shallow copy, any properties of the original object that are references to other variables will remain references. The clone keyword does not copy the contained objects of the copied objects. We now create a clone of myclass object, so that $obj2 is the clone of $obj1. We change the name property of $obj1 from Raja to Ravi, and also modify the embedded address object. The property change will not reflect in its clone, but the referred address object will be changed. Example Take a look at the following example − <?php class address { var $city=”Nanded”; var $pin=”431601″; function setaddr($arg1, $arg2) { $this->city=$arg1; $this->pin=$arg2; } } class myclass { var $name=”Raja”; var $obj; function setname($arg) { $this->name=$arg; } } $obj1=new myclass(); $obj1->obj=new address(); echo “original objectn”; print_r($obj1); echo “n”; $obj2=clone $obj1; # clone copy $obj1->setname(“Ravi”); $obj1->obj->setaddr(“Mumbai”, “400001”); echo “after change: Original objectn”; print_r($obj1); echo “nCopied objectn”; print_r($obj2); ?> It will produce the following output − original object myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 431601 ) ) after change: Original object myclass Object ( [name] => Ravi [obj] => address Object ( [city] => Mumbai [pin] => 400001 ) ) Copied object myclass Object ( [name] => Raja [obj] => address Object ( [city] => Mumbai [pin] => 400001 ) ) Using __clone() Method The clone keyword creates a shallow copy of the object. When an object is cloned, PHP will perform a shallow copy of all of the object”s properties. Any properties that are references to other variables will remain references. Hence, any changes done to the original object will also appear in the cloned object. If you wish to prevent the copied object to update automatically, we need to create a deep copy of the object with the __clone() method. It is one of the magic methods in PHP. Once the cloning is complete, if a __clone() method is defined, then the newly created object”s __clone() method will be called, to allow any necessary properties that need to be changed. Example In the above example, we have an object of myclass, one of its attributes $obj holding the reference to an object of address class. To achieve a deep copy, we override the __clone() magic method in myclass. <?php class address { var $city=”Nanded”; var $pin=”431601″; function setaddr($arg1, $arg2) { $this->city=$arg1; $this->pin=$arg2; } } class myclass { var $name=”Raja”; var $obj; function setname($arg) { $this->name=$arg; } public function __clone() { $this->obj = clone $this->obj ; } } $obj1=new myclass(); $obj1->obj=new address(); echo “original objectn”; print_r($obj1); echo “n”; $obj2=clone $obj1; # cloned deep copy $obj1->setname(“Ravi”); $obj1->obj->setaddr(“Mumbai”, “400001”); echo “after change: Original objectn”; print_r($obj1); echo “nCloned objectn”; print_r($obj2); ?> You will now see that the changes in the original object (we change the address attributes) won’t reflect in the cloned object, as the following output shows − original object myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 431601 ) ) after change: Original object myclass Object ( [name] =>
PHP – Frameworks
PHP â Frameworks ”; Previous Next The PHP ecosystem has a number of web frameworks. Some of the popular PHP web frameworks are Laravel, Yii, CakePHP etc. While one can build a web application with the help of core PHP, developers are increasingly preferring web frameworks for rapid application development. What are Software Frameworks? In computer programming, a software framework is a collection of libraries and classes that provide a generic functionality that allows the developer to concentrate more on the application logic, rather than writing code for routine but tedious low-level processes. A framework provides a reusable software environment that quickly builds a minimal working template application. Developer can then modify these blocks for additional functionality. Each framework is built to help the developer build an application of a certain type. For example, web frameworks (sometimes also called “web application framework”) are used for the development of web applications including web services, web resources, and web APIs. In this chapter, let us take a brief overview of some of the popular PHP frmeworks. FuelPHP FuelPHP (https://fuelphp.com/) works based on Model View Control and having innovative plug ins. FuelPHP supports router-based theory where you might route directly to a nearer the input uri, making the closure the controller and giving it control of further execution. CakePHP CakePHP (https://cakephp.org/) is a great source to build up simple and great web application in an easy way. Some great features which are inbuilt in PHP are input validation, SQL injection prevention that keeps you application safe and secure. FlightPHP FlightPHP (https://flightphp.com/) is very helpful to make RESTful web services and it is under MIT licence. Symfony Symfony is for highly professional developers to build websites with PHP components such as Drupal, PHPBB, laravel, eX, OROCRM and piwik. yiiFramework YiiFramework (https://www.yiiframework.com/) works based on web 2.0 with high end security. It included input Validation, output filtering, and SQL injection. Laravel Laravel (https://laravel.com/) is most useful for RESRful Routing and light weight bled tempting engine. Laravel has integrated with some of great components of well tested and reliable code. Zend Zend (https://framework.zend.com/) is Modern frame work for performing high end web applications. This works based on Cryptographic and secure coding tools. Zend Framework is a collection of professional PHP packages with more than 570 million installations. It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features. Codeigniter Codeigiter is simple to develop small footprint for developer who need simple and elegant tool kit to create innovative web applications. Phalcon PHP Pholcon (https://phalcon.io/en-us) is a PHP framework that works based on MVC and integrated with innovative architecture to do perform faster. PHPixie PHPixie (https://phpixie.com/) works based on MVC and designed for fast and reliability to develop web sites. Agavi Agavi is a powerful and scalable PHP5 application framework and it follows the MVC model. Agavi can help PHP developers in writing clean and maintainable code. Print Page Previous Next Advertisements ”;
PHP – For PERL Developers
PHP For PERL Developers ”; Previous Next PERL is a dynamically typed, high level and general-purpose programming language. It is normally believed that PERL is an acronym for Practical Extraction and Reporting Language. PHP on the other hand is also a general-purpose scripting language. Initially PHP used to be a short for Personal Home Page’, but these days it has now been recognized as a recursive acronym ‘PHP: Hypertext Preprocessor’. In this chapter, certain major similarities and differences in between PHP and PERL are listed. This will help PERL developers to understand PHP very quickly and avoid common mistakes. Similarities between PERL and PHP Both Perl and PHP are scripting languages. They are not used to build native standalone executables in advance of execution. Early versions of PHP were inspired by PERL. PHP”s basic syntax is very similar to PERL. Both share a lot of syntactic features with C. Their code is insensitive to whitespace, Each statement is terminated by semicolons. Both PHP and PERL use curly braces to organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas, in both the cases. All variables in PHP look like scalar variables in PERL: a name with a dollar sign ($) in front of it. Since both the languages are dynamically typed, you don’t need to declare the type of a PHP as well as a PERL variable before using it. In PHP, as in PERL, variables have no intrinsic type other than the value they currently hold. You can store either number or string in same type of variable. Both PHP and Perl do more interpretation of double-quoted strings (“string”) than of single-quoted strings (”string”). Differences between PERL and PHP PHP can be embedded inside HTML. Although it is possible to run a PHP script from the command line, it is more popularly used as a server-side scripting language on a Web server and used for producing Web pages. If you are used to writing CGI scripts in PERL, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block. No @ or % variables − PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound. In PERL, the array variable is prefixed with @ symbol. Also, the hash variable is prefixed by % symbol. Unlike PERL, PHP has a single datatype called an array which can be an indexed array or associative array, which is similar to hash in PERL. Function calls in PHP look pretty much like subroutine calls in PERL. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the case in PERL. Scope of variables in PERL is global by default. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default. No module system in PHP as such. In PHP there is no real distinction between normal code files and code files used as imported libraries. Break and continue rather than next and last − PHP is more like C language and uses break and continue instead of next and last statement as in PERL. No elsif − A minor spelling difference: Perl”s elsif is PHP”s elseif. In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */) and Java-style single-line comments (// comment). Regular expressions − PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its “Perl-compatible” regular expression functions. Print Page Previous Next Advertisements ”;
PHP – Coding Standard
PHP – Coding Standard ”; Previous Next Every company follows its own coding standard based on its best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future. Here are some reasons why one should use coding specifications − Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code. Simplicity and clarity achieved by consistent coding saves you from common mistakes. If you revise your code after some time then it becomes easy to understand that code. Following a uniform coding standard brings more quality in software. There are few guidelines which can be followed while coding in PHP. Indenting and Line Length Use an indent of 4 spaces and don”t use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability. Control Structures These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional. Examples if ((condition1) || (condition2)) { action1; } elseif ((condition3) && (condition4)) { action2; } else { default action; } You can write the switch statements as follows: switch (condition) { case 1: action1; break; case 2: action2; break; default: defaultaction; break; } Function Calls Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here”s an example − $var = foo($bar, $baz, $quux); Function Definitions Function declarations follow the “BSD/Allman style” − function fooFunction($arg1, $arg2 = ””) { if (condition) { statement; } return $val; } Comments C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is allowed but discouraged. PHP Code Tags Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups. Variable Names Use all lower case letters Use ”_” as the word separator. Global variables should be prepended with a ”g”. Global constants should be all caps with ”_” separators. Static variables may be prepended with ”s”. Make Functions Reentrant Functions should not keep static variables that prevent a function from being reentrant. Alignment of Declaration Blocks Block of declarations should be aligned. One Statement Per Line There should be only one statement per line unless the statements are very closely related. Short Methods or Functions Methods should limit themselves to a single page of code. There could be many more points which should be considered while writing your PHP program. Over all intention should be to be consistent throughout of the code programming and it will be possible only when you will follow any coding standard. You can device your own standard if you like something different. Print Page Previous Next Advertisements ”;
PHP – Bugs Debugging
PHP – Bugs Debugging ”; Previous Next A bug in a PHP code refers to an error in the program that leads to unexpected results or crash. A systematic approach towards the process of finding bugs before users do is called debugging. In this chapter, some important tips to trace bugs in a PHP code are given. Programs rarely work correctly the first time. Many things can go wrong in your program that can cause the PHP interpreter to generate an error message. You have a choice about where those error messages go. The messages can be sent along with other program output to the web browser. They can also be included in the “web server error log”. To make error messages display in the browser, set the “display_errors” configuration directive to ON. Ensure that the following settings are enabled in the “php.ini” file. display_errors=On display_startup_errors=On You can also use the ini_set() function to override the “pnp.ini” configuration − ini_set(”display_errors”, 1) ini_set(”display_startup_errors”, 1) To send errors to the web server error log, set “log_errors” to ON. You can set them both to On if you want error messages in both places. PHP defines some constants that you can use to set the value of error_reporting such that only errors of certain types get reported − E_ALL (for all errors except strict notices) E_PARSE (parse errors) E_ERROR (fatal errors) E_WARNING (warnings) E_NOTICE (notices) E_STRICT (strict notices) While writing your PHP program, it is a good idea to use PHP-aware editors like BBEdit or Emacs. One of the special features of these editors is syntax highlighting. It changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black. VS Code from Microsoft is also a good choice for editing PHP code. If you install VS Code extension Intelephense, you will get type hints and error message as you enter PHP statements in the editor window. Another feature is quote and bracket matching, which helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as “}”, the editor highlights the opening “{” that it matches. Points to Check while Debugging a Code One needs to verfity the following points while debugging a program code − Missing Semicolons Every PHP statement ends with a semicolon (;). PHP doesn”t stop reading a statement until it reaches a semicolon. If you leave out the semicolon at the end of a line, PHP continues reading the statement on the following line. Not Enough Equal Signs When you ask whether two values are equal in a comparison statement, you need two equal signs (==). Using one equal sign is a common mistake. Misspelled Variable Names If you misspelled a variable then PHP understands it as a new variable. Remember: To PHP, $test is not the same variable as $Test. Missing Dollar Signs A missing dollar sign in a variable name is really hard to see, but at least it usually results in an error message so that you know where to look for the problem. Troubling Quotes You can have too many, too few, or the wrong kind of quotes. So check for a balanced number of quotes. Missing Parentheses and curly brackets They should always be in pairs. Array Index An array in PHP is a collection of items, each item assigned an incrementing index starting with 0. Moreover, handle all the errors properly and direct all trace messages into system log file so that if any problem happens then it will be logged into system log file and you will be able to debug that problem. Print Page Previous Next Advertisements ”;
PHP.INI File Configuration
PHP.INI File Configuration ”; Previous Next On installing PHP software on your machine, php.ini is created in the installation directory. In case of XAMPP, php.ini is found in c:xammphp folder. It is an important configuration file that controls the performance and sets all the PHP related parameters. The phpinfo() function displays a list of different parameters and their current values of PHP, Aache, MySQL and other parts of the web server installation. Run the following code to display the settings, one of which shows the path to the “php.ini” file: <?php echo phpinfo(); ?> Loaded Configuration File Locate the Loaded Configuration File setting that displays the location of php.ini file C:xamppphpphp.ini Different aspects of PHP’s behaviour are configured by a large number of parameters (called directives). The “php.ini” file comes with most of the lines starting with semicolon (;) symbol – indicating that the line is commented. The uncommented line is actually the effective directive and its value. In other words, to activate and assign a value to a particular directive, remove the leading semicolon. directive = value Directive names are *case sensitive. Directives are variables used to configure PHP or PHP extensions. Note that there is no name validation, so if an expected directive is not found a default value will be used, which can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one of the INI constants (On, Off, True, False, Yes, No and None). Actually, the C:XAMPPPHP folder contains two INI files, one to be used in production environment and other in development environment. The php.ini-development.ini is very similar to its production variant, except it is much more verbose when it comes to errors. In development stage, copy this as php.ini to be able to trace the bugs in the code. Once the code is ready for deployment, use php.ini-production.ini file as the effective php.ini file, which essentially supress the error messages to a large extent. The directives in php.ini are divided in different categories, like Error handling, data handling, path and directories, file uploads, PHP extensions and module settings. Here is a list of some of the important directives in “php.ini” file: short_open_tag = Off Short open tags look like this: <? ?>. This option must be set to Off if you want to use XML functions. safe_mode = Off If this is set to On, you probably compiled PHP with the –enable-safe-mode flag. Safe mode is most relevant to CGI use. See the explanation in the section “CGI compile-time options”. earlier in this chapter. safe_mode_exec_dir = [DIR] This option is relevant only if safe mode is on; it can also be set with the –with-exec-dir flag during the Unix build process. PHP in safe mode only executes external binaries out of this directory. The default is /usr/local/bin. This has nothing to do with serving up a normal PHP/HTML Web page. safe_mode_allowed_env_vars = [PHP_] This option sets which environment variables users can change in safe mode. The default is only those variables prepended with “PHP_”. If this directive is empty, most variables are alterable. safe_mode_protected_env_vars = [LD_LIBRARY_PATH] This option sets which environment variables users can”t change in safe mode, even if safe_mode_allowed_env_vars is set permissively disable_functions = [function1, function2…] A welcome addition to PHP4 configuration and one perpetuated in PHP5 is the ability to disable selected functions for security reasons. Previously, this necessitated hand-editing the C code from which PHP was made. Filesystem, system, and network functions should probably be the first to go because allowing the capability to write files and alter the system over HTTP is never such a safe idea. max_execution_time = 30 The function set_time_limit() won.t work in safe mode, so this is the main way to make a script time out in safe mode. In Windows, you have to abort based on maximum memory consumed rather than time. You can also use the Apache timeout setting to timeout if you use Apache, but that will apply to non-PHP files on the site too. error_reporting = E_ALL & ~E_NOTICE The default value is E_ALL & ~E_NOTICE, all errors except notices. Development servers should be set to at least the default; only production servers should even consider a lesser value error_prepend_string = [“”] With its bookend, error_append_string, this setting allows you to make error messages a different color than other text, or what have you. warn_plus_overloading = Off This setting issues a warning if the + operator is used with strings, as in a form value. variables_order = EGPCS This configuration setting supersedes gpc_order. Both are now deprecated along with register_globals. It sets the order of the different variables: Environment, GET, POST, COOKIE, and SERVER (aka Built-in). You can change this order around. Variables will be overwritten successively in left-to-right order, with the rightmost one winning the hand every time. This means if you left the default setting and happened to use the same name for an environment variable, a POST variable, and a COOKIE variable, the COOKIE variable would own that name at the end of the process. In real life, this doesn”t happen much. register_globals = Off This setting allows you to decide whether you wish to register EGPCS variables as global. This is now deprecated, and as of PHP4.2, this flag is set to Off by default. Use superglobal arrays instead. All the major code listings in this book use superglobal arrays. magic_quotes_gpc = On This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of forms which possibly submit to themselves or other forms and display form values, you may need to set this directive to On or prepare to use addslashes() on string-type data. magic_quotes_runtime = Off This setting
PHP – MySQL Login
PHP – MySQL Login ”; Previous Next MySQL is a popular choice as a backend database for PHP powered web applications. In this chapter, we shall learn to develop a login page for a PHP application that authenticates the given username and password. You should have a web server having PHP and MySQL installed for experimenting with the example discussed in this chapter. The bundled binaries of Apache, PHP and MySQL (MariaDB) in the form of XAMPP for your operating system can be easily installed. Before running the example code, you should have a MySQL database called mydb in which there must be a table called admin. You can use following SQL script to create the table and insert a test data use mydb; CREATE TABLE `admin` ( `username` varchar(10) NOT NULL, `passcode` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; INSERT INTO `admin` (`username`, `passcode`) VALUES (”guest”, ”abc123”), (”manager”, ”secret”), (”user”, ”test”); ALTER TABLE `admin` ADD PRIMARY KEY (`username`); COMMIT; The first part of PHP login application is to establish database connection object. We use myqli API to obtain connection object. Save following code as “config.php” Config.php <?php define(”DB_SERVER”, ”localhost”); define(”DB_USERNAME”, ”root”); define(”DB_PASSWORD”, ””); define(”DB_DATABASE”, ”mydb”); $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); ?> This PHP script is called inside the login script. It presents the user with a HTML form to enter username and password. In case the form is submitted, PHP runs a SELECT query to retrieve a row in the admin table where the username and passcode matches with the user inputs. $myusername = mysqli_real_escape_string($db,$_POST[”username”]); $mypassword = mysqli_real_escape_string($db,$_POST[”password”]); $sql = “SELECT * FROM admin WHERE username = ”$myusername” and passcode = ”$mypassword””; $result = mysqli_query($db,$sql); $row = mysqli_num_rows($result); If the row count is one, it indicates that the username and the password entered matches. The username is save to the $_SESSION variable and the browser is directed to welcome.php script. Login.php Save the following code as “login.php” − <?php include(“config.php”); session_start(); $error=””; if($_SERVER[“REQUEST_METHOD”] == “POST”) { // username and password sent from form $myusername = mysqli_real_escape_string($db,$_POST[”username”]); $mypassword = mysqli_real_escape_string($db,$_POST[”password”]); $sql = “SELECT * FROM admin WHERE username = ”$myusername” and passcode = ”$mypassword””; $result = mysqli_query($db,$sql); $row = mysqli_num_rows($result); $count = mysqli_num_rows($result); if($count == 1) { // session_register(“myusername”); $_SESSION[”login_user”] = $myusername; header(“location: welcome.php”); } else { $error = “Your Login Name or Password is invalid”; } } ?> <html> <head> <title>Login Page</title> <style type = “text/css”> body { font-family:Arial, Helvetica, sans-serif; font-size:14px; } label { font-weight:bold; width:100px; font-size:14px; } .box { border:#666666 solid 1px; } </style> </head> <body bgcolor = “#FFFFFF”> <div align = “center”> <div style = “width:300px; border: solid 1px #333333; ” align = “left”> <div style = “background-color:#333333; color:#FFFFFF; padding:3px;”><b>Login</b></div> <div style = “margin:30px”> <form action = “” method = “post”> <label>UserName :</label><input type = “text” name = “username” class = “box”/><br /><br /> <label>Password :</label><input type = “password” name = “password” class = “box” /><br/><br /> <input type = “submit” value = ” Submit “/><br /> </form> <div style = “font-size:11px; color:#cc0000; margin-top:10px”><?php echo $error; ?></div> </div> </div> </div> </body> </html> Session.php The following is the session.php code file. It checks if the session variable is set; then the user credentials will be assigned to the $login_session variable. If not, the user is redirected back to the login.php file. <?php // Start the session session_start(); if(!isset($_SESSION[”login_user”])){ header(“location: login.php”); die(); } $login_session = $_SESSION[”login_user”]; ?> Welcome.php The “welcome.php” script gets invoked when the user is authenticated. It reads the session variable to display a welcome message. <?php include(”session.php”); ?> <html> <head> <title>Welcome </title> </head> <body> <h1>Welcome <?php echo $login_session; ?></h1> <h2><a href = “logout.php”>Sign Out</a></h2> </body> </html> Logout.php Finally, the logout script removes the destroys the session and redirects the user to the login page. <?php session_start(); if(session_destroy()) { header(“Location: login.php”); } ?> To start the login application, visit “http://localhost/login.php” Enter the username and password. On pressing the submit button, these inputs are checked against the rows in admin table. On success, you get the following message − If the query doesn’t fetch any matching row, the error message is displayed as follows − Print Page Previous Next Advertisements ”;
PHP – AJAX RSS Feed Example
PHP – AJAX RSS Feed Example ”; Previous Next Really Simple Syndication (RSS) RSS, which stands for Really Simple Syndication, is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using AJAX and PHP. This code demonstrates how to show RSS feeds in our site. Index.html The index page should be as follows − <html> <head> <script> function showRSS(str) { if (str.length == 0) { document.getElementById(“output”).innerHTML = “”; return; } if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById(“output”).innerHTML = xmlhttp.responseText; } } xmlhttp.open(“GET”,”rss.php?q=”+str,true); xmlhttp.send(); } </script> </head> <body> <p>Please Select an option to get RSS:</p> <form> <select onchange = “showRSS(this.value)”> <option value = “”>Select an RSS-feed:</option> <option value = “cnn”>CNN</option> <option value = “bbc”>BBC News</option> <option value = “pc”>PC World</option> </select> </form> <br> <div id = “output”>RSS-feeds</div> </body> </html> rss.php “rss.php” has contained syntax about how to get access to RSS Feeds RSS Feeds and return RSS Feeds to the webpages. <?php $q = $_GET[“q”]; if($q == “cnn”) { $xml = (“http://rss.cnn.com/rss/cnn_topstories.rss”); } elseif($q == “bbc”) { $xml = (“http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml”); } elseif($q = “pcw”){ $xml = (“http://www.pcworld.com/index.rss”); } $xmlDoc = new DOMDocument(); $xmlDoc->load($xml); $channel = $xmlDoc->getElementsByTagName(”channel”)->item(0); $channel_title = $channel->getElementsByTagName(”title”) ->item(0)->childNodes->item(0)->nodeValue; $channel_link = $channel->getElementsByTagName(”link”) ->item(0)->childNodes->item(0)->nodeValue; $channel_desc = $channel->getElementsByTagName(”description”) ->item(0)->childNodes->item(0)->nodeValue; echo(“<p><a href = ”” . $channel_link . “”>” . $channel_title . “</a>”); echo(“<br>”); echo($channel_desc . “</p>”); $x = $xmlDoc->getElementsByTagName(”item”); for ($i = 0; $i<=2; $i++) { $item_title = $x->item($i)->getElementsByTagName(”title”) ->item(0)->childNodes->item(0)->nodeValue; $item_link = $x->item($i)->getElementsByTagName(”link”) ->item(0)->childNodes->item(0)->nodeValue; $item_desc = $x->item($i)->getElementsByTagName(”description”) ->item(0)->childNodes->item(0)->nodeValue; echo (“<p><a href = ”” . $item_link . “”>” . $item_title . “</a>”); echo (“<br>”); echo ($item_desc . “</p>”); } ?> It will produce the following output − Print Page Previous Next Advertisements ”;