Archive for the ‘PHP’ Category
Tuesday, July 1st, 2008
A variable variable looks like this: $$var
So, if $var = ‘foo’ and $foo = ‘bar’ then $$var would contain the value ‘bar’ because $$var can be
thought of as $’foo’ which is simply $foo which has the value ‘bar’.
Variable variables sound like a cryptic a useless concept, but they can be useful sometimes. For
example, if we have a configuration file consisting of configuration directives and values in this
format:
foo=bar
abc=123
Then it is very easy to read this file and create corresponding variables:
<?php
$fp = fopen(’config.txt’,'r’);
while(true) {
$line = fgets($fp,80);
if(!feof($fp)) {
if($line[0]==’#’ || strlen($line)<2) continue;
list($name,$val)=explode(’=',$line,2);
$$name=trim($val);
} else break;
}
fclose($fp);
?>
Along the same lines as variable variables, you can create compound variables and variable
functions.
<?php
$str = ‘var’;
$var_toaster = “Hello World”;
echo ${$str.’_toaster’};
$str(); // Calls a function named var()
${$str.’_abc’}(); // Calls a function named var_abc()
?>
Tags: configuration, consisting, corresponding, cryptic, easy, example, format, functions, PHP, read, trim, useful, values, variable, variables
Posted in PHP | 1 Comment »
Tuesday, July 1st, 2008
PHP maintains a connection status bitfield with 3 bits:
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
By default a PHP script is terminated when the connection to the client is broken and the ABORTED
bit is turned on. This can be changed using the ignore_user_abort() function. The TIMEOUT bit is
set when the script timelimit is exceed. This timelimit can be set using set_time_limit().
<?php
set_time_limit(0);
ignore_user_abort(true);
/* code which will always run to completion */
?>
You can call connection_status() to check on the status of a connection.
<?php
ignore_user_abort(true);
echo “some output”;
if(connection_status()==0) {
// Code that only runs when the connection is still alive
} else {
// Code that only runs on an abort
}
?>
You can also register a function which will be called at the end of the script no matter how the script
was terminated.
<?php
function foo() {
if(connection_status() & 1)
error_log(”Connection Aborted”,0);
if(connection_status() & 2)
error_log(”Connection Timed Out”,0);
if(!connection_status())
error_log(”Normal Exit”,0);
}
register_shutdown_function(’foo’);
?>
Tags: Client, Connection, Handling, PHP, register, Script, Timed Out, timelimit, timeout, True
Posted in PHP | No Comments »
Tuesday, July 1st, 2008
When a keep-alive request is granted the established socket is kept open after each keep-alive
response. Note that a keep-alive response is only possible when the response includes a
content-length header.
request 1
request 2
request 3
request 4
20 bytes
120 bytes
60 bytes
?? bytes
You cannot rely on the keep-alive feature for any sort of application-level session state maintenance.
Using Output Buffering to get content-length
<?php
ob_start();
echo “Your Data”;
$l = ob_get_length();
Header(”Content-length: $l”);
ob_end_flush();
?>
You will have to weigh the trade-off between the extra cpu and memory that output buffering takes
against the increased effciency of being able to use keep-alive connections for your dynamic pages.
Tags: Alive, CPU, effciency, established, header, includes, Keep, PHP, REQUEST, response, socket
Posted in PHP | No Comments »
Monday, June 30th, 2008
Client/Server Request/Response
HTTP is a simple client/server protocol with stateless request/response sequences.
The Client HTTP Request
7 possible HTTP 1.1 request types: GET, PUT, POST, DELETE, HEAD, OPTIONS and TRACE.
Any number of HTTP headers can accompany a request.
GET /filename.php HTTP/1.0
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
Accept-Charset: iso-8859-1,*,utf-8
Accept-Encoding: gzip
Accept-Language: en
Connection: Keep-Alive
Host: localhost
User-Agent: Mozilla/4.77 [en] (X11; U; Linux 2.4.5-pre4 i686; Nav)
The Server HTTP Response
HTTP/1.1 200 OK
Date: Mon, 21 May 2001 17:01:51 GMT
Server: Apache/1.3.20-dev (Unix) PHP/4.0.7-dev
Last-Modified: Fri, 26 Jan 2001 06:08:38 GMT
ETag: “503d3-50-3a711466″
Accept-Ranges: bytes
Content-Length: 80
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html
Tags: Client, Connection, Delete, get, HEAD, HTTP, Image, Linux, localhost, Options, PHP, post, PUT, REQUEST, response, server, Text, Trace
Posted in PHP | No Comments »
Monday, June 30th, 2008
Problem
Short expiry cookies depend on users having their system clocks set correctly.
Solution
Don’t depend on the users having their clocks set right. Embed the timeout based on your server’s
clock in the cookie.
<?php
$value = time()+3600 . ‘:’ . $variable;
SetCookie(’Cookie_Name’,$value);
?>
Then when you receive the cookie, decode it and determine if it is still valid.
<?php
list($ts,$variable) = explode(’:',$Cookie_Name,2);
if($ts < time()) {
…
} else {
SetCookie(’Cookie_Name’,”);
}
?>
Tags: clocks, cookie, Expiry, explode, PHP, problem, SetCookie, solution, timeout
Posted in PHP | No Comments »
Monday, June 30th, 2008
Problem
You need PHP’s built-in ftp functions for the ultra-cool script you are writing, but your service
provider does not have PHP compiled with the –enable-ftp option.
Solution
If you have a shell account on a system with the same operating system as your web server, grab the
PHP source tarball and build using:
–with-apxs –enable-ftp=shared
You can check which flags your provider used by putting a phpinfo() call in a script on your server.
<?phpinfo()?>
Once compiled, you will find a “modules/ftp.so” file which you can copy to your web server and
enable either by putting:
extension=ftp.so
in your php.ini file or by adding this to the top of your script:
<?php dl(”ftp.so”) ?>
Tags: Adding, compiled, cool, extension, flags, FTP, functions, PHP, phpinfo, problem, provider, Script, server, service, solution
Posted in PHP | No Comments »
Monday, June 30th, 2008
$today = getdate();
$month = $today['month'];
$mday = $today['mday'];
$year = $today['year'];
Tags: date, getdate, PHP, Today
Posted in PHP | No Comments »
Monday, June 30th, 2008
if (!($HTTPS == “on”)) {
header (”Location: https://$SERVER_NAME$php_SELF”);
exit;
}
Tags: Connection, Force, HTTP, HTTPS, location, PHP, secure
Posted in PHP | No Comments »
Monday, June 30th, 2008
Compositional programming style
In the object oriented programming style, it’s preferable to split functionality out to multiple objects, that can work together to solve a single task. Taken to the extreme, this results in more, but smaller, classes and generally relies less on inheritance and more on composition. In lack of better words, I’ll call this compositional programming style. It’s a style which is usually more prevalent with experienced programmers.
For someone coming from an imperative style of programming, this style can appear abstract and confusing, but the benefits are in the flexibility of the code. If different objects are related through composition, parts can be replaced, without changing the code. This makes it easier to reuse components, and to hook into the code, by providing a wrapper here or there. This is especially useful during testing, since it becomes easier to mock out external dependencies (Such as a database or an smtp server).
There is, however, a dark side to composition — dependencies.
So what is a dependency?
For the sake of this post, I’ll use a rather naïve example. Assume, that we were building an addressbook application. This would feature an entity of type Person. In our code, we might have a class …
Tags: abstract, composition, confusing, dealing, dependencies, experienced, external, functionality, Multiple, PHP, Programming, smtp server, Style, wrapper
Posted in PHP | No Comments »
Monday, June 30th, 2008
The Drupal development team surprised everyone when they released version 6.0 last week, ahead of schedule.
After one year of development we are ready to release Drupal 6.0 to the world. Thanks to the tireless work of the Drupal community, over 1,600 issues have been resolved during the Drupal 6.0 release cycle. These changes are evident in Drupal 6’s major usability improvements, security and maintainability advancements, friendlier installer, and expanded development framework. Further, from bug fix to feature request, these issues follow-through on the Drupal project’s continued commitment to deliver flexibility and power to themers and developers.
While I haven’t used Drupal on any major projects, I got to see it in action in the FullCodePress international site-in-a-day competition last year, when the Australian team chose it to power their charity’s site. And when I attended Drupal MiniCon here in Melbourne a couple of weeks ago, a recurring theme was that the installer needed to be friendlier for first time users.
I’m happy to report that, with the version 6.0 release, getting Drupal up and running is as easy as it should be, and the Lullabot team have prepared an excellent screencast (MP4, 12 minutes, 38.5 MB) that anticipates …
Tags: commitment, development, Drupal, excellent, PHP, project’s, Released, time users, weeks
Posted in PHP | No Comments »