William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Tag Archives: PHP

Comparison of MySQL API options for PHP

Comparison of MySQL API options for PHP

The comparison table is from php.net, put here for easy retrieving:

  PHP’s mysqli Extension PDO (Using PDO MySQL Driver and MySQL Native Driver) PHP’s MySQL Extension
PHP version introduced 5.0 5.0 Prior to 3.0
Included with PHP 5.x yes yes Yes
MySQL development status Active development Active development as of PHP 5.3 Maintenance only
Recommended by MySQL for new projects Yes – preferred option Yes No
API supports Charsets Yes Yes No
API supports server-side Prepared Statements Yes Yes No
API supports client-side Prepared Statements No Yes No
API supports Stored Procedures Yes Yes No
API supports Multiple Statements Yes Most No
Supports all MySQL 4.1+ functionality Yes Most No

Summary: consider to use mysqli Extension first, then PDO, then MySQL native Extension.

Advertisements

php MySQLi: MySQL Improved Extension

There are three main API options when considering connecting to a MySQL database server:

  1. PHP’s MySQL Extension
  2. PHP’s mysqli Extension
  3. PHP Data Objects (PDO)

Each has its own advantages and disadvantages. By default we use ‘PHP MySQL extension’. Here focus on the second – MySQLi extension:
The mysqli extension is built using the PHP extension framework, its source code is located in the directory ext/mysqli.

According to wiki, MySQLi is an improved version of the older PHP MySQL driver, offering various benefits.
The MySQLi extension provides various benefits with respect to its predecessor, the most prominent of which are:

  • An object-oriented interface
  • Support for prepared statements
  • Support for multiple statements
  • Support for transactions
  • Enhanced debugging support
  • Embedded server support

The following is a quick example from php.net/mysqli‘s document page:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
      . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
    !$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test ORDER BY id ASC"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

var_dump($res->fetch_all());
?>

PHP: Project logs setting other than webserver’s

PHP: Project logs setting other than webserver’s

It is important to configure PHP’s error reporting settings depending on which phase of development. Generally, it is a good idea to see all warnings and errors in the web browser during the initial phase; and later, once the site has launched, send error messages to a log file so that visitors do not see them.

1. Error Reporting for Development

During development, you want to display all errors and warnings to the browser.

// Report all PHP errors
ini_set('error_reporting', E_ALL);
// Set the display_errors directive to On
ini_set('display_errors', 1);

2. Error Reporting for Production

In production, you may want to lower the error reporting level and not display errors to the browser.

// Report simple running errors
ini_set('error_reporting', E_ALL ^ E_NOTICE);
// Set the display_errors directive to Off
ini_set('display_errors', 0);
// Log errors to the web server's error log
ini_set('log_errors', 1); 
ini_set('error_log', LOGDIR.'/error_log'); 

3. Logging errors

You can use the PHP function error_log() to send errors to your own log file or an e-mail address:

// Destinations
define("ADMIN_EMAIL", "nobody@site.com");
define("LOG_FILE", "/home/log/errors.log");
// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");
/* Examples */
// Send an e-mail to the administrator
error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
error_log("Error", DEST_LOGFILE, LOG_FILE);

PHP CMS Systems for Church Website

While I am looking for wordpress-based website CMS, I found a useful link:

The 7 Best CMS Systems for Your Church Website

I have my own PHP Church CMS system, and found wordpress has much resources on themes and various feature plugins. This kind of resource is a good help for my application with 3th-party reference. The following are the contents from Jesse Orndorff:

As a web designer, developer, or church staff member, you have to update your church website. Usually it is a small change, updating an event, posting a new sermon, or writing a blog post. The best and simplest way to update your site is using a content management system. These systems provide an easy user interface that makes your website easy to update, come with add on components that add in additional functionality, and allow you to easily change website designs. Today I wanted to share the 7 best CMS systems you can use for your church website, enjoy!

1. LightCMS


This is by far my favorite platform to design and develop for! When designing a church website, I first suggest them to use the Light system. Developed with the church in mind, the system easily allows your staff to update your website, with very little (or no) HTML knowledge. It allows for ANY element to be drag and drop ready, so you can move anything to anywhere on the page. Also, simple donations, email forms, and calendar features are included. The software is hosted, so there is a monthly fee, depending on the amount of pages you have, but a great system!

If your a designer/developer, you will love the way the system works. Design two pages, one home, one interior, code them, drop in LightCMS tags to define what is an edible region and you’re set!

2. WordPress


If you’re looking for a great content management system, easy to use, and are on a budget, nothing can beat WordPress for your church’s website. I have received such an overwhelming amount of requests for WordPress sites in the last year that I am launching a WordPress focused design company!

WordPress offers a lot in terms of features, with a large community of developers offering free or low cost plugins, a huge template market, and WordPress is free! All you really need is a web host and you can be up and running. For churches on a budget, this is the way to go.

Resources:
Official WordPress Site:
WordPress.org
Paid Themes:
ThemeForest WP Themes
Woo Themes
Free Themes:
Free WordPress Templates

3. Pagelime


Pagelime is a unique offering, focusing on designers, this simple CMS allows you host your own website, then update it using their hosted CMS. I have used this on a few client sites and I was very impressed. Simply plug-in their code into any area of a site you want to make editable and you’re set. They offer a free account for up-to 3 sites.

4. Halogy


This one is probably unknown to a lot of users, but I stumbled across this CMS a few months ago and was blown away with how simple this CMS is to use. This is one of the few systems that allows you to buy the source code, host it on your server, and develop on top of it. Created using PHP, this system is extremely fixable.

Features include the ability to add templates, add a shopping cart, and edit content in a simple way! Check them out.

5. Expression Engine


One of most complete and advanced CMS systems on the market today. Some of the biggest companies run their sites using this system and the features are outstanding! A large development community and support will be able to help you get started.

A few downsides include a larger start-up cost and because the system is complex, the learning curve is steep.

6. Ekklesia 360


One of the only two CMS on this list that was built specifically for churches. I have not used the system, but I have heard from a few companies that swear by it for church websites. Church specific modules, sermon manager, and member system all make this system very unique.

7. SquareSpace


SquareSpace has come a long way and is one of the best CMS systems available. For only $12 a month, you will get a hosted website, that you can hand to anyone to update. Easy to update, templates, and blogging are all a few features that this CMS includes.

PHP: header processing flow

PHP: header processing flow

When access a security site, normally the following factors need to be considered:

  • session start?
  • setup error_report mode
  • user login or not?
  • initial steps:load and instantiate modules.

A typical steps are like this:

<?php
session_start();
error_reporting(E_ALL & ~E_NOTICE);
defined('ROOT') or define('ROOT', getcwd());

if(empty($_SESSION['username'])) {
//use Heredoc:
$js_script = <<<EOT
<script>
  if(window.opener) {
    window.opener.location.href='/login.php';
  }
  else {
    window.parent.location.href='/login.php';
  }
</script>
EOT;
  echo $js_script;
  exit;
}
//normal flow...
?>

For the error_report() mode, if not set, PHP configuration file will take effect. in /etc/php.ini, the description is:

; Common Values:
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices and coding standards warnings.)
;   E_ALL & ~E_NOTICE | E_STRICT  (Show all errors, except for notices)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
;   E_ALL | E_STRICT  (Show all errors, warnings and notices including coding standards.)
; Default Value: E_ALL & ~E_NOTICE
; Development Value: E_ALL | E_STRICT
; Production Value: E_ALL & ~E_DEPRECATED

; Note: The php.ini-development file has this setting as E_ALL | E_STRICT. This
; means it pretty much reports everything which is exactly what you want during
; development and early testing.
;   E_ALL | E_STRICT  (Show all errors, warnings and notices including coding standards.)

PHP: a lightweight function for output intermediate results

PHP: a lightweight function for output intermediate results.

In PHP, Except you use xdebug extension, the Intermediate results can be written in various ways. Here I list an effective, simply, convenient way which I used to make work easier. The purpose:

  1. For array and hash, using print_r() or var_dump() to output.
  2. For scalar variables, just simply use echo.
  3. Have the switch flag to open and close the output conveniently.

Here it is:

function __p($vars, $debug=true) {
 if (!$debug) return;
 if (is_array($vars) || is_object($vars)) {
  echo "<pre>";
  print_r($vars);
  echo "</pre>";
 } else
  echo $vars . "<br>\n";
}

The default switch flag, ‘$debug’ is set to ‘true’ by default, so it can be used to output whatever you want to output:

// 1. for variable:
$sql = 'select ...'.mysql_real_escape_string($str);
__p($sql);

//2. for function:
function foo($params) {...}
__p(foo($params);

And later, if test ok, don’t need the output, just change the default switcher ‘$debug’ to false:

__p($sql, false);
__p(foo($params), false);

You can also set the ‘$debug’ as global constant variable, so as to control all the outputs by using a single switch flag.
As an advanced example, the following is a way of using HTTP request to control the output:

if ($__REQUEST['test']) {
  header('Content-Type: text/html; charset=utf-8');
  __p($obj->foo());
  exit;
}

At Browser’s URL part, everytime you add ‘test’ at end of the URI, like:

http://yoursite/your_script?params&test

Instead of output all webpage, the output results will be redirect, and print out the intermediate results.
That is useful for test and debug purpose. Of course, the function can be enhanced to add more features and better output.

PHP:Declare global variables

Declare global variable

I had a small bug in the PHP codes which prevents webpage from correctly display: global variable must be declared in functions before using it. The following codes doesn’t work:

$config = array(
 'header' => array(...),
);
function foo() {
 if (isset($config) && is_array($config['header'])) {
  //do some stuff.
 }
}
foo();

the foo() will not be executed because $config is unseen and not set in the function. To correct it, add:
global $config;
at the beginning of the function, to declare ‘I have been defined some place else’, like this:

function foo() {
 global $config;
 if (isset($config) && is_array($config['header'])) {
  //do some stuff.
 }
}
foo();

Right now it works.
1 more thing is: The $_COOKIE is not secure enough because it can be seen in different scripts as long as it is set. But $_SESSION is much more safe since it can only be seen in the script it is called.

echo "<pre>"; print_r($_COOKIE); print_r($_SESSION); echo "</pre>";

$_COOKIE will be printed out here, but $_SESSION not. So for security reason, $_SESSION is more considerable.

PHP: calling process to run in the back-end

PHP: calling process to run in the backend

Sometimes we need PHP to call server-side scripts. e.g., using PHP to call Perl’s cgi or bash script to do some server-side stuff. There are 2 possible issues:

(1) calling a script without waiting

Here is my way to implement the without waiting calling:

<php
$key = trim($_POST['key']);
if (!empty($key)) {
 exec("/cgi-bin/search.pl '" . $key ."' >/dev/null 2>&1 &");
 // or:
 // exec("nohup /cgi-bin/search.pl '" . $key ."' >/dev/null 2>&1 &");
}

By using ‘&’ at the end of the command, Linux will fork a new child process to execute the Perl script (.pl), thus, seperate it from the original php script.

The benefit is that the php script doesn’t need to wait for processing’s return, no waiting time, just dispatching a task to run back-end. This is very useful in the case of using webpage-form to trigger a ‘backup’ process or ‘searching’ process. User clicks a button, close the page, and just let it do!

(2) call a script and wait for return result.

How about calling a process with return value? Here is the way:

<php
 system("/bin/process.sh >/dev/null 2>&1", $retval);
 if ($retval == 0) echo 'success';
 else echo 'failue';
?>

Notice: here is no ‘&’ at the end of the command, and we use ‘system’ command instead of ‘exec’ because it comes with return value, not fork a child-process and let it go.
After the calling, immediately we judge the return value, here is $retval, to decide next step to go.

PHP and Redis Server

PHP and Redis Server

Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

Redis server can be used as a session handler, which is especially useful if you are using a multi-server architecture behind a load balancer.
Redis also has a publish/subscribe system, which is great for creating an online chat or a live booking system.
I used Redis server with NodeJS before; however and definitely, Redis Server is also available for PHP. Here is a helpful article:

http://phpmaster.com/an-introduction-to-redis-in-php-using-predis/

The following are the steps to install Redis-server, and make it work in PHP.

//1. install redis-server
wget http://redis.googlecode.com/files/redis-2.2.4.tar.gz
tar -zxf redis-2.2.4.tar.gz
cd redis-2.2.4
make
sudo make install

//2. run it, sumple way, you can also use: 
//sudo update-rc.d redis-server defaults to make it run when start.
$ /usr/local/bin/redis-server &

Now Redis server is done. After that, we make it work with PHP.
For PHP, Redis client library is Predis, we can get the sources from github:

$ git clone git://github.com/nrk/predis.git

After install Redis server and Predis interface, we now use PHP to connect and operate the session server. A testing example like this:

<?php
require "predis/autoload.php";
Predis\Autoloader::register();

// since we connect to default setting localhost
// and 6379 port there is no need for extra
// configuration. If not then you can specify the
// scheme, host and port to connect as an array
// to the constructor.
try {
    $redis = new Predis\Client();
/*
    $redis = new Predis\Client(array(
        "scheme" => "tcp",
        "host" => "127.0.0.1",
        "port" => 6379));
*/
    echo "Successfully connected to Redis";
}
catch (Exception $e) {
    echo "Couldn't connected to Redis";
    echo $e->getMessage();
}

Pretty simple, and should return ‘Successfully connected to Redis’. A more test for Redis key-value store is like this:

<?php
$redis->set("any_key", "Hi Redis for php by using predis!");
$value = $redis->get("any_key");
print_r($value);

3 small and interesting PHP applications

3 small and interesting PHP applications

I wrote 3 simple and interesting PHP scripts: with jQuery plugins’ support, they implement: register, send_email, search functions individually. The scripts are accessible at:

https://github.com/williamjxj/3-small-but-interesting-PHP-applications

  1. search.php
    search.php script: search files in certain directory to get the context by keyword. It runs perfect, the advantages:

    • Esay usage, all web-based, Ajax-driven.
    • Using jqtransform
    • The display results is adjustable. The matching times are displayed right side of the mapping files.
    • keyword is highlight, easy to identify.
    • Display looks good. The search form uses jqtransform – a jQuery Plugin CSS render library.
    • The codes are simple and easy to integrated with other apps. Ccan be shared.
    • Any tech issues, I am here for consulting 🙂
  2. register.php
    Using jquery.easing.js to generate a dynamic form for register purpose.
  3. send_email.php
    Using jQuery validationEngine and jqtransformplugin to generate a form to send email.