Difference between revisions of "Short Notes on PHP"

From PaskvilWiki
Jump to: navigation, search
(Created page with "== Convert Accented Characters to Non-Accented == <pre>setlocale(LC_ALL, "en_US.utf8"); $translit = iconv("utf-8", "us-ascii//TRANSLIT", $_GET['orig_name']);</pre> '''Note''': ...")
 
(Disconnect Client and Continue Processing)
 
(2 intermediate revisions by one user not shown)
Line 27: Line 27:
 
     // if $response === false, something went wrong
 
     // if $response === false, something went wrong
 
?></pre>
 
?></pre>
 +
 +
== HTTP Post in Pure PHP (without cURL) ==
 +
 +
<pre>$data = array('param1' => '1', 'param2' => '2');
 +
$_data = http_build_query($data);
 +
$options = array
 +
(
 +
    'http' => array
 +
    (
 +
        'method' => 'POST',
 +
        'header' => "Content-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($_data)."\r\n",
 +
        'content' => $_data
 +
    )
 +
);
 +
$context = stream_context_create($options);
 +
$data = @file_get_contents('http://www.example.com/post', 0, $context);</pre>
 +
 +
For more information see: [http://www.php.net/manual/en/function.http-build-query.php http_build_query()], [http://www.php.net/manual/en/function.stream-context-create.php stream_context_create()], [http://www.php.net/manual/en/function.file-get-contents.php file_get_contents()].
 +
 +
== Prevent Client Disconnect from Killing PHP ==
 +
 +
When client aborts the request (typically "Stop" button in browser), the PHP script is killed. To prevent this, just call
 +
 +
<pre>ignore_user_abort(true);</pre>
 +
 +
Note that your script still can be killed by timeout. You might want to set
 +
 +
<pre>set_time_limit(0);</pre>
 +
 +
== Disconnect Client and Continue Processing ==
 +
 +
Sometimes you need to do something time consuming in the PHP script being called, but you don't want to keep client "hanging".
 +
 +
Just use the following "idiom" (''note - if you're having problems with output being truncated, see below''):
 +
 +
<pre>set_time_limit(0);                  // don't let the time limit us ...
 +
ignore_user_abort(true);            // ... and the user kill us
 +
if (!ob_start('ob_gzhandler'))      // try to compress the output ...
 +
    ob_start();                    // ... or just make it raw
 +
 +
// ... 'echo' any response to client ...
 +
 +
header('Content-Length: '.ob_get_length());
 +
header('Connection: close');        // browser will know to close the connection
 +
 +
// flush everything
 +
ob_end_flush();
 +
ob_flush();
 +
flush();
 +
 +
// close current session if necessary
 +
if (session_id())
 +
    session_write_close();
 +
// if run as CGI, you need to also:
 +
if (is_callable('fastcgi_finish_request'))
 +
    fastcgi_finish_request();
 +
 +
// ... from here on, you're on your own ... process to your liking ...</pre>
 +
 +
''Update'': sometimes there seems to be a problem with <tt>ob_get_length()</tt> not returning the full length. Typically I prefer to use double caching - one for contents, and one for output:
 +
 +
<pre>set_time_limit(0);                  // don't let the time limit us ...
 +
ignore_user_abort(true);            // ... and the user kill us
 +
ob_start();                        // outer 'ob' to cache the full gzip
 +
if (!ob_start('ob_gzhandler'))      // inner 'ob' to catch the data; try to gzip
 +
    ob_start();
 +
 +
// ... 'echo' any response to client ...
 +
 +
ob_end_flush();                    // flush the inner 'ob' into the outer 'ob'
 +
 +
header('Content-Length: '.ob_get_length());  // now the ob_get_length() should return correct value
 +
header('Connection: close');        // browser will know to close the connection
 +
 +
ob_end_flush();                    // flush the outer 'ob'
 +
ob_flush();
 +
flush();
 +
 +
// close current session if necessary
 +
if (session_id())
 +
    session_write_close();
 +
// if run as CGI, you need to also:
 +
if (is_callable('fastcgi_finish_request'))
 +
    fastcgi_finish_request();
 +
 +
// ... from here on, you're on your own ... process to your liking ...</pre>

Latest revision as of 11:42, 21 January 2013

Convert Accented Characters to Non-Accented

setlocale(LC_ALL, "en_US.utf8");
$translit = iconv("utf-8", "us-ascii//TRANSLIT", $_GET['orig_name']);

Note: On *nix systems, you can check for supported locales using `locale -a`.

Note: Instead of hard-coding the locale to use, you could also use values of HTTP_ACCEPT_LANGUAGE and HTTP_ACCEPT_CHARSET, sent by the browser, to tailor the input locale.

Upload a File using cURL

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
    curl_setopt($ch, CURLOPT_POST, true);
    // same as <input type="file" name="file_box">
    // notice the '@' ahead of the path!
    $post = array(
        "file_box"=>"@/path/to/myfile.jpg",
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
    $response = curl_exec($ch);
    // if $response === false, something went wrong
?>

HTTP Post in Pure PHP (without cURL)

$data = array('param1' => '1', 'param2' => '2');
$_data = http_build_query($data);
$options = array
(
    'http' => array
    (
        'method' => 'POST',
        'header' => "Content-type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($_data)."\r\n",
        'content' => $_data
    )
);
$context = stream_context_create($options);
$data = @file_get_contents('http://www.example.com/post', 0, $context);

For more information see: http_build_query(), stream_context_create(), file_get_contents().

Prevent Client Disconnect from Killing PHP

When client aborts the request (typically "Stop" button in browser), the PHP script is killed. To prevent this, just call

ignore_user_abort(true);

Note that your script still can be killed by timeout. You might want to set

set_time_limit(0);

Disconnect Client and Continue Processing

Sometimes you need to do something time consuming in the PHP script being called, but you don't want to keep client "hanging".

Just use the following "idiom" (note - if you're having problems with output being truncated, see below):

set_time_limit(0);                  // don't let the time limit us ...
ignore_user_abort(true);            // ... and the user kill us
if (!ob_start('ob_gzhandler'))      // try to compress the output ...
    ob_start();                     // ... or just make it raw

// ... 'echo' any response to client ...

header('Content-Length: '.ob_get_length());
header('Connection: close');        // browser will know to close the connection

// flush everything
ob_end_flush();
ob_flush();
flush();

// close current session if necessary
if (session_id())
    session_write_close();
// if run as CGI, you need to also:
if (is_callable('fastcgi_finish_request'))
    fastcgi_finish_request();

// ... from here on, you're on your own ... process to your liking ...

Update: sometimes there seems to be a problem with ob_get_length() not returning the full length. Typically I prefer to use double caching - one for contents, and one for output:

set_time_limit(0);                  // don't let the time limit us ...
ignore_user_abort(true);            // ... and the user kill us
ob_start();                         // outer 'ob' to cache the full gzip
if (!ob_start('ob_gzhandler'))      // inner 'ob' to catch the data; try to gzip
    ob_start();

// ... 'echo' any response to client ...

ob_end_flush();                     // flush the inner 'ob' into the outer 'ob'

header('Content-Length: '.ob_get_length());  // now the ob_get_length() should return correct value
header('Connection: close');        // browser will know to close the connection

ob_end_flush();                     // flush the outer 'ob'
ob_flush();
flush();

// close current session if necessary
if (session_id())
    session_write_close();
// if run as CGI, you need to also:
if (is_callable('fastcgi_finish_request'))
    fastcgi_finish_request();

// ... from here on, you're on your own ... process to your liking ...