Modern PHP The_Surpisingly_Simple_Truth_Behind_Extrao_-_Gary_Keller. pdf The Core PHP Programming Using PHP to Build Dynamic Web Sites. The O'Reilly logo is a registered trademark of O'Reilly Media, Inc. Modern PHP, the cover image, and related trade dress are trademarks of O'Reilly Media, Inc. To address this problem, Josh Lockhart has written Modern PHP, Assume we need to run a report and generate a PDF file with the results.

Modern Php Pdf

Language:English, French, Arabic
Published (Last):08.02.2016
ePub File Size:18.33 MB
PDF File Size:20.79 MB
Distribution:Free* [*Sign up for free]
Uploaded by: ROSITA

The classic PHP has won a rebirth, so it's time for the modern PHP to throw away its old burden and follow better practices. But almost all the. Learn how to tune, test, and deploy PHP applications in this free excerpt from O' Reilly's "Modern PHP". Free PHP eBooks. Contribute to manithchhuon/the-best-php-books development by creating an account on GitHub.

Composer does this for us. To install the Flysystem component, for example, run this command: The previous example, as of October , installs Flysystem version 0. You can review the result of this command in the newly created or updated composer. This command also creates a composer. Commit both of these files into your version control system.

Our project will be a command-line application, and the path to the CSV file will be the first and only command-line argument. The scan. It is certainly possible to write our own code to iterate a CSV file or send HTTP requests, but why should we waste our time if these problems are already solved?

Remember, our goal is to scan a list of URLs. It also creates a composer. This effectively locks our project to these specific PHP component versions. If a composer. You should version control the composer. If your team members, your staging server, and your production server all use the same PHP component versions, you minimize the risk of bugs caused by component version discrepancies. The one downside with the composer. If you do need to download newer component versions and update your composer.

The composer update command updates your components to their latest stable versions and also updates the composer. Luckily for us, when Composer downloads the PHP components it also creates a single PSR-compatible autoloader for all of our project dependencies.

Pretty neat, huh? Implement scan. How do we know to use these particular namespaces? Remember, good PHP components have documentation. Add a few URLs to the urls.

Make sure at least one URL is invalid. Next, open a terminal and execute the scan.

The first argument is the path to the scan. This is a great way to automate maintenance tasks for your web application. Learn more about writing PHP command line scripts here: As much as I create and use open source software, I recognize that using only open source PHP components may not always be possible.

Sometimes we have to mix open source and proprietary components in the same application. This is especially true for companies that use internally developed PHP components that cannot be open sourced due to licensing or security concerns. Composer makes this a nonissue. Composer can manage private PHP components whose repositories require authentication.

Composer also asks if you want to save the repository authentication credentials in a local auth. An example auth. Instead, let project developers create their own auth. The example. The final two arguments are the username and password credentials. You can also save authentication credentials system-wide by using the --global flag. This flag lets Composer use your credentials for all projects on your local machine: Tip Learn more about Composer and private repositories in Authentication management in Composer.

The PHP community is built on a foundation of sharing and helping others. Tip Be careful that you do not rewrite components that already exist.

If you improve upon an existing component, consider sending your improvements to the original component as a pull request. Otherwise, you risk confusing and fragmenting the PHP component ecosystem with duplicate components. Remember, each PHP component uses a globally unique vendor and package name combination to avoid name collisions with other components.

I recommend you use only lowercase letters for your vendor and package names. A vendor name is the brand or identity to which a component belongs. Many of my own PHP components use the codeguy vendor name because this is my online identity. Tip Search Packagist before you choose a vendor name to make sure it is not already claimed by another developer. A package name identifies a PHP component beneath a given vendor name. Many components can live beneath a single vendor name.

This is not true.


The vendor and package names are only used by Packagist and Composer to identify a component. This namespace does not exist yet. I just pulled this out of thin air for this particular component. We will not use this directory in this example. It includes information used by Composer to find, install, and autoload the PHP component.

Example shows a composer. It includes all of the composer. The URL Scanner component composer. This value is displayed on Packagist. This description is displayed on Packagist. These keywords help others find this component on Packagist. You can read more about software licenses at http: Remember to always release your code with a license. You should include at least a name and URL for each author. I prefer to include an email address and support forum URL. You could also list an IRC channel, for example.

I also like to list the minimum PHP version required by this component. All dependencies listed beneath this property are installed for both development and production project installations.

For example, I often list phpunit as a dev dependency so that other component contributors can write and run tests. These dependencies are installed only during development. They are not installed in production projects. Composer does not install suggested components. I recommend you use the PSR-4 autoloader, as demonstrated in Example This makes our component compatible with a standard PSR-4 autoloader. Tip Learn more about the complete composer.

This is especially true for components hosted on GitHub and Bitbucket. Use this to your advantage! All you have to do is add the. Learn more about the Markdown format at Daring Fireball. We want our URL scanner class to be as generic as possible.

Before we submit our component to Packagist, we must publish it to a public code repository. However, any public Git repository is fine I have published this component to GitHub. This lets component consumers request specific versions of your component e. You can also log in to Packagist with your GitHub credentials. Once logged in, click the big green Submit Package button at the top right of the website.

Packagist verifies the repository URL and prompts you to confirm your submission.

Click Submit to finalize your component submission. Packagist creates and redirects you to the component listing, which looks Figure Packagist establishes a direct correlation between repository tags and semantic version numbers. This is why I recommend your repository tags be valid version numbers like 1. However, we still have that big red alert message that reads: This package is not auto-updated. We can activate a GitHub or Bitbucket hook that notifies Packagist whenever the component repository is updated.

Learn how to setup this repository hook at https: Run this command in your terminal to install the URL scanner component with Composer: Good Practices This chapter contains an assortment of good practices that you should apply when building PHP applications. Following good practices makes your applications faster, more secure, and more stable.

The PHP language is an accumulation of tools introduced piecemeal over a long period of time, and we use these tools to apply good practices. Tools change with the passage of time as newer and better solutions are introduced in newer PHP versions.

The trick is knowing which tools to use and which to ignore. This chapter contains good and practical advice that I use every day in all of my own projects. You can immediately apply this knowledge to your own projects.

Note Good practices demonstrated in this chapter have always been possible with past and present PHP versions. However, how you implement these practices changes as the PHP language evolves. Newer PHP versions introduce tools that make it easier to apply good practices.

This chapter demonstrates how to apply good practices with the latest tools in PHP 5. Never trust any data that originates from a source not under your direct control. A few external sources are: Writing a PHP script that receives user input and renders output is easy.

Modern PHP - New Features and Good Practices

Doing so safely requires a bit more thought. The simplest advice I can give you is this: This is your first line of defense. For example, assume your website comment form accepts HTML.

This is one example why you must sanitize input data that you do not control. The htmlentities function is dumb, though. It does not validate HTML input. It does not escape single quotes by default.

The first argument is the input string. Regular expressions are complicated, the HTML input can be invalid, and the risk of error is high. Sometimes this input data arrives in an HTTP request query string e. Other times this input www. Never use unsanitized input data in a SQL query. PDO is a database abstraction layer built into PHP that presents a single interface to multiple databases. These two functions accept a variety of flags to sanitize different forms of input: Example demonstrates how to sanitize an email address by removing all characters except letters, digits, and!

Unlike sanitization, validation does not remove information from input data. Validation only confirms that input data meets your expectations. If you expect an email address, make sure the input data is an email address.

If you expect a phone number, make sure the input data is a phone number.

Validation also prevents potential database errors. Example demonstrates how to validate an email address. If the validation succeeds, the return value is the original validated value.

Browse more videos

If the validation fails, the return value is false. I recommend these additional validation components, too: Escape output with the PHP htmlentities function that we mentioned earlier. Specify the appropriate character encoding usually UTF-8 as the third argument.

Example demonstrates how to escape HTML output before it is rendered. The Twig template engine by Sensio Labs, for example, escapes all output by default unless you tell it otherwise.

This is a brilliant default and provides a nice safety net for your PHP web applications. How often have you cancelled a credit card because a major retailer was hacked? Many retailers have and will fall victim to malicious hackers because they do not protect their systems with best security practices. Your PHP applications are no different, and they are vulnerable to the same attacks unless you use appropriate precautions. One important precaution is password security. It is your duty to safely manage, hash, and store user passwords.

Your users entrust you with their information and expect you to guard their information with the best security practices available. After all, securely managing passwords is hard. Fortunately, PHP provides built-in tools that make password security fairly easy. This section demonstrates how to use these tools with modern security practices. Leaked passwords are a serious breach of trust, and they dump a mountain of legal liability on you or your company.

The less you know, the safer you are. I understand that password formats may be restricted for compatibility with legacy applications or databases, but this is not an excuse for poor security practices.

If you require passwords to fit a particular pattern, you are effectively providing a roadmap for bad guys to hack your application. If you must restrict user passwords, I recommend you only require a minimum length.

It is not unreasonable to blacklist commonly used or dictionary-based passwords, too. If you send my password via email, I know three things: Instead, send an email with a URL where I can choose or change my own password.

Web applications often generate a unique token that can only be used once to choose or change a password. For example, suppose I forget my account password for your web application. Your application generates a unique token, and it associates this token with the account identified by my email address. When I visit the URL, your application validates the token and, if the token is valid, allows me to choose a new password for my account.

After I choose a new password, your application invalidates the token. Do not encrypt user passwords.

Encryption and hashing are not synonymous. Encryption is a two-way algorithm, meaning what is encrypted can later be decrypted by design. Hashing is a one-way algorithm. Hashed data cannot be reverted to its original form, and identical data always produces the same hash values. When you store a user password in your database, you hash the password first and store the password hash in your database.

If hackers break into your database, they see only meaningless password hashes that require a massive amount of time and NSA resources to crack. Many hashing algorithms are available e. Some are fast and designed to verify data integrity.

Others are slow and designed to be safe and secure. Slow, safe, and secure are what we want when it comes to password generation and storage. The most secure peer-reviewed hashing algorithm known today is bcrypt. The bcrypt algorithm automatically salts data to foil potential rainbow table attacks. The bcrypt algorithm also consumes a large amount of time measured in seconds while iteratively hashing data to generate a super- secure final hash value.

The number of hash iterations is called the work factor. A higher work factor makes it exponentially more expensive for a bad guy to crack password hashes.

The bcrypt algorithm is future-proof, too, because you can simply increase its work factor as computers become faster. The bcrypt algorithm is extensively peer-reviewed. Minds far greater than my own have reviewed the bcrypt algorithm for potential exploits, and so far none has been found. It is very important that you rely on peer-reviewed hashing algorithms.

Never create your own. There is safety in numbers, and odds are you are not a cryptography expert unless you are, in which case tell Bruce Schneier I said hello. The password hashing API also uses the bcrypt hashing algorithm by default. Note Anthony Ferrara also known as ircmaxell on Twitter is a Developer Advocate at Google, and he is an authoritative source for all things related to PHP performance and security.

I encourage you to follow Anthony on Twitter and read his blog. I want to say a big thank you to Anthony. His contributions to PHP have single-handedly improved PHP application security by making best security practices more accessible.

We create a user account if the email address is valid and the password contains at least eight characters. Example is the register. Lines 4—7 validate the user email address.

Modern PHP: New Features and Good Practices

We toss an exception if the email is invalid. Lines 10—13 validate the plain-text user password pulled from the HTTP request body. We toss an exception if the plain-text user password contains fewer than eight characters.

The final argument is an array of hashing options. The cost array key specifies the bcrypt work factor. A work factor of 10 is used by default, but you should increase the cost factor for your particular hardware so that password hashing requires 0.

We toss an exception if the password hashing fails. Lines 26—29 demonstrate saving a hypothetical user account. These lines contain pseudocode; you should replace these lines with code appropriate for your own application. The point is that you persist the user record with the password hash — not the plain-text password pulled from the HTTP request body. We also persist the email address that is used to locate and log in a user account.

This gives you flexibility to continue storing future passwords that may require more characters than the current bcrypt algorithm. The login. Example shows the login. Line 5 and 8 retrieve the email address and password from the HTTP request body. Line 11 locates the user record associated with the email address submitted in the HTTP request body. I use pseudocode in Example , and you should replace this line with code specific to your own application.

Lines 14—16 compare the plain-text password submitted in the HTTP request body with the password hash stored in the user record.

If verification fails, we toss an exception. Verify password www. This function accepts two arguments. The first argument is the plain-text password. The second argument is the existing password hash in the user record.

Otherwise, the plain-text password is invalid and we abort the login process. Rehash password After line 17 in Example , authentication is successful and we can log in the user.

Before we do, however, it is important to check if the existing password hash in the user record is outdated.

If it is outdated, we create a new password hash. Why should we create a new password hash? Pretend our application was created two years ago when we used a bcrypt work factor of Today we use a bcrypt work factor of 20 because hackers are smarter and computers are faster. Unfortunately, there are some user accounts whose password hashes were generated with a bcrypt work factor of This function makes sure a given password hash is created with the most current hashing algorithm options.

If a password hash does need to be rehashed, rehash the plain-text password from the HTTP request body using the current algorithm options and update the user record with the new hash value.

Pretty much every PHP developer has, at one time or another, made a mistake working with dates and times. This is precisely why I recommend you do not manage dates and times on your own.

There are too many considerations to juggle, including date formats, time zones, daylight saving, leap years, leap seconds, and months with variable numbers of days.

These helpful classes provide a simple object-oriented interface to accurately create and manipulate dates, times, and timezones. There are two ways to set the default time zone. You can declare the default time zone in the php. You can find a complete list of PHP time-zone identifiers at http: A single DateTime instance represents a specific date and time. You can pass a string argument into the DateTime class constructor to specify a custom date and time Example The string argument must use one of the valid date and time formats listed at http: Unfortunately, this is not always the case.

Sometimes you must work with date and time values in different and unexpected formats. I experience this problem on a daily basis. Many of my clients send Excel spreadsheets with data to import into an application, and each client provides date and time values in wildly different formats. The DateTime class makes this a nonissue. Use the DateTime:: The second argument is the date and time string that uses said format Example Valid date and time formats are available at http: A DateInterval instance represents a fixed length of time e.

You use DateInterval instances to modify DateTime instances. Both methods accept a DateInterval argument that specifies the amount of time added to or subtracted from a DateTime instance. Instantiate the DateInterval class with its constructor. The DateInterval class constructor accepts a string argument that provides an interval specification.

First, an interval specification is a string that begins with the letter P. Next, you append an integer. And last, you append a period designator that qualifies the preceding integer value. Valid period designators are: If you include a time value, separate the date and time parts with the letter T.

For example, the interval specification P2D means two days. Example demonstrates how to modify a DateTime instance by a given interval of time using the add method.

This lets you traverse a DatePeriod instance in reverse chronology! Time zones are tricky, and they are a constant source of confusion for many PHP developers. All you have to do is pass a valid time-zone identifier into the DateTimeZone class constructor: I convert the UTC date and time values to the appropriate time zone when I display the data to application users.

Repeating calendar events are a good example. The DatePeriod class solves this problem. The DatePeriod class constructor accepts three required arguments: A DateTime instance that represents the date and time from which iteration begins A DateInterval instance that represents the interval of time between subsequent dates and times An integer that represents the number of total iterations A DatePeriod instance is an iterator, and each iteration yields a DateTime instance.

Example yields three dates and times separated by two-week intervals. Carbon provides a simple user interface with many useful methods for working with date and time values. If you work with different databases in one or more projects, you have to install and learn various PHP database extensions and interfaces. This increases your cognitive and technical overhead.

Database implementations are abstracted away. Instead, we can write and execute database queries with a single interface regardless of the particular database system we happen to be using at the time.

This is the downside to PDO. Each database provides proprietary features, and these features often require unique SQL syntax.

If you absolutely must use a proprietary database feature, keep in mind you must update your SQL statements if you change database systems. Install the database, create the schema, and optionally load an initial dataset. The PDO class constructor accepts a string argument called a DSN, or data source name, that provides database connection details. A DSN begins with the database driver name e.

The DSN connection string is different for each database, but it typically includes: Provide these arguments if your database requires authentication. The database is available at IP address The database username is josh, and the database password is sekrit. The connection character set is utf8. The DSN begins with mysql:. After the: Specifically, we specify the host, dbname, port, and charset settings. If PHP www. Instead, move your database credentials into a configuration file above the document root and include them into your PHP files when necessary.

Tip Do not version control your credentials, either. Protect your credentials with a. Otherwise, you will publish your secret credentials into your code repository for others to see. This is especially bad if you are using a public repository. In this example, the settings. It lives beneath the project root directory but above the document root. The index.

Modern PHP: New Features and Good Practices

It includes the settings. If the index. It provides a welcome mat for hackers to do bad things to your PHP application. It is extremely important to sanitize user input that is used in a SQL statement. Fortunately, the PDO extension makes input sanitization super- easy with prepared statements and bound parameters. A prepared statement is a PDOStatement instance.

In Example , the: Without the third argument, a prepared statement assumes bound data is a string. Example shows a modification of Example that finds a user by numeric ID www. This tells PDO that the bound data is an integer. There are several PDO constants you can use to specify various data types: I use this method to iterate large result sets, especially if the entire result set cannot fit in available memory Example This argument determines how the fetch and fetchAll methods return query results.

You can use any of these constants: The array keys are database column names. The array keys are the numeric index of database columns in your query result. This is a combination of PDO:: Note Learn more about fetching PDO statement results at http: I typically discourage this method unless you are absolutely sure the complete query result is small enough to fit in available memory.

This method, similar to the fetch method, returns the value of a single column from the next row of the query result Example Tip The query result column order matches the column order specified in the SQL query. It therefore becomes the second column in each query result row, and I pass the number 1 into the fetchColumn method columns are zero-indexed.

A transaction is a set of database statements that execute atomically. In other words, a transaction is a collection of SQL queries that are either all executed successfully or not executed at all.

Transaction atomicity encourages data consistency, safety, and durability. A nice side effect of transactions is improved performance, because you are effectively queuing multiple queries to be executed together at one time. Note Not all databases support transactions. Transactions are simple to use with the PDO extension. You build and execute SQL statements exactly as demonstrated in Example There is only one difference.

Browse more videos

The commit method executes queued queries in an atomic transaction. If a single query in the transaction fails, none of the transaction queries is applied. Remember, a transaction is all or nothing. Atomicity is important when data integrity is paramount. Our code can deposit funds into an account. It can also withdraw funds from an account assuming there are sufficient funds. It does not use a database transaction. Perhaps our hosting company had a power outage or a fire or a flood or was afflicted by some other calamity.

Below is minimal. There is no plugin for compiling a LaTeX document, so we need to directly execute the command on a file. Looks like we need to save the output somewhere then. When it gets some text, it will generate a PDF containing the text. Once the template code is hidden away, this powerful technique is easily applied.

Results This is only a minimal example. In any real application, your template would be more extensive. PHPUnit is particularly useful for consistency and scalability testing. Selenium Selenium is a lightweight, open source testing framework that lets anyone create custom UI tests in any language. It is compatible with most browsers, and it deploys on Windows, Linux and macOS.

This open source solution enables single-step debugging and stack trace functionality.

Available as a plugin for Eclipse, PHPDesigner and most other development environments, Xdebug is compatible with dozens of other front end debugging tools. Combine it with the Xdebug extension to view local variables and call stacks in a macOS interface. You can integrate cross referencing and tutorials by linking between documentation. It even includes helpful details like code coverage and complexity information.Tools change with the passage of time as newer and better solutions are introduced in newer PHP versions.

Generators are a tradeoff between versatility and simplicity. Now, save the file - using that directory structure we mentioned as well. The third and final number is the patch release number; the patch release number is incremented when the PHP component receives backward-compatible bug fixes. To do this, tell the PHP web server to listen on all interfaces by using 0. For rare languages , three letters are used.

An opcode cache prevents redundant compilation by storing opcodes in memory and reusing them on successive calls. Travis CI has done a great job of making continuous integration a reality even for small projects. Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can create and edit your files on your host machine and then run the code inside your virtual machine.

URSULA from Monterey
Also read my other posts. I absolutely love lumberjack. I do like studying docunments keenly.