Wednesday, November 25, 2009

Issues with multiple requests on PHP

Again today I was answering questions on StackOverflow when I came across the question about not being able to load pages when downloading/loading large files.

If you are using session, I suggest you use session_write_close() before you output the file to the browser.

This is because when the session is opened on one page, you cannot load another page until the session has been written and released. session_write_close() is called automatically when your script ends, but because your outputting process takes time before your script end, your session file is locked and thus other pages cannot be viewed.

However, if you are using different browser and/or system, it will be ok because the session file locked is unique to each SESSION ID.

Look at: http://php.net/manual/en/function.session-write-close.php

However do take note that after session_write_close(), you cannot call session_start() or there will be a warning. Also if you make changes to $_SESSION, it will not take effect.

Monday, November 2, 2009

Getting value from an object (or instance of a class) in PHP 5

Just earlier on I was working on the String class in the Samstyle PHP Framework. I was glad that I read the PHP manual and found this magical method in PHP5 OOP called __toString().

Using __toString(), you can actually return a value for the object/instance of a class.

See the example below:

class MyClass{

  function __construct(){
    // constructor
  }

  function __toString(){
    // to String
    return 5;
  }

}

$inst = new MyClass();

echo $inst; // echos 5

How powerful!