Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
0

Handling POST Content-Length (PHP) Warning

I got problem when the file upload make the POST size exceed post_max_size setting.
I had disable the error report but the warning kept appearing.
Finally I found a solution.

In my case, I disabled all the PHP warning message using .htaccess.
To disable all errors from .htaccess use :
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
From http://ca2.php.net/manual/en/ini.core.php#ini.post-max-size
If the size of post data is greater than post_max_size, 
the $_POST and $_FILES superglobals are empty. 
This can be tracked in various ways, e.g. by passing
the $_GET variable to the script processing the data,
i.e. , and then checking if $_GET['processed'] is 
set.


Here is the example to handle it in PHP:
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
  return $this->returnErrorMessage("File size exceed limit !!!");
}

Source : 
1. http://stackoverflow.com/questions/12872515/php-warning-demolishes-json-response
2.http://stackoverflow.com/questions/2133652/how-to-gracefully-handle-files-that-exceed-phps-post-max-size
0

OCI_INVALID_HANDLE (ext\pdo_oci\oci_driver.c:579)

In my project, I need to pull data from Oracle Server.
I need to enable oci8 and PDO_OCI extensions but there is a problem since PHP couldn't find OCI.dll.
I had downloaded the oracle Instant Client, extract and copy the oci.dll file to windows folder and successfully enable the extension. But when I tried to connect to the server, PHP gave me this error message:

OCI_INVALID_HANDLE (ext\pdo_oci\oci_driver.c:579)

So, I take a look on oracle Instant Client installation manual. Actually, it's very simple solution.

How to solve :
  1. Set the variable ORACLE_HOME in the Windows environment setting  to the path of the extracted Oracle Instant Client folder.
  2. Restart Apache
It works.
0

GWT - PHP on Apache 3rd Review

Yesterday, on the GWT training session at PPK, Ilhamy (one of my internship student) told me he found another way to communicate GWT with PHP. Actually it's very simple solution without need to configure Apache.

In the solution, the project must located in /htdocs folder and compiler argument must be configured.

The original argument:

-remoteUI "${gwt_remote_ui_server_port}:${unique_id}" -startupUrl GWTPHP.html -logLevel INFO -codeServerPort 9997 -port 8888 -war C:\xampp\htdocs\GWTPHP\war com.vcari.jscadav2.Jscadav2_gwt

New configuration

-noserver -remoteUI "${gwt_remote_ui_server_port}:${unique_id}" -startupUrl http://localhost/GwtPhp/war/GWTPHP.html -logLevel INFO -codeServerPort 9997 -war C:\xampp\htdocs\GWTPHP\war com.peyotest.gwtphp.GWTPHP


Steps :
  1. add -noserver 
  2. change startup url from GWTPHP.html to full url http://localhost/GwtPhp/war/GWTPHP.html
  3. remove server port  -codeServerPort 9997 
The full article about this can be found here:
http://cambiatablog.wordpress.com/2010/11/22/gwt-developing-with-hosted-mode-and-phpxampp/
2

PHP Fatal error: date(): Timezone database is corrupt - this should *never* happen!

When I tried to execute a script that using date function on my Vortex, i got this error message.

"PHP Fatal error: date(): Timezone database is corrupt - this should *never* happen!".

Actually, this happened a long time ago, but only today I gave my efficient time tried to solve this problem. Luckily,I found the solution with just a few minutes.

Solution :

Make sure that web server(I'm using lighttpd on vortex) has enough access to read
/etc/localtime
/usr/share/zoneinfo

if localtime is not exist, you can copy the file from any Linux system.
0

PHP XML-RPC Client Simplified

In my previous for XML-RPC client helper, I suggested to create a client instance to make your methods exposed and developer friendly. But may be some of us are too lazy write all the wrapper code. There is solution for that.

In this case you still need to create client instance which extends XMLRPCClientHelper, but this time you don't need to write all the wrapper code. Just simply add __call overload methods.

It's easy but you need to remember the service API.

Here is the code:

<?php
class TestXMLRPCClientSimplified extends XMLRPCClientHelper {
    public function __call($name, $arguments) {
        return $this->sendRequest("$name", $arguments);
    }    
}
?>

0

PHP XML-RPC Client Helper

I wrote a helper for XMLRPC client.
I also added the automatic base64 type setting for bytes data.
Just need to create the client instance and supply the service URL, then you can start to call the service.

To make you client methods is expose and developer friendly, you can create your own client class which extends XMLRPCClientHelper.

<?php
class TestXMLRPCClient extends XMLRPCClientHelper {

    /**
     * Add two number
     * @param <int> $A
     * @param <int> $B
     * @return <int>
     */
    public function add($A, $B) {
        $params = array($A, $B);
        return $this->sendRequest("add", $params);
    }
}
?>


Here is the simple example :

$url = "http://192.168.56.1:5678/service.rem";
$client = new TestXMLRPCClient();
$client->setURL($url);
$result=$client->add(1,4);  //test add
print "Add Result: $result <br>\n";

It also support the exception when there is any error occurs it will throw the exception.So you just need to use try and catch to handle that.

XMLRPCClientHelper.php. This file also included in my training materials on my previous post.

<?php

/**
 * This helper class help to create a simple XML-RPC client
 * @author Mohamad Fairol Zamzuri B Che Sayut <mfz_peyo@yahoo.com>
 */
class XMLRPCClientHelper {

    private $url;

    /**
     * Get URL
     */
    public function getURL() {
        return $this->url;
    }

    /**
     * Set URL
     * @param <string> $url URL
     */
    public function setURL($url) {
        $this->url = $url;
    }

    /**
     * Send RPC request
     * @param <string> $methodname method name
     * @param <array> $parameters parameters
     */
    public function sendRequest($methodname, $parameters) {
        for ($i = 0; $i < count($parameters); $i++) {
            if (mb_detect_encoding($parameters[$i]) === false) {
                xmlrpc_set_type(&$parameters[$i], "base64");
            }
        }
        $request = xmlrpc_encode_request($methodname, $parameters);
        $context = stream_context_create(array('http' => array(
                        'method' => "POST",
                        'header' => "Content-Type: text/xml",
                        'content' => $request
                        )));
        $file = file_get_contents($this->url, false, $context);
        $response = xmlrpc_decode($file);
        if (is_array($response) && xmlrpc_is_fault($response)) {
            throw new Exception($response['faultString'], $response['faultCode']);
        }
        return $response;
    }

}

?>

0

PHP XML-RPC Server Helper

I wrote a XMLRPCServerHelper to help me to create XML-RPC service in PHP.
It's easy to use and you just need to set the classname of service and all the methods will be extracted automatically using ReflectionClass.

The example of the server :

<?php
error_reporting(E_ERROR | E_PARSE);
require_once("autoload.php");

$server = new XMLRPCServerHelper();
$server->setClassName("TestXMLRPCService");
$answer = $server->handle();
header('Content-Type: text/xml');
print($answer);
?>


The service can be access from your normal webserver url.
To generate php client class, just simply add ?phpwrapper to the url. E.g :

 http://localhost/xmlrpc/server.php?phpwrapper


XMLRPCServerHelper.php . This file also incuded in my training materials on my previous post.

<?php

/**
 * This helper class help to create XML-RPC server
 */
class XMLRPCServerHelper {

    /**
     * Server handler holder
     * @var <Object> Server handler holder
     */
    private $serverHandler;
    /**
     * Class name holder
     * @var <string> Class name holder
     */
    private $classname;
    /**
     * External function list holder
     * @var <array>  External function list holder
     */
    private $externalFunctions;

    /**
     * Contructor
     */
    public function __construct() {
        $this->serverHandler = xmlrpc_server_create();
        $this->externalFunctions = array();
    }

    /**
     * Set object class.
     * All class methods will be extracted and registerd automatically
     * @param <Object> $class
     */
    public function setClassName($classname) {
        $this->classname = $classname;
        $reflection = new ReflectionClass($classname);
        $methods = $reflection->getMethods();
        $props = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
        for ($i = 0; $i < count($methods); $i++) {
            $reflectmethod = $methods[$i];
            $methodname = $reflectmethod->name;
            $reflectparams = $reflectmethod->getParameters();
            if (count($reflectparams) > 0) {
                for ($j = 0; $j < count($reflectparams); $j++) {
                    $methodparams[] = $reflectparams[$j]->name;
                }
            } else {
                $methodparams = array();
            }
            $this->registerMethod($methodname, array(&$classname, $methodname), $methodparams);
        }
    }

    /**
     * Generate client wrapper
     */
    private function generatePHPClientWrapper() {
        $classfunctions = "";
        $reflection = new ReflectionClass($this->classname);
        $methods = $reflection->getMethods();
        $props = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
        for ($i = 0; $i < count($methods); $i++) {
            $reflectmethod = $methods[$i];
            $methodname = $reflectmethod->name;
            $reflectparams = $reflectmethod->getParameters();
            $funcParams = "";
            $funcContent = "";
            if (count($reflectparams) > 0) {
                for ($j = 0; $j < count($reflectparams); $j++) {
                    //$funcContent.= "\$params[] = \$" . $reflectparams[$j]->name . ";\n";
                    if ($funcParams != "") {
                        $funcParams.=",";
                    }
                    $funcParams.='$' . $reflectparams[$j]->name;
                }
                $funcContent = "\$params = array($funcParams);\n";
            } else {
                $funcContent = "\$params = array();\n";
            }

            $classfunctions.="public function $methodname($funcParams) {\n";
            $classfunctions.=$funcContent;
            $classfunctions.="return \$this->sendRequest(\"$methodname\", \$params);\n";
            $classfunctions.="}\n\n";
        }

        $wrapper = "<pre>class " . $this->classname . "XMLRPCClient extends XMLRPCClientHelper {\n";
        $wrapper .= "$classfunctions";
        $wrapper .= "}\n</pre>";
        return $wrapper;
    }

    /**
     * Register method
     * @param <string> $externalName class name
     * @param <Object> $function class pointer
     * @param <array> $parameterNames parameters name
     */
    public function registerMethod($externalName, $function, $parameterNames) {
        if ($function == null) {
            $function = $externalName;
        }
        xmlrpc_server_register_method($this->serverHandler, $externalName, array(&$this, 'callMethod'));
        $this->externalFunctions[$externalName] = array('function' => $function, 'parameterNames' => $parameterNames);
    }

    /**
     * Invoke class method
     * @param <string> $functionName method name
     * @param <array> $parametersFromRequest parameters
     * @return <variant> function call result
     */
    public function callMethod($functionName, $parametersFromRequest) {
        if ($functionName == "generatePHPClientWrapper") {
            return $this->generatePHPClientWrapper();
        }

        $function = $this->externalFunctions[$functionName]['function'];
        $parameterNames = $this->externalFunctions[$functionName]['parameterNames'];
        return call_user_func_array($function, $parametersFromRequest);
    }

    /**
     * Handle server call
     * @return <variant>  function call result
     */
    public function handle() {
        $bWrapper = false;
        foreach ($_GET as $key => $value) {
            if ($key == "phpwrapper") {
                $bWrapper = true;
                continue;
            }
        }

        if ($bWrapper) {
            print $this->generatePHPClientWrapper();
            exit();
        }
        return xmlrpc_server_call_method($this->serverHandler, file_get_contents('php://input'), null);
    }

}

?>

XMLRPC Training (C# and PHP)

Today, I'm going to conduct a simple training on XML-RPC at my previous company.
You can access to the training materials on my googleDocs.


Presentation Slide
PHP source code
C# source code
0

PHP Simple Auto Load

Just wanna share my PHP autoload function.
In my application, I have several types of classes and may located in different folder such as :
  • Helper
  • Model
  • Component
  • Web Service
  • etc
The easiest way to use the classes is to create an auto load function so the classes file will be included automatically.

Hope this could be useful to you too.
<?php
/**
 * Auto function
 * @param <string> $classname class name
 * @return <void> void
 */
function __autoload($classname) {
    global $global_helper_path;
    global $global_model_path;
    global $global_component_path;
    global $global_wsobject_path;

    //load helper
    $pos = strrpos($classname, "Helper");
    if ($pos === false) { // note: three equal signs
    } else {
        //print $classname;
        $filepath = "$global_helper_path/$classname.php";
        require_once "$filepath";
        return;
    }

    // load component
    $pos = strrpos($classname, "com_");
    if ($pos === false) { // note: three equal signs
    } elseif ($pos == 0) {
        $filepath = "$global_component_path/$classname/$classname.php";
        require_once "$filepath";
        return;
    }

    // load database driver
    $pos = strrpos($classname, "DB");
    if ($pos === false) { // note: three equal signs
    } elseif ($pos == 0) {
        $filepath = "$global_helper_path/database/$classname.php";
        require_once "$filepath";
        return;
    }

    // load model
    $pos = strrpos($classname, "Model");
    if ($pos === false) { // note: three equal signs
    } else {
        $filepath = "$global_model_path/$classname.php";
        require_once "$filepath";
        return;
    }

    // load webservice class
    $pos = strrpos($classname, "WS");
    if ($pos === false) { // note: three equal signs
    } elseif ($pos == 0) {
        $filepath = "$global_wsobject_path/$classname.php";
        require_once "$filepath";
        return;
    }
}

?>

0

PHP Web Service Library

I gave a look on my PHP web service class. It's quite hard to extends and create a new web service application. I search on Google and found several open source projects and gave them a test.

I found "php-webservice-class" is the best since the implementation is simple,easy and fully commented. It also use ReflectionClass, makes the code simpler without need to create phpDoc parser to get your parameter settings.

The project url:
http://code.google.com/p/php-webservice-class/


Update on 28th Feb 2011

The wsdl output is not standard. :(
You can't call the web service from other language.
I'm considering to use David Kingma library (my old library also based on his work) for replacement.
0

HTML Doc PHP Implementation

I want to use PDF in my project to print the report. Currently my report is in HTML format since it is easy to generate using PHP. Before this, I have try to use DOMPDF and TCPDF, but unfortunately, there is a lot of customization need to be done to get a good PDF report.
Finally, I found HTMLDoc. It's open source but to get the compiled-ready binary you need to buy.
Fortunately. I found the free compiled binary here :

http://htmldoc-binaries.org/

Download and install HTMLDoc.
 public function topdf($filename, $options = "") {

$path = "library_includes/general/htmldoc/htmldoc.exe";
$path=realpath($path);
# Tell HTMLDOC not to run in CGI mode...
putenv("HTMLDOC_NOCGI=1");

$scmd = "$path -t pdf --quiet --landscape --jpeg --webpage --header ... $options $filename";
# Write the content type to the client...
header("Content-Type: application/pdf");
flush();
system($scmd);
}
Just submit your URL / file name and the HTMdoc will will create the PDF on the fly.
For more details about the command line, you can refer be to the document :

http://www.easysw.com/htmldoc/docfiles/8-cmdref.html

But, if your url is password protected using login and session, you need to handle to bypass the session checking since HTMLDoc read the url and PHP will treat HTMLDoc as new session rather than your current.
1

Lighttpd PHP File Upload - Error 413 request entity is too large

I'm having problem with PHP File upload running on lighttpd web server deployed on my VortexSX86. Lighttpd keep giving me the 413 error message ( 413 request entity is tool large)

Open /etc/lighttd/lighttpd.conf change the following parameters :
server.max-request-size=100000000     # or whatever you want max file size to be
server.upload-dirs=( "/mnt" ) # location to place the uploaded file
# probably should be the same as php.ini
server.network-backend="write" # this one was the key one for me

if the value of "write" doesn't work, try "writev".

server.network-backend="write" or server.network-backend="writev"
Make sure the upload directory is exist and writable.
Done.
0

GWT-Ext & PHP , Glassfish & Apache

Berikut cara macam mana nak guna GWT-Ext dalam Galssfish dan data dalam Apache-PHP.

1. Install Quercus. Ni carik post aku sebelum ni.
2. Create gateway script dalam glassfish (php-Quercus). Nama fail sebaiknya sama dengan nama fail dalam apache (php).

Fail scriptnya adalah seperti di bawah. Support untuk GET, POST & SESSION.


// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://localhost/adapt-gwt/index.php");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);

// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
0

Install quercus -100% Java implementation of the PHP

Berikut adalah cara-cara untuk install quercus.

1. Download fail .war dari web http://quercus.caucho.com/
2. Deploy fail .war dalam glassfish.
3. Extract fail .war dan copy semua fail .jar dalam folder /WEBINF/lib/ ke folder GLASSFISH_HOME/domains/domain/lib.
4. Tambah servlet & mapping dalam web.xml


<servlet>

<servlet-name>Quercus Servlet</servlet-name>

<servlet-class>com.caucho.quercus.servlet.QuercusServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Quercus Servlet</servlet-name>

<url-pattern>*.php</url-pattern>

</servlet-mapping>



6. create fail index.php dan deploy.
7. Try access fail php dari web browser.
0

GWT-Ext dengan PHP

Oleh kerana aplikasi GWT-Ext perlu menggunakan JAVA, agak susah untuk menggunakan data dari domain yang berlainan. Contohnya :

GWT -Glassfish guna port 16476.
PHP-Apache guna port 80.

Terdapat 2 cara untuk menggunakan php.
1. Install quercus -100% Java implementation of the PHP dan guna quercus ni saja.
2. Install quercus -100% Java implementation of the PHP dan guna PHP pada apache web server pada port 80. Kena pakai CURL.
 
Copyright © peyotest