Spiga

‘ Web Aplications ’ category archive

Custom Error Documents with .htacces

May 24, 08 by Gabi Solomon

Some people only know about .htaccess utility in apache rewrite, but it can do more than that. For example it can help you specify your own Error Documents. When ever a browser makes a request for a web document ( webpage, files, images, css files etc) the server returns a header that contains an error code that tells the browser details about the requests. I will list this codes below:

Successful Client Requests
200 OK
201 Created
202 Accepted
203 Non-Authorative Information
204 No Content
205 Reset Content
206 Partial Content
Client Request Redirected
300 Multiple Choices
301 Moved Permanently
302 Moved Temporarily
303 See Other
304 Not Modified
305 Use Proxy

Client Request Errors
400 Bad Request
401 Authorization Required
402 Payment Required (not used yet)
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable (encoding)
407 Proxy Authentication Required
408 Request Timed Out
409 Conflicting Request
410 Gone
411 Content Length Required
412 Precondition Failed
413 Request Entity Too Long
414 Request URI Too Long
415 Unsupported Media Type

Server Errors
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

In order to In order to specify your own ErrorDocuments, you need to know these error codes, since you will need to specify for wich error code you want to assign a page.

But you wont need to specify an error page for all those codes, You only might want to do a custom error page for the most common of them like 404 and 500. Also most people do a custom Error Document for
401 – Authorization Required ( for sections of the site that are protected by a folder password and somebody tries to enter a protected area without corect login details ),
403 – Forbidden ( for example when someone is trying to access a folder withough an index option )
400 – Bad Request, which is one of those generic kind of errors that people get to by doing some weird stuff with your URL or scripts.

The advantage of having custom error documents is that you can display to the user a custom page with the site layout ( instead of the simple default one ) and you can even build a script to make custom logs of this errors.

You shouldn’t make custom pages for all error codes, for example an ErrorDocument for code 200 would cause an infinite loop, whenever a page was found…this would not be good.

To specify your custom error documents, you will add a special command for this in the htaccess file:
ErrorDocument [code] /directory/errorDocument.html

For example an error document for 404 would be:
ErrorDocument 404 /errors/404.html

Now you told the server that when it has an error code of 404 to return the page http://yoursite.com/errors/notfound.html. The same principle apply's to all the codes.

As a small advice i would recommend you make a special folder for your error documents and also name them something that will show theyr error code and purpose. I put 404.html but you can do notFound.html for example. Also the error documents do not need to be html they can also be php,asp or other types of files.

If you dont want to make a special file you can add the html directly in .htaccess file
ErrorDocument 401 "<body> You have to to be a member to view this page.

To do this you need to keep in mind :
the ErrorDocument starts with a " but does not end with one ... that was not a typo :)
the command should be on one line, including the HTML

How to Add JavaScript to Joomla Content

May 20, 08 by Gabi Solomon

Sometimes you need to add some javascript to your joomla content, being either some type of ad ( google adsense or yahoo ) or maybe just a code to display a widget from another site.
I bet you have tried to add it to the content, but as you will see the editor will replace the code with the HTML coresponding code. Ex: < will become >.
This will make all the javascript code display on the page and nothing will happen.

The solution is quite simple, or at least the one i found :)
Login in as admin
Go to Site
Global Configuration
Default WYSIWYG Editor
Change it to No WYSIWYG Editor
Click Save.

Now go to Content:
Just add your Javascript in the Content Area
Click Save

Pretty basic solution. Sorry you need to do this each time you want to add javascript to you’re articles. havent found any other method. If you do please tell me in a comment to this article.

Cheers

Speeding your php application by tweaking the php configuration

May 03, 08 by Gabi Solomon

This article is meant to help you to speed up your application by by tweaking the php configuration. The time gained might not be to visible to the user, but i should relief a little of the load on the server. Also this tweaks are going to help you a little in security.

If you are on a shared server and dont know how to change your php configuration you might want to check this article also.

But enough talk and lets get right into it. I will write the configuration name, the recommended setting and how this helps your application.

short_open_tag = Off

This will turn off short tags ( <? …. ?> ) and have the php engine one problem less to worry about.

asp_tags = Off

Do not use ASP like tags: <% echo “hello world”; %>

memory_limit = 32M

This is one configuration that you might need to tweak once in a while. But for start it is better to set it to a lower value and adjusting it when you need it. This will help you keep track of your aplication memory usage.
An article about memory usage you can find here.

register_long_array = Off

This will tells PHP to not register the deprecated long $HTTP_*_VARS type predefined variables. The default value is On. Since almost nobody ever uses them any more ( unless they have some compatibilty problems with old scripts, and they need them on ) it’s recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET.

This directive became available in PHP 5.0.0 and was dropped in PHP 6.0.0.

register_argc_argv = Off

This is more or less the same with register_long_arrays referring mostly to GET informations so it should be set to Off as well.

auto_globals_jit = On

This makes php stop generating the SERVER and ENV variables at script start ( default behaver ) and generating them when needed (Just In Time). These should help performance by cutting down the memory used by your scripts.
For this to work you need to have register_globals, register_long_arrays, and register_argc_argv disabled.
As an inside info : i tried this on a server .. .and it didn’t seem to create any SERVER or ENV variables, but i guess it was the server configuration because on a different server it worked :D .

magic_quotes_gpc

From my experience having this on can be a real pain in the [****]. When this is on, all ‘ (single-quote), ” (double quote), \ (backslash) and NUL’s are escaped with a backslash automatically. Why this is bad ? because you dont have a control over it. For example you use a mysql wrapper for youre database interactions that already has an escape function, this will make your values double escaped, and you endup after a few submits with a bunch of backslashes. So better have it off and do your own escaping, and maybe use a cleaning function to prevent SQL Injection ( more info here )

always_populate_raw_post_data = Off

Raw Post data is one of the more advanced knowledge, so if you dont use it, relief php of it concern :D and set always_populate_raw_post_data = Off.

How to change php configuration on shared servers ?

April 30, 08 by Gabi Solomon

Sometimes your application might require one or more specific php configurations changed from its current value in order to work properly. The most common of this is the requires global_registers flag off ( i have no idea why some servers keep it on ).

If you are talking about a local sever running on your computer or a server to witch you have root rights, the solution is quite simple : you just modify the PHP configuration file (php.ini) to your needs, restart the server … and voila job done.

But what if you are on a shared server. You cant just go and ask the servers support team to modify the configuration for you ( they couldnt even if they wanted to, because that will affect all the websites on there server and then there would be some angry folks on the chat really fast :D ). Luckily the nice folks that designed the software running the server ( apache most of the time ) have thought of you and this situation and added a 2 possibilities for you to change the php configuration only localy without affecting the other websites hosted on the server.

1. Creating a local PHP.ini file

You just create a php.ini file in your domain root and add your configuration as if it was the php.ini from the actual server settings. This will overwrite the settings just for your domain. Getting back to our example where you want to disable register_globals flag off you would add a line to the file like :

“register_globals = off”

2. Using a .htaccess file

The second way would be to use a .htaccess file ( some of you used to do URL rewrite with it ). Now for this you have to know a certain syntax :

# to modify a flag attribute
php_flag [name] [value]

# to modify a value attribute
php_value [name] [value]

Again returning to our example : php_flag register_globals off

To check if your configuration has been changed you can use the phpinfo() function. Your new setting will appear on the local column.
You should know that that not all servers support this methods of modifying the php configuration, some will only support one of them, so you might want to check this would your server support if it doesnt seem to work.

On another note not all php configuration can be changed locally. A full list of php configuration variables can be found on php official website at :

http://www.php.net/manual/en/ini.php#ini.list

The options that can be overwriten localy have the PHP_INI_PERDIR or PHP_INI_ALL Changeable column. The ones with PHP_INI_SYSTEM can only be changed by the php.ini from the php instalation directory.

PHP Fatal error: Allowed memory size of 33554432 bytes exhausted

April 27, 08 by Gabi Solomon

PHP Fatal error: Allowed memory size of 33554432 bytes exhausted

This is an error that seem to puzzle most beginners, so i will try to explain what this error is all about.First lets understand why this is happing, there are a few reasons why your getting this error:

  • the output of your is very large
  • your script grabs over the 8MB default memory limit of PHP ( maybe from POST FILES variables )
  • there’s a bug in your script that is causing the script to eat that much memory

Now dont get scared its not a big deal, and usualy its a easy fix ;) . To solve this problem you should try to:

  • optimize your script so that it will not eat up the maximum memory limit
  • find bugs (memory leaks) in your script
  • minimize the output of your script
  • increase the memory_limit setting in php.ini or directly in your php script by using the ini_set() function

This 8MB default limit is coded in php to stop any script from taking to much memory out of the server and maybe crashing it. This is way the best method of dealing with this error is to figure out what is causing the need for this much memory and reducing it, rather then going for the easy way out and increasing the limit.

Hope this helped you and i await your comments

How to convert an image to grayscale using PHP

April 25, 08 by Gabi Solomon

This operation is a very simple one and any one can do it using an image procesing software. But when it comes to doing in PHP, then it becomes a bit tricky since php does not have any default functions for this operation.

Grayscale Images

First off let me explain what a grayscale image i. I know you probably think you know this, but i am going to explain it a bit different, in a way that will help you how to convert images to gray scale in php.

A grayscale image contains only various levels of gray in the image, which can be expressed mathematically by the red, green and blue values (expressed as RGB) all equal.

Convert an image to grayscale

Now for the important part how this convertion is actually done. Of course, true color images can have any value for r, g and b, so in order to convert this to a grayscale value a transformation is needed : from RGB to HSV ( Hue, Saturation and Value).
And to make the image grayscale all we need to do is to use the Value, with no Hue or Saturation.
The convertion from RGB to HSV is don trough the equations below :

H = pow(cos( ( (1/2)*( (r-g)+(r-b) ) / ( sqrt( (r-g)*(r-g) + (r-b)*(g-b) ) ) ), -1);
S = 1 - (3 / (r+g+b))*min(r,g,b) );
V = (1/3) * (r + g + b);

Don't get scared by looking at those equations thinking they are pretty complicated, the first two are, but the beauty is we don't need them :D . As i told you above we only need the value which is simply the average of RGB values.

But enough talk, lets get down and dirty and write the actual code to do an image converion :

PHP:
  1. $source_file = "test_image.jpg";
  2.  
  3. $im = ImageCreateFromJpeg($source_file);
  4. $imgw = imagesx($im);
  5. $imgh = imagesy($im);
  6.  
  7. for ($i=0; $i&lt;$imgw; $i++)
  8.   {
  9.    
  10.    for ($j=0; $j&lt;$imgh; $j++)
  11.    {
  12.  
  13.      // get the rgb value for current pixel
  14.      $rgb = ImageColorAt($im, $i, $j);
  15.  
  16.      // extract each value for r, g, b
  17.      $r = ($rgb&gt;&gt; 16) &amp; 0xFF;
  18.      $g = ($rgb&gt;&gt;  8) &amp; 0xFF;
  19.      $b = $rgb &amp; 0xFF;
  20.  
  21.      // get the Value from the RGB value
  22.      $V = round(($r + $g + $b) / 3);
  23.  
  24.     // grayscale values have r=g=b=V
  25.     $val = imagecolorallocate($im, $V, $V, $V);
  26.  
  27.     // set the gray value
  28.     imagesetpixel ($im, $i, $j, $val);
  29.   }
  30. }
  31.  
  32. header('(anti-spam-content-type:) image/jpeg');

Hope this article is going to save you some time on youre googling for a solution, and await youre comments

Web application load and performence testing

April 24, 08 by Gabi Solomon

Until recently i haven't done any load test on any of my web applications. I have heard of this but haven't gotten a chance to do a test and haven't been asked for one by my clients. I know some of you might question me as how can you not do this for big projects. I admit this was a mistake of mine, one which i plan to correct :D . So even if i heard of this applications i did not know of one in particular so i started googleing the web about this. Of course my target was one of many developers a good, professional application and of course open-source :) .

So after a bit of searching i found 3 software's that fit my descriptions, and which seem to be very well seen by the developers community. I will try do do a small review of them based on the information i found on them. Since i haven't got to to test them all, I will return with an update after i test them all and tell you on which one i decided to use.

1. OpenSTA

OpenSTA actually stands for Open System Testing Architecture. It is not in fact the name for a specific tool but for a distributed software architecture based on CORBA. The name OpenSTA is used here for a collection of tools that implement and use this distributed architecture.

The OpenSTA tool-set we describe here is free and its source is open and licensed under the GNU GPL. The source code is available on SourceForge.

The current stable version as of this writing is 1.4.5 and the only platforms available for this product are Windows NT, 2K or XP, although source code is available.

OpenSTA has several advantages that i have read on several websites : it's powerful, flexible, highly programmable, and free. The last point was what caught my attention :) , and i bet it will catch yours. So you can a copy of the OpenSTA and play with it without paying anything. Maybe some of you might argue that you get what you pay for ... but from what i have read this software is highly appreciated by the developer community and even used by some company's for there tests.

In OpenSTA you can program the virtual users that will generate the traffic. You can script various commands to be used through OpenSTA's SCL (Script Control Language). The downside of this is you have to learn it :) ). If you haven't used this before ( like me ) you will have a bit of learning to do to master SCL. This is if you want to make sophisticated tests. But the developers thought of noobs like me and made it possible to use a browser to record actions to script your users actions.

After the scripting is done you can run the test with any number of users, and analyze the results witch can produce graph stats for easy-er interpretation.

OpenSTA screen shoots

2. WebLoad

Yet another good piece of software that is open source. WebLOAD Open Source, licensed under the GNU Public License (GPL) , is based on WebLOAD, the RadView company’s flagship product that is already deployed at 1,600 sites. Immediately available for free download and use, WebLOAD is a commercial-grade open source project with more than 250 engineering years of product development.

The good thing about this product it allows you to create very complex scripts without entering any single line of code trough its advanced visual environment. But if for some reason you have something so specific to your test case that cant be done by the aid of the visual editor you have the possibility to tweak - or completely hand-code the script using JavaScript.

Once this is done you are ready to run the test. WebLOAD can generate requests from many, many simulated clients simultaneously, and also has the ability to simulate numerous Web browsers from old versions of Internet Explorer to new versions of Firefox. During the time the test is performed, WebLOAD is recording complex data about your application performs to the given traffic. This performance data is used by WebLOAD to generate a numerous type of reports. These reports can be generated as standard tabular data witch you can scan and analyze, which can be rendered on the screen but also printed out. Also WebLOAD can generate a variety of graphs from the data which will help you interpret the data more easily, and maybe spot the problems in your application ( hope not ).

WebLoad screen shoots

3. Microsoft’s Web Application Stress Tool

The other two software above although very good are somewhere complex. And sometimes you might want a quick performance tool to simulate multiple users on a page you just wrote. For example a report page that displays the last sales. And you want to know how this will preform if let say 1000 users try to access that page. For these scenarios, I Microsoft’s Web Application Stress Tool is going to be perfect. This is a very simple and small (9MB) application which can do a stress test on your Web application.

The Microsoft WAS web stress tool is designed to realistically simulate multiple browsers requesting pages from a web site. You can use this tool to gather performance and stability information about your web application. This tool simulates a large number of requests with a relatively small number of client machines. The goal is to create an environment that is as close to production as possible so that you can find and eliminate problems in the web application prior to deployment.

TO do a test you need to select record from the Tool menu and a browser window is opened. Here you can record the user actions ( what will the virtual users do ). After you have doing this you press Stop recording. Next you should see a screen similar to the following. On the left side you can see various parameters available for performance testing.

Microsoft’s Web Application Stress Tool screen shoots

That is it so far. Hope this helps you and i await any comments or advices on web stress testing ( i'm sure many of you are more good at this then me )

URL rewrite for XOOPS news module

November 10, 07 by Gabi Solomon

For this example we will considet that the nes module name is PS2. You can adapt this to whatever you want to.

First lets start by adding the rewrite Rules :

# Welcome to Windows IIS URL Rewriting! Below are the rules[ISAPI_Rewrite]# test rewrite StateRewriteRule /testrewrite.html / [I,L]      

# PS2 news Topic Rewrite : /ps2-c191-test-Article.html      

RewriteRule ^.*/ps2-c([0-9]*)-[^/]+.html /modules/news/index.php?storytopic=$1 [I,L]      

# PS2 news Rewrite : /ps2-191-test-Article.html      

RewriteRule ^.*/ps2-([0-9]*)-[^/]+.html /modules/news/article.php?storyid=$1 [I,L]
# Welcome to Linux Url-Rewrite 

# PS2 news Topic Rewrite : /ps2-c191-test-Article.html
RewriteRule ^.*/ps2-c([0-9]*)-[^/]+.html /modules/news/index.php?storytopic=$1 [L]  

# PS2 news Rewrite : /ps2-191-test-Article.html
RewriteRule ^.*/ps2-([0-9]*)-[^/]+.html /modules/news/article.php?storyid=$1 [L]

Next we need to add a new function to the module so we open /modules/news/include/functions.php and add a new function to the end of the file right before the php end tag ?>

/** * Create an url safe text*      

* @package News      

* @author Gabriel Solomon ( solomongaby at yahoo.com  )      

* @copyright (c) GSDesign www.gsdesign.ro      

*/      

function make_url($text)      

{  $urlName = strtolower($text);      

$trans = array(
" " => "-",
"/" => "",
"'" => "",
'"' => "",
);      

$trans[trim( " / " )] = "";      

$urlName= strtr($urlName, $trans);      

return $urlName;      

}

After this we need to register our new function as a smarty modifier. So we open /class/template.php and after

		$this->Smarty();

we add

		$this->register_modifier("make_url", "make_url");

Now we start to modify files :
/modules/news/class/class.newsstory.php
The modifications are saved in the file class.newsstory.php available in this file :
class.newsstory.php Modifications

/module/news/templates/news_article.html
The modifications are saved in the file news_article.html available in this File
news_article.htm Modifications

Hope you will find this usefull.

We are working on an installer and as soon as we have it you will find it here.

Awaiting you're comments and reviews.

How to duplicate the SmartSection Module for XOOPS CMS.

October 04, 07 by Gabi Solomon

A client gaved me a small task of creating 2 new sections for his website. The website is powered by the well-known CMS XOOPS. After looking at it i decided that the easy way out would be to duplicate one of the websites existing sections, and settled on the smart section. And because that gave a good run-a-round i thought i will post my solution on my blog, maybe others will benefit from it and save some time ( although others might think this is so obvious ).

First start by downloading SmartSection from http://smartfactory.ca/
Decide on a name for the new section. For this example we will consider GSD Section as the name.

Next we must do a few find & replaces in the files. To do that i used ReplaceEm wich you can download from http://www.orbit.org/replace/. This program let's you do multiple find&replace on multiple files at once, so you're time alocated to this task should decrease dramaticly. The replacement you must do are :

'smartsection' => 'gsdsection'
'SMARTSECTION' => 'GSDSECTION'
'SmartSection' => 'GsdSection'
'Smart Section' => 'Gsd Section'
'SSECTION' => 'GSECTION'
'Smartsection' => 'Gsdsection'

Now you must also replace the folder name to gsdsection, and also all the template files that have smartsection in there file name. For example smartsection.css will become gsdsection.css.

Also we must replace the names of the mysql tables. So we will open the file /sql/mysql.sql and replace all the of: smartsection_ with the name of your module. In my case I would replace it with gsdsection_.

Once you have completed these steps, upload the duplicated folder (now your cloned module) and install it though the XOOPS Admin panel.

[later_edit]

After completing all this steps i have found an even easyer way :)
I found an already made script to duplicate smart section ( a little bit too late for me , but who knows ... maybe not for others ).
Make a file named clone.php and put in the root folder of you're xoops powered website, also make sure there is a folder of the smartsection in the modules folder of the website.

Put the folowing code in the clone.php :


// ##########################################################
//	Define your mapping here
// ##########################################################
$patterns = array(
// first one must be module directory name
'smartsection'  => 'mysection',
'SMARTSECTION'  => 'MYSECTION',
'SmartSection'  => 'MySection',
'Smart Section' => 'My Section',
'SSECTION'      => 'MSECTION',
'Smartsection'  => 'Mysection'
);

$patKeys = array_keys($patterns);
$patValues = array_values($patterns);

// work around for PHP < 5.0.x
if(!function_exists('file_put_contents')) {
  function file_put_contents($filename, $data, $file_append = false) {
    $fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
    if(!$fp) {
      trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
      return;
    }
    fputs($fp, $data);
    fclose($fp);
  }
}

// recursive clonning script
function cloneFileFolder($path)
{
  global $patKeys;
  global $patValues;

  $newPath = str_replace($patKeys[0], $patValues[0], $path);

  if (is_dir($path))
  {
    // create new dir
    mkdir($newPath);

    // check all files in dir, and process it
    if ($handle = opendir($path))
    {
      while ($file = readdir($handle))
      {
        if ($file != '.' && $file != '..')
        {
          cloneFileFolder("$path/$file");
        }
      }
      closedir($handle);
    }
  }
  else
  {
    if(preg_match('/(.jpg|.gif|.png|.zip)$/i', $path))
    {
      copy($path, $newPath);
    }
    else
    {
      // file, read it
      $content = file_get_contents($path);
      $content = str_replace($patKeys, $patValues, $content);
      file_put_contents($newPath, $content);
    }
  }
}

cloneFileFolder('modules/news');

echo "Happy cloning...\n";
echo "check directory modules/" . $patterns['smartsection'] . " for cloned module \n";
echo "Consider modifying new module by editing language/english/modinfo.php and images/news_slogo.png manually (if you care)\n";

?>

Normaly change mysection with the desired name.

Cheers.

Awayting questions and comments :)