PHP

118K

Solutions

32K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

Share tech news, updates, or what's on your mind.

Sign up to Post

Originally, this post was published on Monitis Blog, you can check it here.



In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer technologies such as mobile and social media, customers are the ones who “shop with their voice” so to speak. The world of blog, forums, and numerous other social media channels over the past decade have provided consumers with unheard of power to determine their choice of products, brands, and services. Because of this power customer expectations have also gone through the roof. Continuing advances in technology, along with the “consumerization of IT,” has meant that companies are now expected to offer real-time, 24/7 service to meet the demands of mobile savvy customers.

 

Today, it’s all about meeting the customer needs and getting them to buy your products. And in order to do so, companies need to ensure their applications and websites are in tip-top shape. Customers simply will not have any patience for a website or application that is error prone or buggy or one that takes forever to load. This is why website performance and application monitoring is so central to your business strategy.

 

We talk about this subject a lot because it’s really so critical to the bottom-line of a business. And it’s even becoming more incumbent today as the demands of new technologies like the Internet of Things and wearables mean that customers are interacting with companies and their products through more endpoints than ever before. All of these channels require performance monitoring to ensure that things run as efficiently and optimally as possible. At the end of the day, web performance is really about keeping the customers happy.

 

In what follows, we want to do a reality check by discussing 7 “sure fire” ways to improve your web performance and make sure your customers keep coming back. After all, your business ROI really depends on it!

 

1. Keep Things Fast!

 

Research shows a clear relationship between web load speed and customer conversions. The faster a page loads the more likely customers will be to visit and do business on your site. The inverse is also true. The slower a page the less likely customers will be willing to wait around and engage with your brand. While this seems fairly straightforward, it’s surprising how few business owners really get the importance of website performance and the role it plays in their business strategy. It might be nice to have a trendy looking website, but if it takes 10 seconds to load visitors won’t hang around long enough to appreciate all the bells and whistles anyway.

 

 

2. Make Your Central Message Crystal Clear

 

From the moment visitors hit your page you want to give them a clear reason for why they should stick around. To do this you need to deliver your central message as quickly, clearly, and convincingly as possible. Don’t make your home page so convoluted that folks don’t know what action to take. Use large font, go generous on the content, and create clear pathways to the channels they need to purchase your product . . . period, end of story.


3. Give Visitors a Reason to Return

 

So you’ve got some visitors, now what? Well, that’s only half the battle. Studies show that most will not purchase on the first visit. So you need to give visitors a solid reason to return to your website. Do this by providing them with something useful, something they can’t refuse. Provide practical articles, a regularly updated blog, a newsfeed, or other user-generated content . . . anything that will engage your visitors and provide them with something of value.

 

4. Check Your Web Hosting

 

When reviewing web performance one of the first things to check is your web hosting service. It’s surprising how many times this gets overlooked. Even though your provider may offer you unlimited bandwidth, does that mean shared service with other sites that end up affecting your own web performance? Are you frequently experiencing downtime or bandwidth issues? If so, it’s worthwhile to review your hosting options to ensure you’re getting the most efficient service. Don’t be afraid to insist on 99.99% uptime.

 

5. Use Web Analytics & Gather Metrics

 

To some, this sounds like a well-worn cliché by now, but it needs to be drilled in more and more. If you’re not tracking the behavior of your visitors with metrics then you’re leaving money on the table. There are many web analytics tools on the market today that can help you closely monitor your customer’s online behaviors. The ability to track a single customer across your site and across multiple devices will ensure that you can tailor your brand to their needs. For instance, you want to learn more about when and where they’re visiting from, what devices they’re using, what are their online activities, and other key demographics such as age. Gaining these insights will help your organization better understand what’s important to your visitors and how to personalize their experience.

 

6. Take It Easy on Design ‘Best Practices’

 

Increasing the size of your website images, third-party scripts, and style sheets come with a heavy price and can adversely affect performance. This is especially true in the world of mobile. Over 50% of all time consumers spend on retails site is on mobile devices and more than 50% of consumers multiscreen during the purchasing. According to this slide deck, some of the worst practices are web pages that are initially blank and then populate, pages where the call to action is the last thing to render, popups that block the rest of the page, and designing and testing in a way that the user experience is completely overlooked.

 

7. Adopt Cloud-Based Website Monitoring

 

There are significant advantages to offloading your website monitoring to a cloud-based host – cost, scalability, efficiency, to name a few. Not to mention, this frees you up to focus on growing your business, which matters the most anyway.

 

If you’d like to get onboard with the latest in cloud-based monitoring then you should try a 24/7 monitoring service like Monitis. With its first-class global service, Monitis allows organizations to monitor their network anytime and from anywhere. For instance, with Monitis you can load test your website to determine at what point it starts creating traffic issues. They’ll also send you timely alerts by every possible means (live phone messages, text, email, Twitter, etc.) to keep you apprised about your site performance. If your web hosting services go down then Monitis will be first to let you know.

 

When it comes to monitoring your website, you don’t want to shortchange yourself. Get the peace of mind you deserve by entrusting your business to a proven industry leader. Go to Monitis and sign up for a free trial today and let them help boost your bottom-line. You’ll be glad you did!

0
[Webinar] Learn How Hackers Steal Your Credentials
LVL 9
[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
0
 
LVL 1

Author Comment

by:Shai Alon
Comment Utility
You're right, and I'm sorry.
I was frustrated from that post that it bothered me that the answer seemed simple.
I've modified the post to be neutral and answer the question only.

Regards,
Shai
0
Article Header
This article discusses how to implement server side field validation and display customized error messages to the client.
5
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
0
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
1
Introduction
This article is intended for those who are new to PHP error handling.  It addresses one of the most common problems that plague beginning PHP developers: effective error visualization.

PHP error handling is well-documented in the online man pages, but the documentation often eludes beginners, who are trying to learn PHP by copying examples they found on the internet.  Copying the code without understanding the code is an antipractice, and there are so many bad PHP examples out there, it can sometimes be difficult to find good ones!  This article will help you get the most, quickly and easily, out of PHP's basic error handlers.  You can get excellent error information, informative and well-targeted, by just following a few simple examples.  So stop copying those obsolete internet examples, and instead make a few "teaching examples" for your own library.  By the time you've finished this article, you will have some great insights into how to diagnose the most common errors quickly and find good solutions.

What's Covered Here
PHP has unlimited opportunities for errors, but in practice only a few things are needed to get good diagnostics.  You need to be able to see the errors in PHP and you need to …
3
 
LVL 110

Author Comment

by:Ray Paseur
Comment Utility
Thanks, Martin.

Some time ago when I published articles, there was a cascade of approvals - something like "It's OK" then "It's good" then "It's really good" and each of these approvals gave some more points as well as comments about how the article can be made better.  Does E-E still do that?
0
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
5
 
LVL 6

Expert Comment

by:mmarth
Comment Utility
can a file be encrypted with OpenSSL as it is being streamed in so it is not first saved in plaintext form
0
This article discusses how to create an extensible mechanism for linked drop downs.
0
Image Overlay
This article discusses four methods for overlaying images in a container on a web page
4
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to use "screen scrapers" to attack web forms.
4
 
LVL 1

Expert Comment

by:Braveheartli
Comment Utility
it's a great article. I wish I had read it earlier.
Thank you very much Ray Paseur
0
[Webinar] How Hackers Steal Your Credentials
LVL 9
[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logout, and Easy Access Control.
3
These days socially coordinated efforts have turned into a critical requirement for enterprises.
1
Questions about connecting to Microsoft SQL Server using PHP come up fairly often.  This article covers a little of the basics and history.
0
Creating and Managing Databases with phpMyAdmin in cPanel.
0
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
9
 
LVL 9

Expert Comment

by:Brandon Lyon
Comment Utility
Thanks for the info
0
 
LVL 40

Expert Comment

by:evilrix
Comment Utility
Nice article!

I'm one of those poor souls who has to write cross-platform C++ code and the headaches involved in getting Unicode encoding working in a cross platform way is a nightmare. In general, we stick to UTF8 right up until we hit the system functions. On *nix platforms UTF8 works fine, on Windows one has to convert to UTF16. It's a bit of a pain, because there is a little inefficiency in doing this but it's normally not enough to cause concern.

What doesn't help is the fact Microsoft continuously refer to UTF16 as Unicode and anything else as ANSI. This has confused a lot of Windows programmers into thinking if it's a 16 bit data type it must be Unicode and if it's an 8 bit data type it's not. Ironically, Windows has no native support for UTF8 at the API level, even though it does have a UTF8 code page! I wish someone would welcome Microsoft into the 21st Century :)

UTF8 is really the only portable encoding format and for my money it's the encoding format I'd go for every time. Anyone interested in Unicode transformation and encoding, either because they are an engineer or they are a masochist, should also find the following resource really very useful and a nice compliment to this well written article.

http://utf8everywhere.org/

Thanks, Gonzo.
0
So you have coded your own WordPress plugin and now you want to allow users to upload images to a folder in the plugin folder rather than the default media location? Follow along and this article will show you how to do just that!
2
Introduction
JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more efficient and more widely supported, JSON has become the dominant technology for use in AJAX applications, APIs, and other data interchange applications where data structure and data elements must be communicated between applications and web services.

JSON is frequently found in combination with RESTful APIs, where XML has rightly fallen into disuse.  This article will examine some of the ways XML and JSON are similar and different, and will show ways of using JSON to our advantage.

Some code examples will show how to create and interpret JSON strings, and detect JSON errors.

A Bit of Test Data
Since the most important thing a programmer can have is a good test case, let's start with some good test data.  Here is the information we will use for all of our code examples.  This information will represent people, giving their names and ZIP codes.  While the example is truly minimalist, it's sufficient to illustrate the principles.
firstName lastName zipCode
John      Doe      20007
Mary      Doe      20016

Open in new window


A Bit of Test Data Organization
Both XML and JSON can represent the data structure.  Here is how our data will be organized.
People (with a date attribute)
|_ Person
   |_firstName
   |_lastName
   |_zipCode

Open in new window


The Old School Way: XML
XML, or Extensible Markup Language, is a text-string data transport mechanism.  It was popularized in the 1990s when SOAP
11
 
LVL 43

Expert Comment

by:Rob
Comment Utility
Ray,

Great article (as always) :).  I just wanted to address the "Using JSON Strings in JavaScript" section of your article.

I'd like to see the distinction between JavaScript and jQuery/AngularJS to show that jQuery & AngularJS are frameworks of the JavaScript language. In otherwords, they are just JavaScript. They do not implement their own version of the ECMA-262 standards.  Node.js on the other hand DOES have its own version but being only a server side language, that's a different story.

On another note, JSON in the browser still needs to be decoded from a string to be a useful JavaScript native object. Any data that PHP returns in JSON format will need to be decoded using the JSON.parse() native JavaScript function.  jQuery will do this automatically when the getJSON() or ajax() with the dataType set to "json" but vanilla JavaScript will not.  For your reference: http://www.w3schools.com/js/js_json.asp

Following on from this, the example you go on to give isn't a string, but a JS object.  I'd like to see an example of using the native functions for converting JSON strings to objects as indicated here: http://www.w3schools.com/js/js_json.asp
0
 
LVL 110

Author Comment

by:Ray Paseur
Comment Utility
Hey, Rob.  Thanks for your comments.  Why not add your clarification examples to the comment thread here, or post a new article about this?  Especially if any of my old code and data examples are overtaken by current events... technology is always advancing!
0
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to do amazing, modern things with bits!
27
 
LVL 35

Author Comment

by:gr8gonzo
Comment Utility
@philkryder - The impact is going to be different depending on the application. For example, let's say that you do have this situation where you're dealing with 20 million 15-byte strings (roughly 286 megabytes).

If you're dealing with a database, then typically you're in a client/server setup, so the client needs the data locally in order to do any viewing or processing (this can be expanded also to a scenario where you've got DB Server -> Web Server -> End User, and data has to be transferred twice - and that's just basic setups).

Typically, the data's going to be transmitted over a TCP/IP network connection, so you're also adding about 8 megs of TCP overhead for 300,000,000 bytes (versus 2 megabytes for 80,000,000 bytes). You also have overhead of the structure containing/defining the data, plus any extra identifying data, but we'll set that aside for now.

So let's say that the database server has all the resources it needs to send all the data across to the client. On a LAN, it might not take too long either way, but you'll still notice a significant difference between transferring 78-ish megs vs 294-ish megs.

If you're dealing with a situation where you transfer that over a broadband connection of some kind, the difference will be even larger.

So the majority of the time, your "extra time" is going to be found in the data transfer, since that's often the slowest point. For the sake of having some example numbers, let's say that we're transferring over a 60Mbps connection, so we're looking at anywhere from 30 seconds - 45 seconds to download a roughly-300 meg payload, and 10-15 seconds to download a roughly 80-meg payload.

We'll say that we can save about 20-30 seconds in transfer time.

Now let's say the client app finally has the data in memory. It probably needs to store it somewhere, so there's some kind of structure involved, which also means an extra % of overhead storage in memory. Let's say you have a C# app using a DataTable structure. A string column in a DataTable takes up a LOT more memory per row than a long column. I don't have hard numbers in front of me, but I did have a project once where I hadn't defined my column type and I was accidentally storing small integers as a string. When I fixed the problem with a byte type definition on the field, memory usage dropped by several hundred megabytes.

So now we've got a client app with the data in memory. What's the next step?

If we're displaying the data on-screen, then chances are that you're probably only converting a handful of records at a time - maybe 200 at most.  The time it takes to convert 200 longs into string is around 0.001 seconds each time (just a rough test on my end).

But let's say you want to convert those 20 million numbers into 20 million entries all at once to be written to a file. Let's say that looping through 20 million records in memory takes a full 3 seconds, with absolutely no processing at all, so it wouldn't matter if the numbers were already converted or not - 3 seconds is the starting baseline. Your question is then - how much ADDITIONAL time would it take to convert 20 million numbers? A rough test on my machine shows about 40 seconds, and of course, that's going to depend on processor power. Many machines might be even slower.

So now we have some example numbers.
You have about 20-30 seconds of savings on the transfer side. If you were to turn around and convert all of those to strings immediately and write them to a file, then you're probably looking at a speed LOSS of roughly 10 seconds. Of course, this also doesn't take anything else into consideration (the value of bandwidth pipes / network saturation / memory / likelihood of this scenario / scalability across multiple clients / etc).

For displaying the data on-screen, you have about 20-30 seconds of savings on the transfer side, and virtually no time spent on conversion since you're not doing them all at once. The client's not going to notice a split-second of extra time every time they move to a new page of results.

Either way, there is a LOT of extra value in more efficient storage. There will always be some scenarios where it doesn't make sense to compact everything, but that's where being a good programmer comes into the picture and understanding the business case and how it translates into data flows and the value of each resource involved, and how that multiplies with concurrent load.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
Comment Utility
Excellent article!  The only thing I would have included would be a small section on Endianness (Big Endian vs. Little Endian).
0

Introduction

Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the principles and examples of the original article on a 1:1 basis.  As I created the examples for this article, I came across some anomalies in the PHP OOP DateTime implementation.  Here are some of my impressions and some notable gotcha's that I found.


It is possible to create an infinite loop with date/time arithmetic.  Your code will look right, but transitions at the boundaries of daylight savings time will change the values in your DateTime objects.  I hope PHP will fix this.

See: http://php.net/manual/en/datetime.sub.php#114780


When you create a new DateTime object, you can assign both a date/time string and a timezone.  If you create the DateTime object from a Unix timestamp, the timezone cannot be used in the constructor.  You must assign the timezone to the object separately, after the object is created.


The ISO-8601 format for DateTime::format() method is not 100% ISO-8601 compatible.  You can use DateTime::ATOM instead if you need perfect compatibility.


The designator for a Unix timestamp in DateTime::__construct() is the at-sign ("@") prepended to the numeric Unix timestamp.  The at-sign ("@") is also the PHP error-control operator, but it has no error-control meaning in the DateTime constructor.


There is no avoiding arithmetic - DateTime::getOffset() returns its answer in seconds, but functions that use this information may expect minutes or hours.


I found no convenient way to instantiate a DateTime object and get a formatted date/time string in a single line of code.  The marriage of PHP date() and strtotime() was a convenience that is not here any more.  I'll update this article if I find a good solution.


At PHP 7.1+ the DateTime constructor incorporates microseconds when the object is constructed from the current time.  This may increase the risk that two DateTime objects will be unequal.


Now the good news.  Most of what you learned about date formatting with the date() format parameters is still applicable.  You will write a little more code with the OOP notation, but that is common for OOP programming and may help to improve readability.  And none of the common tasks we use in procedural PHP is impeded by the OOP DateTime notation.  A list of the most useful references is included at the end of this Article.


The DATE/TIME Tower of Babel

Human beings can read dates and times in a variety of ways.  We readily understand such things as September 5th, 2010, and we know that it comes before November 11th, 2010,and after May 9th, 2010.  We have shorthand conventions that let us write things like 9/5/2010 or the military correspondence format 5 Sep 2010.  But when we try to process dates and times in a computer program, this variety of formats becomes a jumble of confusion.  In response to the confusion, the International Organization for Standards was moved to publish a standard in 1988.  The standard has been revised and extended somewhat since the original publication.  The only thing that mystifies students of history is why it took so long to promulgate a standard.


Toward a Universal DATETIME Notation

Date formats for computer processing are prescribed by the ISO-8601 standard.  The ISO-8601 standard places all the information in fixed-width data strings with leading zeros where needed.  When you read ISO-8601 standard information you notice immediately that everything lines up in columns.  The larger values are to the left and progressively smaller values are to the right, starting with Year, then Month, then Day, then Hour, etc.  Date/time information formatted according to the standard is very useful because it is both easy to read and easy to understand in comparisons and computations.  For example, the date '2010-09-05' is a valid ISO-8601 string meaning September 5th, 2010.  Imagine how difficult it would be to write programming that works with dates in the text formats, or dates that are formatted like this: 05.09.2010.  Does that mean May 9th, 2010 or September 5th, 2010?  Fortunately the ISO-8601 standard removes the ambiguity.


The ISO-8601 standard removes the ambiguity about the time of day, as well.  All of the hours are represented on a 24-hour clock, so there is no question about what "two o'clock" might mean.  The string 0200 or 02:00:00 refers to 2:00 a.m.  If you're thinking of 2:00 p.m. your ISO-8601 standard will use 14:00:00.


This link gives a good discussion and examples of permissible variations on the ISO-8601 format.

See http://en.wikipedia.org/wiki/ISO_8601


The Value of PHP time() is Always the Same

No matter where in the world you stand, the value of time() is always the same.  The PHP function time() returns the number of seconds since the Unix Epoch.  While local times may differ, time() ticks on second-by-second.  Run this script to see the effect.  Knowing this, we can do arithmetic with seconds, and then return human-readable date and time values that are sensible for different locations around the world.

<?php
                                        /**
                                         * Different Timezones share the same Unix Timestamp
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        // TIMEZONES AROUND THE GLOBE
                                        $locations
                                        = array
                                        ( 'Pacific/Auckland'
                                        , 'Australia/Sydney'
                                        , 'Australia/Perth'
                                        , 'Asia/Tokyo'
                                        , 'Asia/Calcutta'
                                        , 'Asia/Tel_Aviv'
                                        , 'Africa/Cairo'
                                        , 'Europe/Rome'
                                        , 'Europe/London'
                                        , 'Atlantic/Bermuda'
                                        , 'America/Chicago'
                                        , 'America/Anchorage'
                                        , 'Pacific/Honolulu'
                                        , 'UTC'
                                        )
                                        ;
                                        // ITERATE OVER THE TIMEZONES
                                        foreach ($locations as $location)
                                        {
                                            // SET OUR ZONE AND LOCAL TIME
                                            $zoneobj = new DateTimeZone($location);
                                            $dateobj = new DateTime(NULL, $zoneobj);
                                        
                                            // SHOW THE LOCATION AND THE CURRENT DATE / TIME
                                            echo PHP_EOL;
                                            echo str_pad($location, 24, ' ');
                                            echo $dateobj->format(DateTime::RSS);
                                        
                                            // SHOW THE NUMBER OF SECONDS SINCE THE EPOCH, RECOMPUTED IN EACH TIMEZONE
                                            echo ' ';
                                            echo $dateobj->format('U');
                                        }


Handling External Input

Whenever you accept a date/time string from an external data source, what is the first thing you should do?  Turn it (immediately) into an instance of the DateTime object.  The DateTime constructor can turn almost any English language human-readable date/time text into an object for use in DateTime computations and displays. Like the PHP function date(), the DateTime::format() method can turn DateTime information into a formatted date. 

<?php 
                                        /**
                                         * The DateTime constructor may throw an Exception
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $external = 'Yesterday';
                                        try
                                        {
                                            $dateobj = new DateTime($external);
                                        }
                                        catch (Exception $e)
                                        {
                                            // ON FAILURE, SHOW THE EXCEPTION
                                            var_dump($e);
                                        }
                                        echo PHP_EOL . $dateobj->format(Datetime::ATOM);
                                        echo PHP_EOL;

Once you have done that internal date format conversion your programming will handle internal date/time computations easily.


When you are storing date/time values, you may want to store them in the ISO-8601 format strings or in the form of Unix timestamps.  I prefer to use the formatted strings - they are easier to understand when you're debugging.


Handling External Input that is Invalid

The PHP DateTime constructor can turn virtually any human-readable date / time text into a DateTime object - but it won't work on everything.  When it fails to make the conversion, it throws Exception.  You can and should test for this.


<?php
                                        /**
                                         * Invalid date/time strings can be detected when you catch the Exception
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $external = 'Nonsense';
                                        $dateobj  = FALSE;
                                        try
                                        {
                                            $dateobj = new DateTime($external);
                                        }
                                        catch (Exception $e)
                                        {
                                            // ON FAILURE, SHOW THE EXCEPTION
                                            var_dump($e);
                                        }
                                        if ($dateobj)
                                        {
                                            $iso_datetime = $dateobj->format(Datetime::ATOM);
                                            echo "SUCCESS: $external EQUALS ISO-8601 $iso_datetime";
                                        }
                                        else
                                        {
                                            echo "ERROR: I DO NOT UNDERSTAND $external";
                                        }


Handling External Input that is Formatted (contrary to the disambiguation rules)

The PHP DateTime Constructor works much the same way as strtotime(), making some assumptions and obeying certain rules about the format of the date / time input string.  But what if you have dates that are not formatted according to the rules?  One of the common issues arises when we have dates that are in European order d-m-y, but have been written with slashes, implying American order m/d/y.  This may result in incorrect output when the values for m and d  are both in the range from 1 - 12, and will cause an exception when m exceeds 12.  Fortunately PHP has a way around this issue, in the static constructor createFromFormat().  We can tell PHP what format to use as it interprets the date.  This example shows how.


<?php
                                        /**
                                         * Date values separated by slash are assumed to be in American order: m/d/y
                                         * Date values separated by dash are assumed to be in European order: d-m-y
                                         * Exact formats for date/time strings can be injected with createFromFormat()
                                         *
                                         * http://php.net/manual/en/datetime.createfromformat.php
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        // THIS WOULD IMPLY MONTH == 19, OBVIOUSLY INVALID
                                        $external = "19/10/2016 14:48:21";
                                        
                                        // HOWEVER WE CAN INJECT THE FORMATTING WHEN WE DECODE THE DATE
                                        $format = "d/m/Y H:i:s";
                                        $dateobj = DateTime::createFromFormat($format, $external);
                                        
                                        $iso_datetime = $dateobj->format(Datetime::ATOM);
                                        echo "SUCCESS: $external EQUALS ISO-8601 $iso_datetime";


Interesting Forms of External Input

All of these external inputs work correctly with the DateTime constructor and this gives you and your clients powerful ways of talking about dates and computing with dates.

- 3 hours

tomorrow

tomorrow midnight

tomorrow 1:35pm

March 15, 1986

yesterday

yesterday + 1 week

next year

now

now + 627 hours 15 minutes

last Tuesday

third Wednesday

3 minutes, 15 seconds


Producing "Pretty" Dates From DateTime Objects ISO-8601 Dates

When you are ready to present the dates to people and you want them to see nicely formatted dates, you can use the DateTime::format() method to do the reformatting.  Let's say you have this timestamp value: 1,284,593,400 (which equals the ISO-8601 date: '2010-09-15T18:30:00-0500'. )  Maybe you got it out of your data base or computed it in your script.  It's meaningful, but not what you expect when you open the envelope.  "Please join us for cocktails on Unix Timestamp 1,284,593,400."  How can we get something that would be appropriate on an invitation?  Here is how you might do the conversion from a timestamp or ISO-8601 date to the pretty date.

<?php 
                                        /**
                                         * The DateTime::format() can change the rendering of date values and produce pretty dates
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $iso_date = '2010-09-15T18:30:00';
                                        $formats  = 'l, F jS, Y \a\t g:ia';
                                        $dateobj  = new DateTime($iso_date);
                                        echo PHP_EOL . $dateobj->format($formats);

Outputs "Wednesday, September 15th, 2010 at 6:30pm" -- very civilized!


Breaking down the date formatting, we have the following (all documented on PHP.net)...

$pattern
                                        = 'l, '    // LOWERCASE L - text name of the day of the week
                                        . 'F '     // UPPERCASE F - text name of the month
                                        . 'j'      // LOWERCASE J - day of the month
                                        . 'S, '    // UPPERCASE S - ordinal like the letters in 1st, 2nd, etc 
                                        . 'Y '     // UPPERCASE Y - 4-digit year
                                        . '\a\t '  // ESCAPED LETTERS... More to follow
                                        . 'g:'     // LOWERCASE G - hours on a 12-hour clock
                                        . 'i'      // LOWERCASE I - minutes 
                                        . 'a'      // LOWERCASE A - designator of "am" or "pm"
                                        ;


You might envision several patterns that you need in your application.  Most PHP sites and services are written with a central "common.php" file that gets included into all the specialized scripts.  You could prepare the formatting patterns in the common script and refer to them by a variable name, or define the patterns as constants.

define('MILITARY_CORRESPONDENCE', 'j M y');
                                        define('SHORT_8601', 'Y-m-d');
                                        define('COCKTAILS', 'l, F jS, Y \a\t g:ia');


What about the escaped letters?  Like the date() function, the DateTime::format() uses letter patterns as signals to describe the conversion into human-readable character strings, so some letters have special relevance and some do not.  Any character that is not used as a signal in the date pattern string is returned from the function unaltered.  Punctuation is one example - commas and hyphens go right through.  But if we want to get one of the signal letters back, we must tell PHP to ignore the signal and just return the letter.  We do that with the back-slash character, as shown here.  Try running these two lines of code to see how the escape can be useful:

echo PHP_EOL . date('The year is: Y');
                                        echo PHP_EOL . date('\T\h\e \y\e\a\r\ \i\s\: Y');


Setting Your Own Clock Values

Since the values contained in the DateTime object are usable in many different time zones, you want to have control over the way PHP interprets the time zone.  You control this time with the DateTimeZone object.  You can set the DateTimeZone in the DateTime constructor, or you can inject a new DateTimeZone into a DateTime object via the setTimeZone() method.  Here is an example that I use, because my server is located in the midwest at ChiHost.com.


<?php
                                        /**
                                         * DateTime objects are usually aware of time zones via the DateTimeZone object
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $string  = 'Now';
                                        $zoneobj = new DateTimeZone("America/Chicago");
                                        $formats = 'l, F jS, Y \a\t g:ia (e)';
                                        $dateobj = new DateTime($string, $zoneobj);
                                        echo PHP_EOL . $dateobj->format($formats);
                                        
                                        // WHAT TIMEZONE SHOULD I USE?
                                        $tz_ids = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, 'US');
                                        foreach($tz_ids as $zone)
                                        {
                                            echo PHP_EOL . $zone;
                                        }


Special Meanings for NOW and TODAY

We know how to convert external date/time strings into DateTime objects, and we know how to return them to human-preferred formats with DateTime::format().  Now we can return to some of the special meanings of date/time strings.  NOW and TODAY are particularly useful.

<?php 
                                        /**
                                         * NOW and TODAY have special meanings in the DateTime object; NOW includes time of day
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $date = new DateTime('Now');
                                        echo PHP_EOL . $date->format(DateTime::RSS);
                                        
                                        $date = new DateTime('Today');
                                        echo PHP_EOL . $date->format(DateTime::RSS);
                                        
                                        $date = new DateTime('Now', new DateTimeZone('UTC'));
                                        echo PHP_EOL . $date->format(DateTime::RSS);
                                        
                                        $date = new DateTime('Today', new DateTimeZone('UTC'));
                                        echo PHP_EOL . $date->format(DateTime::RSS);

The principal difference between NOW and TODAY is the time of day.  TODAY is always today's local date at midnight, with hour, minute and second equal to zero.  NOW is today's date including the current time of day.  So in our September example, NOW and TODAY have UNIX timestamp values equal to 1,284,593,400 and 1,284,526,800 respectively.  The difference is 66,600.  This is the number of seconds from midnight to 6:30pm (18 hours plus 30 minutes).  


This script shows that the Unix timestamp is consistent, no matter what timezone you have specified.

<?php 
                                        /**
                                         * The Unix Timestamp values for NOW and TODAY are the same, no matter what timezone
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $dateobj = new DateTime('Now');
                                        echo PHP_EOL . $dateobj->format('U');
                                        
                                        $dateobj = new DateTime('Today');
                                        echo PHP_EOL . $dateobj->format('U');
                                        
                                        $dateobj = new DateTime('Now', new DateTimeZone('UTC'));
                                        echo PHP_EOL . $dateobj->format('U');
                                        
                                        $dateobj = new DateTime('Today', new DateTimeZone('UTC'));
                                        echo PHP_EOL . $dateobj->format('U');


Computing the Difference Between DateTime Objects

This script shows how to compute the difference between two DateTime objects, using the diff() method.


<?php 
                                        /**
                                         * Computing the difference between NOW and TODAY in different timezones
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        // TESTING UTC
                                        $zoneobj    = new DateTimeZone('UTC');
                                        $date_now   = new DateTime('Now',   $zoneobj);
                                        $date_today = new DateTime('Today', $zoneobj);
                                        $date_diff  = $date_now->diff($date_today);
                                        $print_diff = $date_diff->format('%H:%i:%S');
                                        
                                        echo PHP_EOL . $zoneobj->getName();
                                        echo PHP_EOL . $print_diff;
                                        echo PHP_EOL;
                                        
                                        // TESTING ANOTHER ZONE
                                        $zoneobj    = new DateTimeZone('America/New_York');
                                        $date_now   = new DateTime('Now',   $zoneobj);
                                        $date_today = new DateTime('Today', $zoneobj);
                                        $date_diff  = $date_now->diff($date_today);
                                        $print_diff = $date_diff->format('%H:%i:%S');
                                        
                                        echo PHP_EOL . $zoneobj->getName();
                                        echo PHP_EOL . $print_diff;
                                        echo PHP_EOL;
                                        
                                        // USING METHOD CHAINING FOR TIGHTER CODE
                                        $print_diff  = $date_now->diff($date_today)->format('%H:%i:%S');
                                        
                                        echo PHP_EOL . $zoneobj->getName();
                                        echo PHP_EOL . $print_diff;
                                        echo PHP_EOL;


As you can see, it is important to be consistent about your timezone.  You can deal with this phenomenon in one of two ways.  You can set your timezone to UTC.  Or you can set your timezone to a reasonable setting for the location of your server.  I prefer the latter.  See http://php.net/manual/en/timezones.php and http://php.net/manual/en/timezones.others.php for more.


Time Without Date

Let's say we want to know the elapsed time between two events, and we want to express it in notation like HH:MM:SS. DateTime::diff() and DateTime::format() can help with this.

<?php 
                                        /**
                                         * Computing the difference between two times
                                         */
                                        error_reporting(E_ALL);
                                        echo '<pre>';
                                        
                                        $alpha = "2:30:47pm";
                                        $omega = "3:43:16pm";
                                        $date_alpha = new DateTime($alpha);
                                        $date_omega = new DateTime($omega);
                                        $elapsed    = $date_omega->format('U') - $date_alpha->format('U');
                                        $date_diff  = $date_omega->diff($date_alpha);;
                                        $print_diff = $date_diff->format('%H:%i:%S');
                                        
                                        echo PHP_EOL . "TWIXT $alpha AND $omega THERE ARE " . number_format($elapsed) . " SECONDS";
                                        echo PHP_EOL . "RIGHT ELAPSED TIME IS $print_diff";


Leap Year and Daylight Savings Time

These are amazingly easy in PHP.  But beware of a bug in DateTime::add(), illustrated in this code.


3
WordPress Tutorial 1: Installation & Setup
WordPress Tutorial 1: Installation & Setup

WordPress is a very popular option for running your web site and can be used to get your content online quickly for the world to see. This guide will walk you through installing the WordPress server software and the initial setup process.

With Wordpress gaining more and more popularity not only as blogging platform but as a shopping or CMS solution, it's worth to know which plugins are the first ones to grab and integrate with your website. We will briefly go over the most useful plugins such as TablePress or Google Analytics.
22
 
LVL 70

Expert Comment

by:Jason C. Levine
Comment Utility
Jetpack contact form does not allow you to use reCaptcha anti-spam protection out of the box

No, but the better form plugins use a honeypot or timer-based approach which is a vastly better UX than any captcha. Captchas suck for the users and there's a growing body of bots that blow right through recaptcha like it isn't there.

I used Jetpack as an example because for one plugin you get a ton of functionality that could replace a few plugins in your list.  Perhaps a better example would have Formidable (free) or Ninja Forms.

Jason, I hope I addressed at least some of your concerns!

You tried, and I appreciate it and the article isn't terrible at all...it's well-written and engaging and you clearly have a passion for WordPress.  Mostly I'm skeptical of "top X you should Y-ing because Z" articles because they have to be general and unspecific almost by definition.  Each of the areas you touch on (analytics, layout/content, utility, e-commerce, caching, backup and migration) is a universe unto itself and could be the subject of a compare-and-contrast piece that really educates a reader on why you recommend a particular plugin over the competition.

What this current piece doesn't do all that well is account for different use cases. Recommending WooCommerce is a no-brainer for large applications but if you are only selling 3-5 things, it's massive overkill and would send a neophyte down a rabbit hole that they may not find their way out of.  You also don't mention any of the drawbacks or criticisms leveled at particular plugins.  TablePress is a fantastic plugin but you don't mention the absolutely massive overhead it adds to sites because it loads its own js and css to handle what is a relatively simple use case for most users.  While SuperCache creates static pages and appropriately handles rewrites, it doesn't easily allow for minification or async/deferred loading which becomes critical when trying to eliminate render blocking.  It's also under-documented like crazy.  

When recommending anything, I think we have a responsibility as experts to make sure our recommendations are well-thought out and defensible.  This is especially important with something like WordPress which is picked up and used by people with very little knowledge of programming, security, application design, and the mechanics behind serving web pages and turn to plugins to cover up that knowledge gap.

*I* know why you are using the above because I've used them myself and, like you, I understand their strengths and limitations.  I'm not 100% sure someone who is not at our level would be able to feel confident in these choices.  If you feel like pushing yourself a little further on this, you could have a truly great article on your hands, or a series of them :)
0
 
LVL 11

Author Comment

by:Radek Baranowski
Comment Utility
I know where you are coming from, I think, and agree it has a bit one-sided approach. What I am trying to address however, is "how to set up wordpress quickly and get it to do things I want" which is a question I often try to answer myself (not only about Wordpress) and which is, I believe, the purpose of Top 10... kind of articles. These are for people who want to build things on their own, instead of turning to experienced (and pricey ;) professionals who have the matter thought through in and out. I completely agree with you that every single functionality I listed might be a separate article. Might as well evolve into something like that, should my (or yours) time allow.
0
In this article, we will look at our content management system as a whole, to get an idea of how we will start to manage these content items.
2
 

Expert Comment

by:dwarak besant
Comment Utility
Would you have any recommendations on how to make this add/edit blog entries instead of pages? I'm trying to just add blog functionality to a single page on a website without converting the entire site into a CMS.
0
Introduction
This question got me thinking...

Why shouldn't we use Globals?
This is a simple question without a simple answer.  How do you explain these concepts to a programmer who is coming from a background in procedural programming? 

There is a lot of deep background thinking that you need to understand in order to know why globals are considered to be a poor design choice today.  Singletons are just as bad as globals in many ways.  Often procedural programmers have looked at the global keyword as an expedient solution - a global declaration made inside your functions provided a simple reference to an external database connection.  Tightly-coupled code sets were the norm in programming just a few years ago, and the global keyword implemented tight coupling in a way that irrevocably bound certain objects into the fabric of the application.   If you're working alone on a standalone project, you can sometimes get away with using global objects, but if you want to come into the modern world of application design, and especially if you want to collaborate on anything important, you need to understand why global elements are considered harmful, and what the alternatives offer.

Global Variables Break Encapsulation
2
 
LVL 110

Author Comment

by:Ray Paseur
Comment Utility
I may have to sign off on this because I'm not following the part about passing an object three levels deep.  It looks like the $db variable is injected into the constructor of the Contact class and used in its methods.  That seems fine to me.  The granularity level for testing is the Contact class, since the $db is the same throughout all the methods.

A "config" class sounds like a singleton to me - similar to a global, but I would have to read the code that sets it up and uses it.  Maybe a consulting agreement would make sense here?
0
 
LVL 32

Expert Comment

by:DrDamnit
Comment Utility
No, I'm satisfied with getConfig(). I was just trying to understand if there was a better way. But your feedback is appreciated.
0
This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
1
There is a huge demand for CodeIgniter among the PHP web developers due to its dynamic features and benefits these days. It is one of most popular and agile open source PHP framework for creating robust web applications in PHP web development field. 

​Any web applications developed based on CodeIgniter framework perform effectively and rapidly. It helps the programmers to build dynamic and custom web applications with an advanced technology platform by offering valuable set of aspects to write code from scratch.

Let us look out some of benefits and features of CodeIgniter.



codeigniter-features.png

Key features

Model-View-Controller Based System

CodeIgniter make use of the MVC system to find complex models and helps you to create application easily by using controllers and views. It assists the developer to build core libraries for the system and enables you to integrate your own existing scripts with database.

Error Handling

It offers simple user-friendly interfaces that help you to detect error functions throughout the application globally. In this way of approach, it provides instructions to error logging class that allows debugging messages to be saved as text files. It displays all PHP errors in your web application without missing inadequacy.

Form Validation

This feature helps you to write the code in a single line by using effective validation framework system. It generates codes without any errors and ensures …
0
Introduction
Here is an interesting hierarchy of learning.  Let's identify four groups.
  • Neophyte
  • Inquirer
  • Competent
  • Expert
Consider, if you will, the different nature of learning in each of these groups. We could take almost any subject, but let's use German language, and compare it to software development. Natural languages are close enough to programming languages for the analogy to stand.

Neophyte
When you enter German 101, you start with the most basic rules of grammar and pronunciation. You learn that plurals end in "en." Your learning is nearly 100% rules-guided, and built up with rote practice. You memorize the alphabet. You need to be told what to do and say. 

In software development, when you're a novice, you're just learning the rules of syntax and the basic structure of program flow. An introductory tutorial is helpful. You may not understand the expressive power of the language yet. You begin reading the language reference.

Questions at this level need straightforward, prescriptive answers.

Inquirer
By the time you're far enough along to be called an Inquirer, you're able to read and understand common German phrases and you're picking up a few idioms. You can ask simple questions in German. Your learning is still …
10
 
LVL 2

Expert Comment

by:Christopher Rourke
Comment Utility
Excellent article Ray.
0

PHP

118K

Solutions

32K

Contributors

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.