Archive for the 'php' Category
5 ways to speedup javascript
by Justin Silverton
1) use a compressor
JSMin is a filter which removes comments and unnecessary whitespace from JavaScript files. It typically reduces filesize by half, resulting in faster downloads. It also encourages a more expressive programming style because it eliminates the download cost of clean, literate self-documentation.
PHP version here
2) Minimize the number of .js files
Each .js file reference on a web page means another http request from a client’s browser. Although it may decrease the readability/maintainability of your code, it is faster to have one larger .js file than multiple smaller ones.
3) use profiler and timer tools
Firebug offers a suite of profiler and timing tools that allows you to see exactly how long your scripts take to execute and gives you the ability to tweak and optimize them.
4) asynchronize your code
Browsers run Javascript code synchronously. This means that when a <script> tag has been found, everything on the page stops until the end script tag has been found. If a script doesn’t finish executing within a certain amount of time, then the user gets a warning that says, “A script on this page is taking a long time to complete.”
example:
function testfunc()
{
var x1="test1";
var x2="test2";
alert(x1+x2);
}
testfunc(); //normal way to execute the function
window.setTimeout(testfunc,0); //asynchronous execution of testfunc()
The setTimeout function takes 2 parameters. The first is the name of the function that will be executed and the second is the number of milliseconds to wait until it is called. Since 0 is used for the second parameter, the function is called immediately (it will be forked in the background and the rest of your page will continue to load). This is useful for functions that take a long time to load.
5) cache DOM variables
Every binding in Javascript is late. This means each time you access a property, variable, or method a look-up is performed. Within the IE DOM, this could mean an extensive search of the element to find the same property over and over again, only to be returned to the JScript engine unchanged from the previous request.
Here is an example of a function that can be optimized:
function buildString()
{
var newElement = document.getElementById("myitem");
newElement.innerHTML = ""; // Clear out the previous
newElement.innerHTML += addHeader();
newElement.innerHTML += addBody();
}
Here is the optimized function:
function buildString()
{
var newText = addHeader() + addBody();
document.getElementById(”myitem”).innerHTML = newText;
}
PHP library for Microsoft AJAX
By Justin Silverton
Microsoft has released their AJAX library package for non-windows systems which contains a complete set of client JavaScript components that are included in the full ASP.NET AJAX installation. Developers over at Codeplex have developed a library that allows you to integrate your PHP applications with this package.
requirements
- PHP 5.2 — 5.2 is required for json_encode/json_decode; For earlier versions, you will need to install php-json
How to install
- Download the PHP library from codeplex here
- Download the Microsoft AJAX Library here
- After extracting both of these, place all the files from the Microsoft Ajax library in a directory called “MicrosoftAjaxLibrary”
Example
The following is a simple example that demonstrates a simple ajax transmission using the microsoft libraries.
(hello.htm)
<html>
<head>
<title>Hello, World!</title>
<script type="text/javascript" src="../../MicrosoftAjaxLibrary/MicrosoftAjax.js"></script>
<script type="text/javascript" src="HelloService.php/js"></script>
</head>
<body>
Name: <input id="name" type="text" /> <input type="button" value="Say Hello" onclick="button_click(); return false;" />
<br />
Response from server: <span id="response"></span>
</body>
<script type="text/javascript">
function button_click() {
HelloService.SayHello($get('name').value, function (result) { $get('response').innerHTML = result; });
}
</script>
</html>
(HelloService.php)
<?php
require_once '../../dist/MSAjaxService.php';
class HelloService extends MSAjaxService
{
function SayHello($name)
{
return "Hello, " . $name . "!";
}
}
$h = new HelloService();
$h->ProcessRequest();
?>
1 commentUsing Ajax across multiple domains
By Justin Silverton
XMLHttpRequest, the main component behind AJAX, does not automatically work across multiple domains. This means that you cannot make a request to an ovject on a domain that is different from the web page’s domain. There is an easy solution to this issue: apache’s mod_rewrite module.
Example
function getXMLHttpObject()
{
if (window.XMLHTTPRequest)
return new XMLHttpRequest();
else if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
else
return null;
}
function handleHTTPResponse()
{
if (http.readyState == 4) {
results = http.responseText;
}
}
var http = getXMLHttpObject();
http.open("POST"."http://www.yahoo.com/service");
http.onreadystatechange = handleHttpResponse;
The above example will fail with both Firefox and Internet Explorer (unless you are running it on a web page located on the yahoo domain). There are other ways to allow cross site ajax. Within Internet Exporer, the default security settings can be changed or a host can be added to the “trusted hosts” list. Firefox, on the other hand, has a concept called signed scripts. Both of these methods will not work for most websites on the Internet. This is because it would involve every user coming to your site adding your page to their trusted host list.
Apache setup
- Install apache with both mod_rewrite and proxy enabled.
- Create the following rule: RewriteRule ^/yahoo_proxy http://www.yahoo.com/service [P]
Note: The [P] indicates a pass-through proxy.
Replace the above line: (http.open("POST"."http://www.yahoo.com/service")) with
http.open("POST"."http://your_host/yahoo_proxy") and a connection will be made to the yahoo domains through your apache server while not violating the security restrictions of IE or Firefox.
1 commentHow to use the digg API
By Justin Silverton

This article will show you how to use the digg API using PHP. I have also written a library in PHP that maps all of the endpoints documented in the API to easily accessible functions (it is also compatible with PHP 4).
What can you do with the digg API?
- Get all popular stories submitted after January 1, 2007 sorted by promotion date
- Get the most recent 100 upcoming stories in the topic “Apple”
- Get the first 20 stories that were promoted on or after December 25, 2005
- Determine whether a story, identified by its URL, has been submitted to Digg and, if so, get details like the number of Diggs and comments it has received
- Get the details of a story, identified by its URL on Digg
- Get all stories submitted today from nytimes.com
- Get all stories submitted by Kevin Rose (or another Digger)
How it works
Requests are sent to the digg servers through URLS that are described in the API doc (here).
Here is an example:
http://services.digg.com/stories?appkey=http%3A%2F%2Fexample.com
This will return all stories. By default only 10 will be returned at a time (which can be increased to a maximum of 100). Also, you may notice an appkey=XXX argument. This is a unique identifier required by the digg servers. It is recommended to use the urlencoded refereral URL. Other return types are also available, which can make parsing easier depending on the language used.
response types:
- XML: Easily parsed in many languages on many platforms. It is particularly easy to use in Flash applications.
- JSON: May be directly eval’d in Javascript, and also can be parsed in many languages.
- Javascript: Useful as the source of a script tag, it passes JSON response to the Javascript callback function you specify.
- Serialized PHP: Easily unserialized in PHP to create objects, to which the programmer can attach custom methods. Or the programmer can directly access the response data through the public properties of the objects.
example:
http://services.digg.com/stories?appkey=http%3A%2F%2Fexample.com (will return XML by default)
http://services.digg.com/stories?appkey=http%3A%2F%2Fexample.com&type=json
http://services.digg.com/stories?appkey=http%3A%2F%2Fexample.com&type=php
http://services.digg.com/stories?appkey=http%3A%2F%2Fexample.com&type=javascript
Other basic arguments
- count
Number of events to retrieve.
Event count integer
Default: 10, Maximum: 100.
offset
Offset in complete events list.
Event offset integer.
Default: 0.
PHP code
The following is a function that will allow you to connect to the digg service and parse the results. It also will automatically generate the appid based on the current location of the script.
function connect($hostname) {
//this is an ID that is unique to your app. It is auto-generated, based on the calling URL
$appid = urlencode("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);
$host = $hostname."&appkey=".$appid;
echo $host;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL,$host);
curl_setopt ($ch,CURLOPT_USERAGENT,"Test library");
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,60);
$response = curl_exec ( $ch );
curl_close($ch);
return $response;
}
Download
The digg toolkit can be downloaded Here
1 commentA PHP compatible MD5 function in c#
By Justin Silverton
The following is a function written in c# that will return a PHP compatible MD5 hash of a file, given the name. The equivalent function in PHP is md5_file().
public string MD5Hash( string sFilePath )
{
try
{
MD5CryptoServiceProvider md5Provider
= new MD5CryptoServiceProvider();
FileStream fs
= new FileStream(sFilePath, FileMode.Open, FileAccess.Read);
Byte[] hashCode
= md5Provider.ComputeHash(fs);
string ret = "";
foreach (byte a in hashCode)
{
if (a<16)
ret += "0" + a.ToString ("x");
else
ret += a.ToString ("x");
}
fs.Close();
return ret;
}
catch( Exception ex )
{
throw ex;
}
}





