..a dose of zero-day know-hows ..

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

5/03/2010

Using PHPXref

PHPXref is a PHP cross referencing documentation generator designed to make it easier for developers to browse a PHP application's codebase. With features such as mouse-over information and hot-jumping among classes and functions and extraction of phpdoc style documentation, it really does simplify a job of a developer in getting to know a new application.

It requires Perl to be installed since it uses a perl-based script to parse the source directory to generate a documentation. You may download the right version of Perl for your platform here.

Using PHPXref to generate a cross referencing documentation of any application is easy, assuming you already have Perl installed, just follow these 5 simple steps.

Step 1.) Download PHPXref from http://phpxref.sourceforge.net/#download (choose the version suited for your platform).

wget http://prdownloads.sourceforge.net/phpxref/phpxref-0.7.tar.gz?download

Step 2.) Uncompress the downloaded phpxref archive

tar xvpf phpxref-0.7.tar.gz

Step 3.) Navigate to the extracted folder and edit the file named phpxref.cfg. Edit the values for the SOURCE, OUTPUT and PROJECT as needed.


(NOTE: You may need to create the directory for the OUTPUT if it doesn't exist yet to prevent runtime errors during generation as the phpxref script will not create it for you.)

Step 4.) Run the phpxref generation script by invoking the following command:

./phpxref.pl



Step 5.) Once generated, you may now browse the generated documentation in HTML format. If you have set the OUTPUT to point within your Document Root as with our example above, you may browse it using http://localhost/phpxref_sugarcrm or directly in its location since the generated doc is static.



You may automate this process to keep the cross referencing documentation up to date by regularly running phpxref.pl via cron.

5/02/2010

Quick Install Memcached and Memcache for PHP on Fedora

Memcached is a high-performance, distributed memory object caching system. In web applications implementation, it is intended to alleviate database load by caching the most requested data for faster retrieval and lessen DB hits.

Installing Memcached on Fedora and adding it as a PHP module is fairly simple using the console.

Step 1: Install Memcached

yum install memcached

Step 2: Install Memcache PECL module for PHP

yum install php-pecl-memcache

Step 3: Restart Apache

service httpd restart

Step 4: Run the Memcached Daemon

service memcached start

Once finished, you should be able to access memcache-related functions and utilities. You can check the memcache entry in the phpinfo() page which verifies that it has been successfully installed as PHP module.



For more information on how to use the Memcache Class provided by the Memcache PECL module, visit the following link: http://www.php.net/manual/en/book.memcache.php


8/06/2009

Getting "failed to open stream: HTTP request failed! HTTP/1.1 501 Method Not Implemented" When Passing Post Requests to JSON RPC Server

I spent some few hours trying to figure out how to go around the HTTP/1.1 501 error I am getting using the JSON Client Class from JSON-RPC_PHP (http://jsonrpcphp.org).

As it turns out the culprit was the modsecurity module for Apache2. The logs indicate that the JSON Server script is denying the JSON Client access.

[msg "Request content type is not allowed by policy"]


Instead of hacking the JSON-RPC library, what I did was disabled the restrictions inhibiting the JSON client from passing post request to JSON server by commenting out few lines in my /etc/httpd/modsecurity.d/modsecurity_crs_30_http_policy.conf, lines 68-70, specifically the following:


#SecRule REQUEST_METHOD "!^(?:get|head|propfind|options)$" \
#"phase:2,chain,t:none,t:lowercase,deny,log,auditlog,status:501,msg:'Request content type is not allowed by policy',id:'960010',tag:'POLICY/ENCODING_NOT_ALLOWED',severity:'4'"
#SecRule REQUEST_HEADERS:Content-Type "!(?:^(?:application\/x-www-form-urlencoded(?:;(?:\s?charset\s?=\s?[\w\d\-]{1,18})?)??$|multipart/form-data;)|text/xml)" "t:none"


After restarting apache, json server/client works fine. I hope this would spare someone from the hours of hair pulling.

5/17/2009

Using PHPMailer and Crontab in Enqueuing/Sending System Generated Emails

This article covers how to use PHPMailer and Crontab to send Emails via an SMTP server without having to directly trigger the actual email sending task via the web process. This implementation gives a performance gain especially to the systems wherein most actions need to trigger email sending (eg. Notification systems in ERP's, CRM's and CMS's).


Scenario
Most of the systems I have dealt with trigger the sending of Emails from the Web server through the web request. An example of this scenario are Notification Emails being sent to the recipients when a certain action is triggered/accomplished.

Although this is a common approach for most systems eg. CMS, CRM etc., I find it inefficient as the execution speed of the script which sends the actual email is dependent to the SMTP server set to be used, in such events, if the SMTP serves lags/fails on responding, the script which invokes fsckopen will wait until the STMP server answers which might cause the script to timeout after some moments of waiting.

Solution:
Instead of attempting to send the email directly along the web process, it is wise to enqueue the email by storing it on a database, and let crontab pick those entries up and send the emails using the php cli by accessing a PHP Email Class such as PHPMailer. The sent emails in the database can then be flagged as 'sent' so the query which picks the emails up can exclude sent emails via "WHERE `sent` != '1' LIMIT ...".

This is a sample implementation (PHPMailer)

A. Setup the Database Table

The first thing that needs to be done is to create a table where the enqueued emails will be stored. This sample table is generic enough for most purposes, but feel free to expand as deem fit.
CREATE TABLE  `outgoing_emails` (
`id` int(9) NOT NULL auto_increment,
`recepient` text,
`subject` text,
`body` text,
`mode` int(1) default '0',
`date_entered` datetime default NULL,
`sent` int(1) default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
In the table above, the basic parts of an Email has columns which correspond to arguments that can be passed to the phpmailer Send() method.

B. Setup the PHPMailer Class
Download PHPMailer (PHPMailer 2.0.4 is used for this example, although other versions may be used), and uncompress it as appropriate.

C. Setup the actual email enqueuing and sending script
This script will be used to access the PHPMailer class, enqueue and send the emails (in short, it will be the all-in-one script which will do all the job). This script will be accessed by cron and execute it via PHP cli.

Note: This is a modified version of the functions used by Mambo CMS to send out emails and is found in all versions up to 4.6.x series. This is a very good implementation anyways and I am lazy to write my own for the sake of demo-ing:



Copy and paste the code above and save as enqueue_emails.php. You may need to modify lines 1-14 to set proper MySQL and SMTP credentials, as well as the path where you extracted the PHPMailer package.

D. Setup the Cron job
Next is set the crontab to run enqueue_emails.php, eg. if you intend to send the email in batches every 2 minutes, you would need to set the cron to the following:

*/2 * * * * php -f /var/www/mail/enqueue_emails.php


E. Reroute the email sending lines in your script to use the 'enqueue_emails()' function
Take it for a spin, An example would be:

require_once( 'enqueue_emails.php' );
enqueue_email('test@example.com', 'email subject', 'email body');

Wait for 2 minutes and let cron pick the email up and send it to the recipient, wait until it arrives in the inbox and And you're done.

For any questions, follow-ups, feel free to leave a comment, I hope this has been helpful.

4/16/2008

How to Make 'Read More' Links (A very simple sample implementation for PHP/MySQL)

Scenario: You have a php/mysql dynamically driven pages, you want a 'Read More' link displayed with your articles. This sample implementation might just give you the very basic analogy.

Method 1: For Articles stored on a single DB Field

A.) The DB Structure: (Use MySQL CLI or PHPMyAdmin to execute query)

CREATE DATABASE `test`;
CREATE TABLE `test`.`article_table` (
`id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(100) NOT NULL default '',
`article` mediumtext NOT NULL,
`created` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)

B.) The DB Sample Content: (Use MySQL CLI or PHPMyAdmin to execute query)

INSERT INTO `test`.`article_table` VALUES
(1, 'Article 1', 'Its been a while since i posted an article, busy months have passed and
im still within timeframes and deadlines.. well most of the time real life intervenes eh?
anyways heres my article about Sharing Hashes between Mambo 4.x and SugarCRM
4.5.1 Using MySQL Views', '2008-01-01 12:00:00'),
(2,'Article 2', 'The "foo: bar: not found" error message does not indicate that bar could
not be found, but rather bar exists but is calling something that could not be found.
This is the case with Perl scripts when the script cannot find where Perl is.
I have noticed that most of out "out-of-the-box" Perl scripts point to "/usr/local/bin/perl"
whereas some of the OS pre-bundled Perl is preinstalled at "/bin/perl", hence, when you
run a Perl script, the "foo: bar: not found" pops out the terminal.', '2008-01-01 12:00:00')

C.) The Script to Display the Articles in Summary and Full View Depending on the Task. Save as readmore.php


Heres whats happening above:
  • All Articles Are displayed as Summary
  • We used Substring to show only first 60 characters, of course you can adjust this to any value, just hack the code.
  • Read More Link Per article will point to "readmore.php?task=Full&id={ID OF ARTICLE}"
  • Full View is Displayed
Important Hints:
  • The Full Article View needs the ID of the Article to Display
  • This makes it necessary for ReadMore link to specify the ID of the Article it is a part of

11/26/2006

Basic: Preparing Solaris 10 to run Mambo CMS

Brief Backgrounder on Solaris 10:

Solaris 10 is the latest OS offered by Sun Microsystems. Unlike its predecessors – Solaris 9 and previous releases, this version of Solaris is free for use with no restriction of any kind. It also has a twin named OpenSolaris which is essentially an exact replica except that it is available in source and as the named implies, yes OpenSolaris is open source. More info here and here.

Preparing Solaris 10:

Preparing Solaris 10 environment to run Mambo is basically having to set up Apache, MySQL and PHP environment and nothing else, as you might know the system requirements of Mambo is any system that can run certain versions of Apache, MySQL and PHP – click here for details. Solaris 10 is bundled with Apache 2 and MySQL 5 already, its just a matter of configuring these which we will discuss in detail later. PHP 5 is a little different story though as we will need a source distribution to compile this ourselves. PHP 5 needs to be a module for Apache, it has to support MySQL so bear with as we dig deeper.

Configuring Apache:

The configuration file for Apache should be located in “/etc/apache2/”. From a fresh installation it is named as httpd.conf-example under the same directory. You have to rename it to httpd.conf so Apache will recognize it.

# mv /etc/apache2/httpd.conf-example /etc/apache2/httpd.conf

Using your text editor (gedit or vi), edit httpd.conf to your liking, take note of the following directives as you may need to set this as neccessary:

ServerName – The IP address or hostname of your machine (ex. 127.0.0.1 or example.com)

Listen – the port where Apache will listen to (ex. 80)

Next, is invoke the terminal and enable the service using the following command:

# svcadm enable apache2

Test Apache by opening the browser and pointing it to http://localhost.

Note that depending with your Desktop GUI, invoking the Terminal is done differently. Under the Java Desktop System 3, you do this by right clicking the desktop and selecting Open Terminal. Under CDE, you do this by clicking the Tools menu (the arrow on top of Performance Meter) and clicking console.

Configuring MySQL:

The MySQL database tables need to be created 1st. It will be the physical representation of your would-be MySQL tables as you create them. Moreover, the physical storage for your MySQL databases. Invoke the terminal and do the following command:

# /usr/sfw/bin/mysql_install_db

You should see several messages. MySQL Daemon by default does not allow root to run it. In such case a user needs to be set up specifically to run the MySQL server. Proper permissions are also mandatory. Invoke the terminal and issue the following commands:

# groupadd mysql
# useradd –g mysql mysql
# chown root /var/mysql
# chgrp –R mysql /var/mysql
# chmod –R 770 /var/mysql

What the above commands do are:
  1. Creates a group called MySQL,

  2. Creates a User named MySQL and makes it a member for the MySQL Group,

  3. Sets the ownership of the MySQL data directory to root,

  4. Sets the group of the MySQL data directory to MySQL group and

  5. Sets Read write access for the Group and Owner designated to the MySQL data directory while leaving others with no access.

Next is to set the MySQL Configuration File: Using the terminal, create a copy of a sample MySQL configuration file to the /etc directory as follows:

# cp /usr/sfw/share/mysql/my-medium.cnf /etc/my.cnf

Now to start the MySQL Daemon, use the following command:

# cd /usr/sfw/sbin/
# ./mysqld_safe --user=mysql &

To set the MySQL Password, the following commands need to be executed:

# cd /usr/sfw/bin
#./mysqladmin –u root password new-password
#./mysqladmin –u root –h localhost password new-password

To start the MySQL Daemon automically when Solaris starts, you need to bootstrap the startup files to rcs.d, rc1.d, rc2.d and rc3.d under the /etc directory. Issue the following commands using the terminal:

# ln /etc/sfw/mysql/mysql.server /etc/rcS.d/k00mysql
# ln /etc/sfw/mysql/mysql.server /etc/rc0.d/K00mysql
# ln /etc/sfw/mysql/mysql.server /etc/rc1.d/K00mysql
# ln /etc/sfw/mysql/mysql.server /etc/rc2.d/K00mysql
# ln /etc/sfw/mysql/mysql.server /etc/rc3.d/S99mysql

Compiling PHP 5

If you have gone this far without errors - congratulations, but we are still at the half. Since we will need to compile PHP from source, we will need to set Solaris for compiling environment and will install a bunch of applications.

Note that the variable $PATH which is an array of location where Solaris searches for applications is not set properly on a fresh installation. Consider setting up your path as follows
On TCSH:
# setenv PATH {$PATH}: /opt/csw/bin:/usr/sfw/bin:/usr/dt/bin:/usr/css/bin
On SH:
# set PATH=$PATH:/opt/csw/bin:/usr/sfw/bin:/usr/dt/bin:/usr/css/bin
# export PATH

A default install of PHP requires the following:

  • gcc
  • make
  • flex
  • m4
  • autoconf
  • automake
  • perl
  • gzip
  • GNU tar
  • GNU sed

However a standard install of Solaris is already bundled with most of the listed above, what you'll need is only autoconf, automake and GNU sed, you can download them directly by invoking the following commands from the terminal (you should be in a directory where you intend to store the packages). The full is at http://www.sunfreeware.com/programlistintel10.html

# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/autoconf-2.60-sol-10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/8/automake-1.5-sol8-intel-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/sed-4.1.5-sol10-x86-local.gz

Note that the Automake version is for Solaris 8 but should also work, links to the Solaris 9 and 10 versions are dead on the time of this writing as reffered here.

Once you have downloaded the above packages, uncompress them using gunzip

# gunzip *.gz

Then install them using pkgadd -d

# pkgadd -d autoconf-2.60-sol-10-x86-local.gz
# pkgadd -d automake-1.5-sol8-intel-local.gz
# pkgadd -d sed-4.1.5-sol10-x86-local.gz

After successfully doing the steps above which have set up a compiling environment for PHP, there are still a few applications that needs to be installed similar to the procedure above. The following applications are needed for a fully functional and optimal Mambo installation later: Download the following files from http://www.sunfreeware.com/programlistintel10.html or use wget for direct download

# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/zlib-1.2.3-sol10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/xpm-3.4k-sol10-intel-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/freetype-2.2.1-sol10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/freetype-2.2.1-sol10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/fontconfig-2.2.98-sol10-intel-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/expat-1.95.5-sol10-intel-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/libiconv-1.11-sol10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/libpng-1.2.12-sol10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/jpeg-6b-sol10-intel-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/openssl-0.9.8d-sol10-x86-local.gz
# wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/curl-7.15.4-sol10-x86-local.gz
#wget ftp://ftp.sunfreeware.com/pub/freeware/intel/10/ncurses-5.5-sol10-x86-local.gz

Install the above application in exact order as downloaded to stay safe. Certain dependencies might not be fullfilled if installed in random..

..TO BE CONTINUED