May 24

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..

Apr 22

URL Manipulation

Introduction

In web development,  is very common to use links. It is also common that the links need to be manipulated to add or remove parameters. In this post, we will see how to manipulate a link and its parameters so easy and safe.

Breaking a URL in parts

When a programmer doesn’t know the capabilities of PHP to handle URLs, it is common venture to manipulate the string with the URL directly, making operations such as checking if there is ‘?’ in the URL and get the content to the left or right, etc..

The main function to “parse” a URL and break it into parts is parse_url. This function can be used for two purposes: to get all the parts of a URL or to obtain a specific part of a URL (for example, the protocol, the domain, the query string, etc.). For all parts, just pass the URL as a parameter and don’t enter the second parameter:

For a specific part, just pass the second parameter of the function, which specifies which part is desirable. This parameter can have one of the constants:

PHP_URL_SCHEME
PHP_URL_HOST
PHP_URL_PORT
PHP_URL_USER
PHP_URL_PASS
PHP_URL_PATH
PHP_URL_QUERY
PHP_URL_FRAGMENT

Note: If you want the file name, just apply the function on the basename of $parts['path'], as an example:

Breaking the query string into parts

As you can see, the function parse_url returns the query string of the URL in the way it is and not divided into parts. To break the query string into parts, just use the function parse_str passing the query string as the first parameter and the second parameter as a vector. Vector will be populated with the variables present in the query string, so that the array index stores the variable name and each position points to the respective variable value (the value is automatically decoded urldecode). Here’s an example:


Modifying the URL or Query String

After breaking the URL and optionally the query string, just manipulate the vector $parts or $queryArray as desired. For example, let’s change the protocol from http to https, change the port from 80 to 81 and remove the parameter “x” and include the parameter “z” value “abc”:

Riding the URL with the parties

After manipulating the URL and/or query string, we now need to assemble the parts and form the URL as a string. To do this, simply use the function http_build_query to mount the query array to turn it into query string. This function now makes coding using urlencode, then you need not worry about reserved characters.

Unfortunately, http_build_url function is only available via PECL. However, it is a very simple function to implement. See below:

Now just use this function and run:

 

Apr 03

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).
Mar 28

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!

Mar 19

PHP in interactive mode

php

 

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.

Mar 15

PHP SQL Server – Scriptcase 7 is out!

PHP SQL Server – The new version  of Scriptcase 7 came out in January!

With it came many improvements like Dynamic Group By, HTML 5 Charts, Integration with Social Networks, Upload multiple files, Export PDF in Forms, LDAP security, Menus for mobile devices and more!

See a list with some of the new features:

 

  • SQL PDO Drivers (MySQL, PostgreSQL, SQLServer)
  • Toolbar option
  • Mobile menu support
  • Integration: PayPal, Facebook, Google+, Twitter
  • Grid Ajax events
  • PDF export on forms
  • Progress Bar/Drag’n Drop Upload
  • Multiple Upload
  • HTML5 Charts
  • Javaless PDF generator
  • Reworked GroupBy with Multiple Rules
  • Percent(%) field
  • Single-record-detail on master/detail
  • LDAP Support for security module
  • Scriptcase Macros improvement
  • New Scriptcase Macros created

Check more about Scriptcase 7 at: www.scriptcase.net

PHP SQL Server Blog

Jan 18

PHP SQL Server – Constants in Query Result Sets

PHP SQL Server – Constants in Query Result Sets

Constants are not usually specified as a separate column in a result set. It is usually more efficient for an application itself to build the constant value into the results when they are displayed, rather than requiring the server to incorporate the constant value in every result set row returned across the network.

Exceptions to this general rule include:

  • Stored procedures may be called by many different applications or scripts. These procedures do not have access to the constant value that should be incorporated in the results. The SELECT statement in the procedure itself should then specify the constant as part of the select list.
  • When a site wants to enforce a formatting or display standard, the format can be built into a view or stored procedure.
  • A SELECT statement may be executed from a script or a tool that does not support merging constants with a result set after the result set has been returned from the server.

Character string constants are included for proper formatting or readability when character columns are concatenated. This example combines the LastName and FirstNamecolumns into a single column. The character string ‘, ‘ separates the two parts of the name in the new combined column:

Jan 07

PHP SQL Server – FreeTDS to access Sql Server from Linux via PHP

PHP SQL Server – FreeTDS to access Sql Server from Linux via PHP

PHP SQL Server Blog – Compiling and installing FreeTDS and PHP to access SqlServer Linux

cd /usr/src
wget ftp://ftp.ibiblio.org/pub/Linux/ALPHA/freetds/stable/freetds-stable.tgz
tar xfz freetds-stable.tgz
cd freetds*
./configure

PHP

cd /usr/src &&\
wget -c http://www.php.net/get/php-5.2.1.tar.bz2/from/this/mirror
tar xfh php-5.2.1.tar.bz2
cd /usr/src/php-*
‘./configure’ ‘–prefix=/usr’ ‘–disable-static’ ‘–with-apxs=/usr/sbin/apxs’ ‘–sysconfdir=/etc’ ‘–enable-discard-path’ ‘–with-config-file-path=/etc/apache’ ‘–enable-safe-mode’ ‘–with-openssl’ ‘–with-mhash’ ‘–enable-bcmath’ ‘–with-bz2′ ‘–with-pic’ ‘–enable-calendar’ ‘–enable-ctype’ ‘–with-gdbm’ ‘–with-db3′ ‘–with-imap-ssl=/usr/local/lib/c-client’ ‘–enable-dbase’ ‘–enable-ftp’ ‘–with-iconv’ ‘–with-dom’ ‘–with-exif’ ‘–enable-exif’ ‘–with-gd’ ‘–enable-gd-native-ttf’ ‘–with-jpeg-dir=/usr’ ‘–with-png’ ‘–with-gmp’ ‘–enable-mbstring’ ‘–with-curl=/usr’ ‘–with-pcre-regex=/usr’ ‘–with-mysql=shared,/usr’ ‘–with-gettext=shared,/usr’ ‘–with-expat-dir=/usr’ ‘–with-xml’ ‘–enable-wddx’ ‘–with-mm=/usr’ ‘–enable-trans-sid’ ‘–enable-shmop’ ‘–enable-sockets’ ‘–with-regex=php’ ‘–enable-sysvsem’ ‘–enable-sysvshm’ ‘–enable-yp’ ‘–enable-memory-limit’ ‘–with-tsrm-pthreads’ ‘–enable-shared’ ‘–disable-debug’ ‘–with-zlib=/usr’ –with-pdo-mysql –with-mssql –with-pdo-dblib
make
make install

PHP SQL Server Blog

Dec 26

PHP SQL Server – PHP 5.5.0 Alpha2 released

PHP SQL Server - PHP 5.5.0 Alpha2 released

 

PHP SQL Server Blog – The PHP development team announces the immediate availability of PHP 5.5.0alpha2. This release adds new features and fix some bugs from alpha1. All users of PHP are encouraged to test this version carefully, and report any bugs in the bug tracking system.

THIS IS A DEVELOPMENT PREVIEW – DO NOT USE IT IN PRODUCTION!PHP 5.5.0 Alpha 2 comes with new features and improvements such as (incomplete list) :

  • Support for using empty() on the result of function calls and other expressions,
  • Systemtap support by enabling systemtap compatible dtrace probes on linux,
  • Optimized access to temporary and compiled VM variables. 8% less memory reads.

Please, note that this alpha version also introduces the ext/mysql depreciation.

You can read the full list of changes in the NEWS file contained in the release archive.

For source downloads of PHP 5.5.0 Alpha 2 please visit the download page, Windows binaries can be found on windows.php.net/qa/.

Thank you for helping us making PHP better.

Dec 20

PHP SQL Server – Login System with PHP object-oriented

PHP SQL Server – Login System with PHP object-oriented

In this new post of PHP SQL Server Blog we will develop an authentication system with PHP using object orientation. We will need three files: a file to contain the User class, another to perform authentication and redirection and make an HTML page that will contain the form. Well, get to work.

The user class. This class will be on the file user.php

 

 

The HTML Page:

 

The page that will make the authentication data from the HTML page:

 

Well folks, this is an idea for an authentication system. Safety habits like store the password encrypted in the database are important and should be used. To post questions, suggestions and improvements to the code. I have not tested the system. It’s just a tutorial teaching, but either way, it does not cost study and test. In the event that access the database, do not forget to write a connection method.

That’s it folks. Until next.

 

PHP SQL Server Blog