PHP

Browsersync is an automation tool that can watch files for changes and inject them into a web page without reload.

Usage:

  • Install Node.js
  • Install Browsersync
    npm install -g browser-sync
  • Start Browsersync
    browser-sync start --proxy "myproject.dev" --files "css/*.css"

Browsersync will create a proxy that will wrap your vhost myproject.dev with a proxy URL.

It can also be used with gulp:

var browserSyncWatchFiles = [
'./style.css',
'./js/*.min.js',
'./*.php'
];
var browserSync = require('browser-sync').create();
var browserSyncOptions = {
proxy: "myproject.dev",
notify: false
};
gulp.task('browser-sync', function () {
browserSync.init(browserSyncWatchFiles, browserSyncOptions);
});

Technology:

The best way to customize a WordPress theme, is to create a child theme. To do this, you need to create a directory in the themes folder, add a style.css and set the the ‘Template’ parameter in its header to the name of the parent theme:

/*
Theme Name: Some Child Theme
Template: some-parent-theme
*/

Then you need to create a functions.php file and make sure to enqueue the parents css:

add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_styles' );
function mytheme_enqueue_styles() {
   wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}

After that, you can copy any template file from the parent theme to your child themes directory and change whatever you need. These files won’t be overwritten when the parent theme receives an update.

Technology:

PHP blocking fifo queue

I have put together a few functions in PHP that allow processes to enter into a queue and wait their turn. This queue is file based and thus accessible to all processes on the system. The use case is e.g. a function call or processing of a file that should not have more than one instance on the whole system.

There are two files, one that contains the actual queue (queue.php) and a lock for accessing the queue (queue.lock). All the functions are part of a bigger PHP object, hence the private modifiers and occasional $this references.

As of now I can't get any kind of indention to work here, sorry for that. Now for the function that lets a process put his ID into the queue:


private function push_to_queue()
{
$queue = Array();
$fh = fopen($this->folder."/queue.lock","w");
$start_time = microtime(true);

do
{
$haveLock = flock($fh, LOCK_EX);
if(!$haveLock) usleep(rand(0,100)*10000);
}
while(!$haveLock && (microtime(true)-$start_time) < 10000);

if($haveLock)
{
include($this->folder."/queue.php");

if($queue == null) $queue = Array($this->id);
else array_push($queue, $this->id);

$save = '$queue = unserialize(\''.serialize($queue).'\') ?>';
file_put_contents($this->folder."/queue.php", $save);
}

fclose($fh);
}

Next the function which lets a process remove his id from the queue:

private function remove_from_queue()
{
$fh = fopen($this->folder."/queue.lock","w");

$start_time = microtime();

do
{
$haveLock = flock($fh, LOCK_EX);
if(!$haveLock) usleep(rand(0,100)*1000);
}
while(!$haveLock && (microtime(true)-$start_time) < 10000);

if($haveLock)
{
include($this->folder."/queue.php");

$key = array_search($this->id,$queue);

if($key !== FALSE)
{
unset($queue[$key]);
$queue = array_values($queue);
}

$save = '$queue = unserialize(\''.serialize($queue).'\') ?>';
file_put_contents($this->folder."/queue.php", $save);
}

fclose($fh);
}

And last a function for reading the queue:

private function load_queue()
{
$fh = fopen($this->folder."/queue.lock","w");

$start_time = microtime(true);

do
{
$haveLock = flock($fh, LOCK_SH);
if(!$haveLock) usleep(rand(0,100)*1000);
}
while(!$haveLock && (microtime(true)-$start_time) < 10000);

if($haveLock)
{
include($this->folder."/queue.php");
return $queue;
}

fclose($fh);
}

Usage for the functions currently looks like this:

$this->push_to_queue();

$sleep_time = 0;

$queue = $this->load_queue();

while($queue[0] != $this->id)
{
usleep(500000);
$sleep_time++;

if($sleep_time >= 120)
{
$return = Array("error" => "queue_timeout");
$this->make_log("[WARNING] Request timed out in queue.");
return $return;
}

$queue = $this->load_queue();
}

// DO STUFF

$this->remove_from_queue();

Caveats: Obviously there could be a lot of disk access with the file based queue.

Taggings:

PHP mail() Function

The problem was solved by the creation of the PHP mail()-function.

Programmers have to include the receiver or receivers, subject, message, header (From, Cc, and Bcc) and optional parameter of the eMail.

The syntax of the mail()-function is mail(to,subject,message,headers,parameters).

For an example, see "Screenshot PHP Mail-Function" or the following code-snippet:


<?php
$to = "somebody@example.com";
$subject = "test subject";
$txt = "Hello world!";
$headers = "From: from@example.com" . "\r\n" .
"CC: cc@example.com";
mail($to,$subject,$txt,$headers);
?>

Taggings:

Changing the timout in the php-files manually

I realized that I wasn't able to log in in any way. But this was seeming a problem of some older versions of Joomla. They allow you to enter any value you want as timeout but if you enter a too high value you will be not able to log in again. Fortunatelly I could access all the source files of the CMS via FTP and I also had the access-data like username and password and so I could change the timout value to another one in two source files in which it is neccessary: the index2.php and the index3.php file. You can find that solution in the troubleshooting-section in the Online-Book "Joomla!" from http://www.galileocomputing.de.

Use PHP to extract textual information from DOCX and ODT documents

Actually this task appeared to be not that hard as I first thought. To make the task more real, I was working with Russian language, i.e. with CP1251.

So at first I tried to open the documents with simple Lister. The screenshot of the experiment is provided in the attachments. Both files, odt and docx, look like binary files from this point of view. But the most important detail to notice (and it's quite small I would say) is th letters "PK" in the beginning of the data. That actually means that both files are, somewhere deep in their soul, just a zip-archive, which extension was renamed either to odt or to docx.

If we open any of the files in Total Commander using Ctrl+PageDown (Open element under the cursor) we will get a structured content with some folders and XML documents. The screenshot of the experiment is provided in the attachments.

The content that we need is situated in the file content.xml (in ODT) and word/document.xml (in DOCX).

So, in order to extract textual information from ODT ot DOCX formats, we will have to use the standard ZipArchive class and some functions to work with it.
The source code is provided in the attachments. The solution works under PHP 5.2+ and requires php_zip.dll for Windows or --enable-zip key for Linux. In case of unavailability of ZipArchive (like old PHP or lack of libraries) one could use PclZip (http://www.phpconcept.net/pclzip/index.en.php) .

References:
www.msdn.microsoft.com/en-us/library/aa338205.aspx
http://www.i-rs.ru/content/download/1447/8162/file/OpenDocument-v1.0-os.pdf

Use flash and actionscript

After hours of search in the internet I figured out that flash in combination with actionscript 3 is able to provide mutli-select file dialogs. So I included a small flash file in my website to read the given input files and send them via a HTTP post request to a PHP file which moves the uploaded files iteratively to the specified destination location. In the constructor of the actionscript file I defined a file reference object and added some events that invoke certain methods automatically:<code>fileRef = new FileReferenceList();fileRef.addEventListener(Event.OPEN, fileRefListener_onOpen);fileRef.addEventListener(Event.CANCEL, fileRefListener_onCancel);fileRef.addEventListener(Event.SELECT, fileRefListener_onSelect);fileRef.addEventListener(ProgressEvent.PROGRESS, fileRefListener_onProgress);fileRef.addEventListener(Event.COMPLETE, fileRefListener_onComplete);</code>After that I specified a bunch of methods. The first one will be called if the user hits the “Upload-Files” button. It specifies the sort of files allowed to be uploaded (filter) and opens the upload dialog:private function browseClick(event:Event) {                var fileFilter:FileFilter = new FileFilter("Images", "*.jpg;*.jpeg;*.png");    fileRef.browse([fileFilter]);}Now I wrote the methods defined in the constructor that will be called automatically because of the event listeners. The most important is the “fileRefListener_onSelect”-method. It stores all file references in an array:public function fileRefListener_onSelect(event:Event) {        var fileRefList:FileReferenceList = FileReferenceList(event.target);    var list:Array = fileRefList.fileList;    var tempList = new Array();        for (var i:uint = 0; i < list.length; i++) {                                        tempList.push(list[i])    }        filesToUpload = filesToUpload.concat(tempList);}The other listener methods can be specified in the same way. They will be called if the file upload has started, ended or is still in progress (progress diagrams). In one last method I told the script to start the upload on the collection of filereferences . The variable “pathUploadScript” contains the URL of the PHP script:public function uploadFiles(event:Event){                filesUploaded = 0;        var item;    for(var i:Number = 0; i < filesToUpload.length; i++) {                item = filesToUpload[i];        item.addEventListener(Event.OPEN, fileRefListener_onOpen);        item.addEventListener(Event.CANCEL, fileRefListener_onCancel);                        item.addEventListener(ProgressEvent.PROGRESS, fileRefListener_onProgress);        item.addEventListener(Event.COMPLETE, fileRefListener_onComplete);        var url:URLRequest = new URLRequest(pathUploadScript);                if(!item.upload(url)) {            status_txt.htmlText = "Upload dialog failed to open.";        }    }}    The smallest version of this PHP file has to look similar to this:$uploadFile = $dir."/".$_FILES['Filedata']['name'];move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadFile);It moves the file from the temporary upload directory to a location I specified in $uploadFile.

Taggings:

Use the apache mod_rewrite

The default CodeIgniter URL is composed in the following way:http://domain.com/index.php?myController/myMethod/param1/param2/param3This URL loads the file myController.php in the controller subdirectory and calls the public method myMethod(“param1”, “param2”, “param3”) with the given strings as parameters. What I wanted to do was hiding the substring “index.php?” from the users to make the URL look better. The website runs under the apache webserver so I used the rewrite module to finish this task. So before you continue, make sure that this module is running properly. The first step I had to do was writing an .htaccess file which contains those few lines of code and save it in the directory where the index.php is located: <code>    RewriteEngine On    RewriteBase /    RewriteCond %{REQUEST_FILENAME} !-f    RewriteCond %{REQUEST_FILENAME} !-d    RewriteRule ^(.*)$ index.php?/$1 [L] </code>The first line activates the rewrite module. The second line states the scope of the rewrite rule. Since the index.php and the .htaccess files are located in the same folder I used a backslash to use the current directory as the scope. The RewriteCond commands can be perceived as conditions that have to be met until the rewrite rule is activated. My two conditions test if the URL calls another file (f) or directory (d) that exist in the current directory. If so, the URL want be changed and the desired resources will be loaded. This is important if there are any other resources than those provided by CodeIgniter in your root directory. If there are no such resources, the rule will be activated which is depicted in the last line. It says that the complete URL string after the domain plus toplevel domain (left term in the regular expression) has to be copied behind the term “index.php?/”. The $1 represents this copied value which in the upper example is the string “myController/myMethod/param1/param2/param3”. The [L] says that this is the last rule (this is just importand if we would have used a sequence of rules). In the last step we have to tell the framework that it should not use the term “index.php” for the creation of links anymore (this step is now done by the apache module implicitly). Therefore we open the file system/application/config/config.php and change the variable$config['index_page'] = "index.php"; to$config['index_page'] = '';   Thats it! After an apache restart the thing should be working!

Taggings:

Using PHP-IDS to secure php web pages

The use of PHP-IDS is pretty simple. Not much coding has to be done. The tool is nicely tested and easy to configure. Once you have downloaded PHP-IDS from http://php-ids.org/downloads/ you can start securing your user-input. After including PHP-IDS with

  • require_once 'IDS/Init.php';

you can define which arrays should be checked by the tool

  • $request = array( 'REQUEST' => $_REQUEST, 'GET' => $_GET, 'POST' => $_POST, 'COOKIE' => $_COOKIE);

initialise and run PHP-IDS with your config

  • $init = IDS_Init::init('IDS/Config/Config.ini');$ids = new IDS_Monitor($request, $init);$result = $ids->run();

finally you can look at the $result object to determine the content

  • if (!$result->isEmpty()) { echo $result;}

PHP-IDS is not 100% secure but it provides help to make your web page safer. 

Taggings:

Subscribe to PHP