Home > Tags > PHP
Page 2

PHP Error Checking

“Just when you think you’ve made something foolproof, God makes a better brand of fool.”

This maxim of manufacturing also applies to software development, especially on a highly accessible technology like web applications. As much as programmers attempt to anticipate every possible action or combination of actions that a user can take when encountering a web application, no one can foresee them all. When the user takes an unanticipated course of action and “breaks” the application, the software needs to catch them before they fall.

Die() Function

One of the techniques that early PHP programmers used to catch errors was the “die” function. When the program would “die”, this function stops the script and displays an error message.

<?php if(!file_exists("hello_world.txt")){ die("File not found"); } else { $file=fopen("hello_world.txt","r"); echo(“Hello World file found”); } ?>

Without the die function, the program would return a specific error message, but not one that users could readily understand:

Warning: fopen(hello_world.txt) [function.fopen]: failed to open stream:No such file or directory in C:\wwwroot\developer_drive\file_opener.php on line 2

Exception Handling

As with other C-based languages (C#, Java, etc.), PHP 5 has a technique for catching exceptions. The keywords “try”, “throw” and “catch” find exceptions and enable better error handling.

Try: Any function that employs the use of an exception to handle errors should be in a “try” block. If the exception is not triggered, the rest of the script will continue executing as written. If the exception is triggered, the exception is said to be “thrown”. Throw: The “throw” block triggers an exception. For each “throw” block, there must be one or more “catch” blocks. Catch: The “catch” block retrieves an exception and instantiates an object that holds the exception data.

<?php try { $error = 'Throw this error'; throw new Exception($error); // Code following an exception is not executed. echo 'This line is ignored'; } catch (Exception $e) { echo 'Exception caught: ', $e->getMessage(), "\n"; } // Continue execution echo 'This line is executed.'; ?>

The Exception class that the catch block creates contains several methods: getMessage()- displays message of exception getFile() – finds error source filename getLine() – finds error source line getCode() – displays code of exception getTrace() – creates an array of the backtrace() getTraceAsString() – formats string of trace array

Trigger Error

In most cases, programmers attempt to avoid errors. In some instances, however, developers may want to test their error handling capabilities.  The “trigger_error” function throws an error message when the program encounters an error:

<?php $text= “Hello”; if ($text !== “Goodbye”){ trigger_error(“Say Goodbye. Error Triggered.”); } ?>

Error Messages

Not only do applications have to catch errors before the user encounters them, they must present the reason for the error in a way that the user will understand why it “broke”.

Error messages should always be easy to read for the users; these message allows the user to remain confident that the application can be fixed.  The error messages also help developers chase down potential problems.

Remember, confused users can become angry users, and a user’s anger can lead to a developer’s impending unemployment.

...
more →
Alex Vernacchia says: You would use try/catch when you throw an exception as an error and you want to don't want to break your application. For...

Common PHP File Upload Restrictions

From family photos to business documents, file uploads power many of the major web applications. A typical HTML form that allows the user to upload a file may look like this:

<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> File Name: <input type="file" name="file" id="file" />  <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>

In this case, the only field displayed on the form is the “file” field.  This field allows the user to browse their hard drive for the file they wish to upload. The enctype “multipart/form-data” specifies that the field should be filled with binary data, as from a file, rather than typed input from the user. PHP applications allow users to upload files through its $_FILES object. Developers can use the $_FILES object to check on the properties of an uploaded file:

$_FILES["file"]["name"] – the name of the uploaded file $_FILES["file"]["type"] – the type of the uploaded file $_FILES["file"]["size"] – the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] – the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] – the error code resulting from the file upload

For files that upload successfully, the value of $_FILES["file"]["error"] is 0. However, some developers may want to place restrictions on the files users can upload.

File Type

Developers can use the $_FILES["file"]["type"] property to limit the types of files uploaded to those in use for specific applications. For instance, businesses may wish to restrict file types to documents, spreadsheets and presentations, but not allow users to post photos, videos or executable programs.

<?php if (($_FILES["file"]["type"] != "application/msword") || ($_FILES["file"]["type"] != "application/vnd.ms-excel ") || ($_FILES["file"]["type"] != "application/vnd.ms-powerpoint"))   {   echo "Invalid file type";   } ?>

File Size

Network administrators may also choose to limit the size of files users can upload to a server in order to reduce bandwidth usage. Developers can set limits on the size of a file a user can upload.

<?php if ($_FILES["file"]["size"] < 25000)) // Max File Size: 25KB   {   echo "File size exceeds maximum.";   } ?>

Upload Timed Out

Another method that administrators use to conserve bandwidth is to limit the time that a page can use to upload a file. Most PHP applications time out after 30 seconds, but the developer can set the time to as little or as much as needed by changing either the php.ini file on the server or setting the time in the application itself. PHP.INI File max_input_time 300

PHP Script

<?php // code to upload file to temporary directory ini_set('max_input_time', 300); // code to move file to new directory ?>...
more →
Eric Wilson says: I would say understanding how to securely store and access an uploaded file is more important than how you upload it. For...

5 PHP Security Measures

For many years, PHP has been a stable, inexpensive platform on which to operate web-based applications. Like most web-based platforms, PHP is vulnerable to external attacks. Developers, database architects and system administrators should take precautions before deploying PHP applications to a live server. Most of these techniques can be accomplished with a few lines of code or a slight adjustment to the application settings.

#5: Manage Setup Scripts

If the developer has installed a set of PHP scripts from a third-party application, the scripts the application uses to install the working components can also provide an access point to unscrupulous users. Most providers of third-party packages recommend removing the directory containing the setup scripts shortly after installation. For developers who wish to retain the setup scripts, they can create an .htaccess file that controls access to the administrative directories.

AuthType Basic AuthName “Administrators Only” AuthUserFile /usr/local/apache/passwd/passwords Require valid-user

Any unauthorized user who attempts to bring up a protected directory will see a prompt for a username and password. The password must match the assigned password specified in the “passwords” file.

#4: Include Files

In many instances, developers may use an individual file in several portions of an application. These scripts will contain an “include” directive that incorporates the code of the individual file into that of the originating page. When the “include” file contains sensitive information, including usernames, passwords or database access keys, the file should have a “.php” extension, rather than the typical “.inc” extension. The “.php” extension insures that the PHP engine will process the file and prevent any unauthorized views.

#3: MD5 vs. SHA

In situations where end users create their own usernames and passwords, site administrators will often include functionality to encrypt the password data before the form submits the form field entry to the database field. In past years, developers have used the md5 (Message Digest algorithm) function to encrypt passwords into a 128-bit string. Today, many developers use the SHA-1 (Secure Hash Algorithm) function to create a 160-bit string.

#2 Automatic Global Variables

The php.ini file contains a setting called “register_globals”. When the register_globals setting is on, the PHP server will create automatic global variables for many of the server’s variables and query strings. When installing third-party packages, such as content management software like Joomla and Drupal, the installation scripts will direct the user to set register_globals to “off”. Changing the setting to “off” insures that unauthorized users cannot access data by guessing the name of the variable that validates passwords.

#1 Initialize Variables and Values

Many developers have fallen into the trap of instantiating variables without defining their values, either due to time constraints, distractions, or lack of effort. Variables that validate the authentication process should have values instantiated before the login procedure begins. This simple step can prevent users from bypassing the verification routine or accessing areas of the site to which their privileges do not entitle them.

These steps can block users from starting a new session on an application, but what about protecting data during a session?  Next week’s lesson will examine PHP session security.

...
more →
Yggdrasil says: Yeah, I do know the difference but couldn't correct my faulty text without starting fresh. Chrome on iOS has some issues with the...

Converting a Web Template into a WordPress Theme

If you are not into all the hype surrounding WordPress, you probably have likely heard about its ease of use especially for end-users. The platform is also easy to manage and delivers an almost limitless number of widgets to help add functionality.

Many users are usually not interested in the development process and only want an end product that is painless and flexible enough to allow additional features as the website grows. WordPress gives you that edge. However, before you can port your existing website or template into WordPress, you need to have a basic understanding of both HTML and CSS. WordPress uses PHP function calls to retrieve or call data elements. To make editing easier, you also need some fundamental knowledge of how PHP works.

Create the Basic Files and Folders

First, you need to create a new folder and give it the name of your theme. Inside this folder, you will need to create two files, “Index.php” and “Style.css”.

From your original CSS file, copy all its contents into the new “Style.css”. To help WordPress identify your new theme, add the code below at the very top inside your “Style.css” file:

/* Theme Name: Replace with your Theme’s name. Theme URI: The URI of your Theme goes here Description: Describe your theme under this section. Version: 1.0 Author: DavGit Author URI: www.e-labz.com */

Slicing the HTML

Since WordPress uses PHP function calls to call files from within your template folder, we will need to slice the layout of the website into 4 different sections.  These sections include the header, content, sidebar and footer.  These 4 different sections are actually 4 separate files that will be called using PHP.

Create 4 new files, “Index.php”, “Header.php”, “Sidebar.php” and “Footer.php” within your theme directory.  For the header.php file, copy and paste the PHP code below:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> <title> <?php wp_title(''); ?> <?php if ( !(is_404()) && (is_single()) or (is_page()) or (is_archive()) ) { ?> at <?php } ?> <?php bloginfo('name'); ?> </title> <meta name="generator" content="WordPress <?php bloginfo('version'); ?>" /> <!-- leave this for stats -->...
more →
S@kiv says: Hi.. This blog is good and easy to understand. I also want to know how can we chop the each sections. For i.e. in header section...

Create your own CRUD app with PHP & MySQL (Part 2)

Picking up from where we left off, we need to start by creating some HTML to display the data we’ve stored in the $results variable. You can always modify this to suite your project. I’ll be using a table structure.

<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <link href="styles/theme.css" rel="stylesheet"/> <title>PHP & MySQL</title>\ </head> <body> <div id="wrapper"> <table> <thead> <th>Title</th> <th>Release Date</th> <th>Publisher</th> <th>System</th> <th>Rating</th> <th>Number Of Players</th> <th>Tools</th> </thead> <tbody> <?php foreach($results as $entry): ?> <tr> <td><?php echo $entry->title; ?></td> <td><?php echo $entry->release_date; ?></td> <td><?php echo $entry->publisher; ?></td> <td><?php...
more →
Marty Lavender says: Your code had a lot of errors. All of which I have been able to fix on my own. I cannot however figure out how to resolve this...

Up and Running With Custom Post Types Part 2

In part one of our post Up and Running With Custom Post Types, we covered the concept behind WordPress’s Custom Post Type feature, and how to get started by creating your own custom post type. We also covered ways to keep it modular by utilizing a separate PHP file, allowing you to port the post type from theme to theme.

In this post, we’ll cover creating Taxonomies for your custom post types, creating custom fields and meta boxes, saving your data and using it in your WordPress themes.

Let’s get rollin’!

Creating Taxonomies (To Categorize By)

The next step is to set up some taxonomies to categorize your custom post type by. These are effectively the same thing as Categories for posts, except we can make them whatever we want with just a few lines of code.

For this, we are using the WordPress function register_taxonomy();. As you can see below and on the Codex, the arguments it takes is the taxonomy, followed by the object type, and finally the $args. For our example here, we create two taxonomies – Skills and Club Level. We assign the taxonomies to the “athlete” post type, and then give it arguments including labels and rewrite privileges. Let’s take a look at the code.

register_taxonomy("Sport", array("athlete"), array("hierarchical" => true, "label" => "Sport", "singular_label" => "Sport", "rewrite" => true)); register_taxonomy("Club Level", array("athlete"), array("hierarchical" => true, "label" => "Club Level", "singular_label" => "Club Level", "rewrite" => true));

The registered taxonomies come through looking like this.

You can click on the post types and you will be presented with a screen that looks just like the Categories page, and the ability to add your custom taxonomies.

So we’re done, right?

Well, effectively, you do have a custom post type that works and functions. Although currently, it’s not any different than a regular post. Let’s dig in to creating custom fields in your posts that will allow you to get unique information and display them back in your theme.

Creating Custom Fields

To start off the true magic of custom post types, you have to first initialize a function to add the meta boxes. We’ll call ours admin_init() and call it like this:

add_action("admin_init", "admin_init"); function admin_init(){ add_meta_box("personal_info", "Personal Info", "personal_info", "athlete", "normal", "low"); }

The first part of that code initalizes the function admin_init(). Obviously the second part of that code is the actual function. Basically it’s telling your theme to create a new meta box called Personal Info, put it in the post type of “athlete” and give it a low priority (placement in the post type).

Cool! We’re done, right?

Nope. Close though. Let’s add a few custom fields to populate. This will dabble more in HTML than PHP.

Creating Fields In Your Meta Box

Now this is where the fun comes in. We’re going to create a personal info meta box (we’ll, we already created it above – now we’re going to fill it out) that will ask for a persons first name, last name, gender, email, phone number and birthday.

To do this, we create a function called personal_info(). This is the same function we called in our admin_init() function. Light bulbs going on now? The lines are starting to connect.

Within the function, we first set some variables. We declare variables for $custom, and then using that variable, we create variables for all of our fields. After that, we close out the php, and render the fields with some good ol’ HTML. I use tables just for ease of use and the ability to quickly and easily port this to other post types, but feel free to use div’s or whatever your personal preference is.

function personal_info() { global $post; $custom = get_post_custom($post->ID); $first_name = $custom["first_name"][0]; $last_name = $custom["last_name"][0]; $gender = $custom["gender"][0]; $email = $custom["email"][0]; $phone = $custom["phone"][0]; $birthday = $custom["birthday"][0];...
more →
Herdhistory says: Great tutorial! I'm very new to this! I'm curious as to how to get this to work in a way that I can display my cpt on a .php...

Plugin Development for WordPress

The WordPress platform allows you to modify, customize and enhance your existing website easily. You don’t need to change the core program but rather you can create or modify existing plugins to add the extra functionality that you need. This flexibility in customizing your WordPress installation is provided by the WordPress Plugin API.

There are already hundreds of WordPress Plugins on various WordPress Plugin repositories on the Web where you can download and install. If you cannot find a plugin of your choice, this article will introduce the basics of developing your own plugin for WordPress.

Know the Environment

The first thing you want to do is get familiar with the WordPress environment. This includes how files and folders are organized and arranged and how they are referenced from the WordPress interface.  Since PHP is the language used for Plugin development, having PHP programming experience is a prerequisite. Plugins in WordPress are located inside the folder below:

wp-content/plugins

Create a folder for your plugin. We shall name it “Author”. This is where your plugin PHP and JavaScript code will reside as well as the CSS and images that renders the code to make it user-friendly.

Plugin Header Code

Create a PHP file inside the “Author” folder and name it “author.php”. Add the following code to the file:

<?php /* Plugin Name: Author Plugin URI: http://www.davgit.com Version: 1.0 Description: A Plugin that displays author info for each post. Author: David Gitonga Author UI: http://www.davgit.com */

This is standard plugin information header that must be present if WordPress is to recognize the plugin. This plugin info will be displayed when you visit the “Installed Plugins” page.

Adding Functionality

Functions are hard-coded into the plugin files using PHP. In our case, we are going to define one function that calls a section holding the author info. We will also add HTML and WordPress template tags that will be used to build the author info section.

Start by defining the function below:

function author_info() { ?>

Add the HTML needed to build the page as shown below:

<div class = “author_info”> <?php if (function_exists (‘get_avatar’)) { echo get_avatar(get_author_email(), ‘70’); } ?> <?php author_meta (‘description’); ?> </div> <?php

Note the template tags used tell you their functionality. For example, the “get_author_email” tag gets the author email from his profile page.

Add the CSS styles that control the HTML page appearance by adding the code below:

<?php function stylesheet() { echo" <style> .avatar { float:left;background-color: #9A9B9B;padding: 4px;margin: 0 4px 0 0;display: inline; } .author_info { color: #666;background: #DDDDDD;padding: 8px;margin:0 0 6px 0; } </style> "; }

CSS styles that control the HTML page appearance can also be added by creating a separate file called “styles.css” and then adding the above code to it.

Load the function that will be executed when the plugin loads below:

function display_author_info() { if (is_single()) return author_info().stylesheet(); }

Create a file “single.php” and add the code below to it:

<?php...
more →
Guest says: dfgsgsde