Error Control in PHP

Error handling strategy is used to capture the occurrence of a situation that prevents a successful system operation. This can take place at different levels. Low level: a function can receive an unexpected parameter. At a high level, a tool can not accept certain sequence of user actions.

I think it is crucial to distinguish what is a low-level error of an error high level. Each of these errors can take a different course and be reported to the user differently too. If, for some reason, the programmer created a SQL wrong and this prevented a value to be saved in the database, it is not convenient to tell the user that the problem was in SQL, after all, the end user need not (and should not) know what is SQL. However, if the user has filled in a form field with an invalid value, it must be informed in detail about what he missed and/or how to fix.

Using exceptions natives(exception)  language PHP is a solution particularly suitable for dealing with low-level errors. In the case of high-level errors, can also be used the same alternative, although I prefer to use methods of input validation of user data and store the error messages in an array (for example). Note that usually in these cases there is no attempt to adjust the invalid value entered by the user, so is the responsibility of the user to correct the problem itself. Already low-level error, you can try to be bypassed in some way (or not).

The operation of exceptions can be relatively simple, but also lets you build solutions rather sophisticated. Don’t intend to discuss the use of exceptions. So, if you want to dig, read the manual:http://www.php.net/manual/en/class.exception.php. If you don’t like to create exception to this and that, maybe it’s a good to know the exceptions defined by SPL: http://www.php.net/manual/en/spl.exceptions.php.

A reasonable solution to error control is to create methods that return Boolean values (true = worked / false = went wrong) and, optionally, the method takes an array of errors that should be passed by reference. Then, if a problem occurs, the array of errors is completed and it will return false.

For errors that should never occur (for example, an error use of a resource by a programmer), it is possible to use exceptions, but can also be used to launch the error log. This is done by the function trigger_error. The function receives a message and an error level. Levels that may be issued by the programmer are:

  • E_USER_NOTICE - When you want to send a notification to the programmer (not necessarily an error). For example: a function consumed more memory than expected.
  • E_USER_WARNING - When you want to issue a warning to the programmer (a mistake, but not too severe). For example: failing to connect to the database (for some unknown reason), but the page still can be generated with a warning to the end user.
  • E_USER_ERROR - When the error is fatal and must stop running the script (the programmer can not launch the system if an error is being caused these). For example, a method needed to receive a mandatory data type, but received another.
  • E_USER_DEPRECATED - A special type of warning to indicate that a method is depreciated (should no longer be used and/or has been replaced by a different way to perform the same operation).

There are two functions in PHP especially useful to standardize the flow of processing errors and log unhandled exceptions with try/catch. They are: set_error_handler and set_exception_handler. This makes it possible, for example, store some types of errors in a database to facilitate searches, track the amount in a given period etc..

PHP Settings

PHP is an interpreted language that allows multiple policies are configured, both the core of the language and its extensions.

Each policy has a “mode shift” that defines where and when it can be modified. For example, some can only be set in the settings file managed by the server administrator, for security reasons, while others can be changed by the programmer in the application itself.

The modes change the policies are:

PHP_INI_USER - can be changed with ini_set, file .user.ini or in the Windows registry.
PHP_INI_PERDIR - Can be modified in php.ini.htaccesshttpd.conf or .user.ini.
PHP_INI_SYSTEM - Can be modified in php.ini or httpd.conf.
PHP_INI_ALL - can be modified anywhere.

Note: some policies belonged to a mode change by a certain version of PHP, but switched to another mode in another version of PHP. This information is displayed in the list of language policy.

 

1.0 Configuration files (php.ini)

 

phpini

 

 

The default settings are defined in the PHP files “ini” which have syntax based on simple key/value. They are loaded so that a script starts running, but the values can be cached and re-loaded periodically for performance.

The file name may vary according to sapi used. For example, the default file is php.ini, but if you run the CLI sapi (PHP commands in terminal) is the sought php-cli.ini file and if it is not found, it uses the default file .

These files are in a directory server settings (on Linux are usually in the directory “/etc/”, although this site may be modified during the compilation of PHP or some alternative, although not common). Usually only the server administrator has access to these files for changes, for security reasons. This is especially useful for hosting servers, where scripts from one domain can not interfere in another.

 

2.0 Settings by Programmer

 

There are basically 3 ways programmer override the settings of PHP: through ini_set (at runtime), the .htaccess (if using Apache) or file .user.ini (an alternative created in PHP 5.3). Note that in these cases, the behavior is modified specifically for a script or set of scripts and not all PHP files, as with the php.ini file.

2.1 Using ini_set

Using ini_set, simply specify two parameters: the first is the policy name and the second is the value you want to apply to it (as a string). To get the current value of the policy, there is a function ini_get (simply enter the name of the policy). For the value of all policies, or any policies of an extension, there is a function ini_get_all. And to return the policy value to its initial value (when started the script), just use the function ini_restore stating which policy should be restored. example:

 

2.2 Using .htaccess

Use the file .htaccess for Apache servers is allowed in PHP is being used as a module. Apache must be properly configured to accept this type of file in the application directory. In this case, a policy can be defined using two syntaxes. A non-Boolean values to set and another to set boolean values (which may take “on” or “off”) as examples:

Note: in httpd.conf policies can be modified with php_admin_value and php_admin_flag. This can be useful to apply different settings for different directories (or different virtual hosts).

 

2.3 Using .user.ini

Use the file .user.ini is an alternative to the .htaccess, and was incorporated to PHP in version 5.3. For now, it can only be used by SAPIs CGI or Fast CGI. The syntax used in these files is identical to that used in php.ini.

The file name used for this type of configuration ( “.user.ini“) can be modified in php.ini through policy user_ini.filename. This is typically required when the application is already using that name for another purpose.

Note: it is recommended to hide access to this file, as well as (usually) is done with .htaccess to prevent it can be read by any user accessing the system.

 

3.0 Settings useful to know

  • display_errors and display_startup_errors - Indicates whether errors should be displayed or omitted (normally “on” in the development environment and “off” in the production environment).
  • log_errors - Indicates whether errors should be logged to a log file (usually “off” when “display_errors” is “on”, and vice versa).
  • report_memleaks - Indicates whether the bursts of memory should be shown/logged (usually “on”).
  • memory_limit - amount of memory reserved for PHP during script execution. Normally a simple script needs no more than 10M, but some require much more than that. The directive must be set to a reasonable value for the expanded application and, in cases of tools that require more memory. To evaluate memory usage, see the functions memory_get_peak_usage and memory_get_usage.
  • max_execution_time - Sets the maximum time the script can run before it is aborted automatically by PHP (usually “30″, but can be configured with higher values for heavier tools).
  • precision - Sets the precision of decimal places for real numbers (usually 14).
  • date.timezone - Sets the default timezone of the application (eg “America / Sao_Paulo”)
  • default_mimetype - Sets the mimetype of files generated by PHP which have left with the explicit call to header (‘Content-type: …’) (eg “text/html” or “application/xhtml+xml”).
  • default_charset - Sets the default charset of the files generated by PHP which have left with the explicit call to header (‘Content-type: …; charset = …’).
  • short_open_tag - Defines whether the application will accept the abbreviated notation of PHP tags: “<?” and “?>” (recommended “on” only in closed applications whose portability is not important).
  • aps_tags - Defines whether the application will accept the notation ASP to PHP tags “<%” and “%>” (recommended “on” only in closed applications, where portability is not important).
  • register_globals - Defines whether the application will create global variables to values derived from EGPCS (Environment, GET, POST, Cookie, Server). It is strongly recommended to use “off” because it is a deprecated feature which makes the application more prone to security breaches.
  • magic_quotes_runtime and magic_quotes_gpc - sets whether addslashes automatically applied on the data submitted. It is strongly recommended to use “off” because it is a deprecated feature and featuring a performance disadvantage.
  • arg_separator.output - Separator used by standard PHP functions that build URL. It is recommended “&”, especially for applications XHTML).
  • session.auto_start - Automatically log (usually “off”)
  • session.use_cookies - Indicates whether sessions can use cookies to store session keys (recommended “on”).
  • session.use_only_cookies - Indicates whether sessions can only use cookies to traffic session keys, rather than inform them via GET (it is strongly recommended “on” for security reasons).
  • session.use_trans_sid - Indicates whether sessions can use the mechanism of “transparent sid” to travel the session keys (data passed by GET) (it is strongly recommended “off” for security reasons).

Problems with charset? Never again!

In this article we will see how to use UTF-8 at all and never see characters being displayed wrong.

1.  Save the source code in UTF-8

First of all, choose a good source code editor that allows you to define which encoding used in saved files. Normally this is the editor settings or options of saving time. If you use text mode editors, you may need to configure it in the settings of the terminal command (gnome-terminal, xterm, etc.).

Note: some publishers have option to save the file with the BOM. It is recommended that doesn’t include these bytes, because they can cause unexpected behavior in PHP. For example, you will not be able to call functions such as header or use the namespace feature, which requires that the namespace declaration is the first thing in the script.

2. Tell the browser that you use UTF-8

When a PHP file and generates a HTML is sent to the browser, along with the file go to header (HTTP protocol), where you specify the file type and encoding. If you don’t report it explicitly in your code, your HTTP server (for example, Apache) will send this file with a mime-type pattern (usually “text/html”) and a default encoding (usually “ISO-8859-1 “).

To change this header explicitly, and properly inform the mime-type and encoding of the document you are creating, use the header function, passing the policy “Content-type” as such:


If the file is of another type, just change the mime-type to the corresponding type (eg “text/css”, “text/xml”, “application/xhtml+xml”, etc).

However, the files aren’t always generated via PHP. There are static HTML you need to inform the HTTP header with the mime-type and correct coding. In this case, there is an alternative that is using the meta tag with the attribute “http-equiv” (equivalent HTTP). With it, you can “simulate” HTTP header by the contents of the HTML document. This is done as follows:

In HTML 5, it was simplified:

If you use XML or XHTML, remember to inform the UTF-8 encoding in the XML header:

 

 3. Communicate with the BD via UTF-8

For information to be trafficked between PHP and the database using UTF-8, you must declare this encoding logo that connects to the database. This varies from bank to bank, but let’s see some common examples:

MySQL (PDO):


MySQLi:

MySQL (functions):

Note: the connection to MySQL functions are deprecated. Prefer to use PDO or MySQLi.

PostgreSQL (PDO):

 PostgreSQL (functions):

 

 4. Create your database in UTF-8
The text fields stored in databases also need a character encoding. If it isn’t defined when you create the field, the default encoding is taken from the table or from the database. To set a default encoding of a database, use the command:
MySQL:

 PostgreSQL:

 5 Remember to specify the UTF-8 which you can

Some functions in PHP receive as parameter encoding to be considered. Some of the most important things that should be highlighted are: htmlentities and htmlspecialchars.

Furthermore, when performing operations with regular expressions PCRE, remember to use the modifier “u” at the end of the expression, indicating that it is UTF-8, as an example:


An important set of functions takes into account the location (with encryption) to function. So it is also important to properly set the locale to locale UTF-8:

Remember that the location depends on the server and the name used may vary.

Conclusion:
Taking the necessary steps, you can use UTF-8 with no big problems at all layers of their system: in HTML, PHP and database. Problems with charset? Never again!

PHP in interactive mode

 

Although PHP is specially designed to meet Web requests, it can also be run in a terminal prompt  through php cli. At the terminal, we can run it in different ways, and in this post we will see what they are.

Running a script by terminal:

To run a PHP script from the terminal, just run the command “php” followed by the path to the file to be executed.

 

Running a PHP code by terminal:

To run a PHP code through the terminal, just run the command “php” passing the “-r” parameter, followed by the command to be executed. Note that the command must be delimited by single or double quotes. You may not use the PHP code delimiters to delimit commands (like <? Php and?>), Although you can close it and open it again. Here’s an example:

This can be useful for performing rapid tests for the small terminal, without the need to create a script only to see the result.

One drawback is that if you use double quotes, and you want to run any command involving variables, you need to escape the “$” symbol. Also, if you want to use the same quotes used to delimit the command also needs to escape it, like this:

Note that we can execute more than one command. Simply enclose them by “;”.

Running a PHP code by interactive terminal:

To perform a sequence of PHP codes through the terminal, interactively, simply run the “php” passing the parameter “-a”.

When executing this command, a prompt will be shown in PHP, as shown below:

 

In PHP prompt, you can run PHP commands and the result is shown how a command is completely interpreted. In this case, we can create variables, run loops and print results more easily than the previous form (with “-r”). That’s because we don’t need to worry about escaping quotes and variables.

See an example of a loop executed at the interactive prompt:

 

Note that after adding the first line, we opened a key. With this, the PHP changes the prompt to “php {“. So we closed the keys, the third row inserted, PHP executes the entire block set.

To end the interactive mode, simply run the command “exit” or “quit”. Note that it is different from running the PHP command “exit (0);”. In this case, only the value being set is returned to the shell.

The Main Function of MYSQL Report Builder

It seems that almost everyone in the world is having his or her own website to talk about MYSQL report builder, whether it is for business or personal needs. A website is very beneficial for those who need to promote their products or services. If you are one of those people who need to have your own website pretty
soon, what would you need to make it? You can leave the task for website developers, or you might want to manage it yourself. If you choose the second alternative, then you will need a website builder with MYSQL report builder for developing your own site.

It is much better to develop our own website because we can just manage everything, just in case there are some troubles. Besides, almost all website builders are sophisticated enough and are user friendly. Users can just follow the manuals and there will be clear instructions when things go wrong. It will take shorter time compared to the service that almost all website developers do. Never imagine that the software will require users to handle complicated process of website
builder though users may not know much about technical details about building a website. Some software which are known very user friendly include Weebly Webnode, Yola and so forth.

What makes them more convenient is the coding platforms and built-in programming that most website builders are using. One of the easiest one is MYSQL. It has broader option of data-driven reports with dependable MYSQL report builder which does not take too much time to deal with. Users may just build the audience MYSQL reports builder for their audience or users in creating their own. They can simply choose the kind of criteria, columns, data sources and so forth.

When users are using appropriate MySQL report builder, they can create queries through simple easy GUI interface on demand. This makes users can connect to MySQL databases in simpler and easier ways by running queries to produce CSV format reports.

Top PHP Framework Comparison

I found this PHP Framework comparison on Hotscripts:

Writing a simple database application in PHP and mySQL can take a lot of time and effort – you will have to design the HTML form, write queries, implement validation/error handling, test the application, etc. You can save yourself a lot of time and reduce development cost if you use a PHP Framework. Code generators are desktop or web-based applications that once installed will allow you to define your database and it will automatically generate all the required HTML, CSS and PHP files. You can then simply update these files to your server and get complete running applications in a few minutes.

Here’s the showcase of the top 5 PHP Framework on HotScripts:

ScriptCase

ScriptCase is a complete PHP Code Generator. Through a friendly web interface, the developer can generate rich web applications extremely fast, such as: web forms, html reports, container applications, pdf reports, menus, editable grids, webhelp pages, FLASH charts, auto-complete components using JQUERY technology, master/detail forms and grids.

PHP MySQL Wizard

PHP MySQL Wizard is a smart PHP code generator, with absolute zero knowledge of coding the wizard can generate a functional web application driven from your MySQL database, saving you hours of tedious programming. Using the generated application both administrator and/or users will be able to view, search, sort, edit and delete records from your MySQL Database . The wizard has many friendly and easy to use features such as: fully customizable appearance of the generated application, validation rules, custom error messages, etc.

PHPMaker

PHPMaker is a powerful automation tool that can generate a full set of PHP quickly from MySQL, PostgreSQL, Microsoft Access and Microsoft SQL Server databases. Using PHPMaker, you can instantly create web sites that allow users to view, edit, search, add and delete records on the web. PHPMaker is designed for high flexibility, numerous options enable you to generate PHP applications that best suits your needs. The generated codes are clean, straightforward and easy-to-customize.

AppGini PHP Generator For MySQL

AppGini helps you develop web database applications instantly. You do not need to have any programming background to use it. Just define your database, set some options, click the Generate button, and you’re done! Applications generated will allow your users to view, search, edit data as well as allow administrator to access permissions. The application can then be easily customized using CSS and HTML templates.

ScriptArtist

ScriptArtist is a PHP & AJAX code generator software for MySQL. It helps helps you save a lot of developing times to create the completed CRUD operations (Create, Read, Update, & Delete), easily generates web forms (email or contact form) retrieved information from either database fields or user-defined fields and many more.

Sample of grid creation with connQuery

data_handle

Here is a Framework PHP usage sample of a grid creation with connQuery return array. Only numeric and text values can be recovered that way. I’ll show a sample for blob fields later.

I started the session and called the initial files: Simple Mysql, Connections file and the Header:

Inside myconn.php I have:

And this is my header.php:

The css called on the header is available Here.

The key point of the page is using the array to build a HTML table dynamically, following the rows and columns count:

Note that I protected the result inside the table: If that column is empty, the code will echo a ‘&nbsp;’, to prevent the cell to be not shown.

It used half of the array count too. It is because the connQuery returns twice each query column(Explained here).

At the end of the page, I just called the Footer and closed the session:

This is the footer.php:

All these files are available on the Download Page, under Samples.

Famework PHP Connection File using connCreate

Before start our Famework PHP application, we can use connCreate to define all the connections used by your application. There is a sample of a Famework PHP script to include connections in a batch process. This file must be included before the functions include.

This file will create all the connections needed by my application. To add more connections, we use this template:

This will be available at the Download Page, in the Samples.

Framework PHP – connQuery

One more function to our Framework PHP MySQL Simple Functions: connQuery(). This function will execute a SQL Statement on the connection used and return it’s results. If the query fails, it will return False. If the statement returns no value, the array returned will be empty.

The values returned are listed twice on the array: One with the variables names as numeric values in ascending order and other with the columns names for the variables names, for example.

This query will fill the array like this:

So, let’s see the Framework PHP function code:

It will available at the Download Page, in MySQL Simple Functions, here, at Framework PHP.

Framework PHP – Functions Change

Reworked connCreate() and connStart() from our Framework PHP to select automatically the database.

They’re available for Download on the Download Page, here, on Framework PHP.