Thursday, August 22, 2013

Using php execute command/run another php file wihtout waiting for result

<?php
session_start();
$_SESSION["student_name"] = "Pritom Kumar Mondal";

$_SESSION["roll"] = "College: 2150, Varsity: 060238";
echo "Start time: " date('h:i:s');
$phpCommandLocation "C:\\xampp\\php\\php.exe";
$phpFileLocation    "C:\\xampp\\htdocs\\test1\\call.php";
$logLocation        "C:\\tmp\\result.log";
$argvList = " session_id=".session_id(); /*You can send session id*/ 
$argvList.= " name=".rawurlencode("Pritom Kumar Mondal");
$command            $phpCommandLocation " -f "           .
    $phpFileLocation . $argvList " 1>>" $logLocation " 2>&1 &"; 
pclose(popen("start /B " $command"r"));
echo 
"<BR>End time: " date('h:i:s'); 

?>

And output is:
Start time: 11:07:26
End time: 11:07:26

And call.php looks like:
<?php
foreach($argv as $argvString) {
    $argvStringList = explode("=", $argvString);
    if($argvStringList[0] == "session_id") {
        session_id($argvStringList[1]);
        session_start();

        /* Start session with received session id, BINGO... */
    }
}
$string 
"\r\n-------------------------------\r\nStart time: " date('h:i:s'); 

$string .= "\r\nStart sleeping for 5 seconds."; 
sleep(5); 
$string .= "\r\nEnd time: " date('h:i:s');
 file_put_contents("data.txt" 
    "SOMETHING WENT GOOD...................\r\n" 
    $string);
echo 
$string; 

echo "\r\nReceived argv list: ";
print_r($argv); /* Printing argv as array */
echo "\r\nPrevious index.php session variables in currently executed php: ";
print_r($_SESSION); /* Printing argv as array */
?>
Yellow background showing that this script wait for 5 seconds.

The C:\\tmp\\result.log is:
-------------------------------
Start time: 11:07:28
Start sleeping for 5 seconds.

End time: 11:07:33
Received argv list: 
Array
(
    [0] => C:\xampp\htdocs\test1\call.php
    [1] => session_id=gjbf54ql8dhuvg0njsgt4hh8n7
    [2] => name=Pritom%20Kumar%20Mondal%2C%20Roll%3D2525

Previous index.php session variables in currently executed php:
Array
(
    [
student_name] => Pritom Kumar Mondal
    [roll] => College: 2150, Varsity: 060238
)


There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'result.log' file

If you use linux operating system just write:
<?php
exec
($command " > /dev/null &"); 

?>

Asynchronous cURL Requests

A possibly underused technique available to PHP developers is the ability to spawn a background PHP script without JavaScript. All you need to do this is the cURL library and a few lines of code. Let me explain, suppose you have a script that is going to take minutes (or longer) to run, you don’t want to sit looking at a blank screen, and your users certainly won’t! In this kind of scenario you can separate out that logic to a background file and leave your view free for other things, perhaps to query the database to see how the background process is doing?
All you need to do to set this off is use the following code (entering your own url):
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_NOBODY, true); 

curl_exec($ch);
curl_close($ch);
There is an irritating 1 second delay for this to finish, but this cannot be helped (so far as I am aware!)
Remember to be careful with this technique (especially if you turn off script timeout etc) and build in a control to stop the script should you need to (database query every minute? or a lock file?)
Enjoy!

Update

It has been pointed out to me that on modern systems (cURL 7.16.2 or higher and PHP 5.2.3 or above) you can use a millisecond option to reduce the delay effectively to zero.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://www.yoursite.com/background-script.php');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1);
curl_setopt($ch, CURLOPT_NOBODY, true);

curl_exec($ch);
curl_close($ch);

Monday, August 19, 2013

How can I upload files asynchronously with jQuery


With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress eventwith the HTML5 progress tag (or a div).

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

<div class="progress_bar"
     style="width: 300px; height: 20px; background-color: blue; position: relative;">
    <div class="full" style="width: 0%;
    height: 20px; background-color: red;"></div>
    <div class="text"
         style="color: #ffffff; font-weight: bold; text-align: center;
         position: absolute; left: 109px; top: 0;">Uploading...</div>
</div>
<script type="text/javascript">
    jQuery(document).ready(function() {
        $(':button').click(function(){
            var formData = new FormData($('form')[0]);
            $.ajax({
                url: 'upload.php',  //Server script to process data
                type: 'POST',
                xhr: function() {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){ // Check if upload property exists
                        myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function() {
                    console.log("Before send...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.full").css({
                        width: "0%"
                    });
                },
                success: function(data) {
                    console.log(data);
                    console.log("Success...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.text").html("Uploaded.");
                },
                error: function() {
                    console.log("Error...");
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });
    function progressHandlingFunction(e){
        console.log(e);
        if(e.lengthComputable){
            var $div = jQuery("div.progress_bar");
            var p = e.loaded / e.total * 100;
            $div.find("div.full").css({
                width: p + "%"
            });
            console.log(p);
        }
    }
</script>


As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser. 

Downloading a Remote File With cURL and PHP

cURL is a great tool to help you connect to remote web sites, making it easy to post forms, retrieve web pages, or even to download files. In this PhpRiot Snippet I'll show you how you can download a file straight to disk using cURL.
Note: To simplify our key points in this article we don't perform any error checking on the cURL requests. You should always do so; the curl_getinfo function is extremely useful for this.
If you use basic options when executing a cURL request, the returned data will be output directly. If instead you want to assign the response to a PHP variable you would specify the CURLOPT_RETURNTRANSFER option.
You can then read the response and write it to disk, as shown in the following listing. The $path variable is the location on the server where you want to write the file.
Listing 1 Downloading a file and saving it with file_put_contents() (listing-1.php)
<?php 
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
 
    file_put_contents($path, $data);
?>
There is however a problem with this code. If the file you're downloading is quite large, the entire contents must be read into memory before being written to disk. Doing so can result in your script breaking down due to exceeding the memory limit.
Note: Even if your memory limit is set extremely high, you would be putting unnecessary strain on your server by reading in a large file straight to memory.
Therefore, you should let cURL do the hard work by passing to it a writable file stream. You can do this using the CURLOPT_FILE option.
Note: Because we'll be writing to a file you no longer specify the CURLOPT_RETURNTRANSFER option.
To do this you must first create a new file pointer using fopen(). Next we pass this file pointer to cURL and perform the request. Finally, we close the file pointer.
Listing 2 Using cURL to download straight to a file stream (listing-2.php)
<?php     
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $fp = fopen($path, 'w');
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
    fclose($fp);
?>
That's all there is to it. You can now download files without worrying about exceeding PHP's memory limit.

PHP Script to force download big files using chunk

<?php
$file 
dirname(__FILE__) . "/download_it.zip";
if (
file_exists($file)) {
    if (
FALSE !== ($handler fopen($file'r'))) {
        
header('Content-Description: File Transfer');
        
header('Content-Type: application/octet-stream');
        
header('Content-Disposition: attachment; filename=' basename($file));
        
header('Content-Transfer-Encoding: chunked'); //changed to chunked
        
header('Expires: 0');
        
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        
header('Pragma: public');
      
        
//Send the content in chunks
        
while (false !== ($chunk fread($handler4096))) {
            echo 
$chunk;
        }
    }
    exit;
}
echo 
"<h1>Content error</h1><p>The file does not exist!</p>";?>

Thursday, August 15, 2013

Save PHP Array Data as Formatted XML and Parse Again

<?php 
include 'xml_converter.class.php'; /* Download class file */

include 'xml.class.php';           /* Download class file */
 

/* Your array of data */ 
$data = array(
    
'first_name' => 'Pritom',
    
'middle_name' => "Kumar",
    
'last_name' => 'Mondal',
    
'url' => 'http://pritomkumar.blogspot.com',
    
'languages' => array(
        
'php language !! ' => '<!CDATA[&Php&amp;]]>%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇',
        
'Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨',
        
'Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐',
        
'CSS',
        
"CakePhp<Help]>]]\/\/\/\/\/\/",
        
"jQuery"
    
),
    
'title' => 'Pritom Kumar (Web Developer)',
    
"inline_tag" => "<name><first>Pritom</first><last>Kumar</last></name>",
    
'favorite_blogs' => array(
        
'CSSTricks' => 'http://css-tricks.com',
        
'AJAXian' => 'http://ajaxian.com'
    
),
    
"invalid characters" => array(
        
"''" => "00-&*",
        
"'" => "&#39;",
        
">" => "&#62;",
        
"<" => "&#60;",
        
"&" => "&#38;",
        
"-" => "&#45;",
        
"°" => "&#176;"
    
)
);

 /* Array to xml converting... */ 

$xmlConverter = new XmlConverter($data); 

$xmlString    $xmlConverter->toXmlString();

/* Xml would look like this: */ 
echo $xmlString;


<?xml version="1.0" encoding="UTF-8"?>
<data>
   <first_name><![CDATA[Pritom]]></first_name>
   <middle_name><![CDATA[Kumar]]></middle_name>
   <last_name><![CDATA[Mondal]]></last_name>
   <url><![CDATA[http://pritomkumar.blogspot.com]]></url>
   <languages>
      <php_language____><![CDATA[<!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊⟩⟨ ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇]]></php_language____>
      <tag_0><![CDATA[Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨]]></tag_0>
      <tag_1><![CDATA[Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐]]></tag_1>
      <tag_2><![CDATA[CSS]]></tag_2>
      <tag_3><![CDATA[CakePhp<Help]>]]\/\/\/\/\/\/]]></tag_3>
      <tag_4><![CDATA[jQuery]]></tag_4>
   </languages>
   <title><![CDATA[Pritom Kumar (Web Developer)]]></title>
   <inline_tag><![CDATA[<name><first>Pritom</first><last>Kumar</last></name>]]></inline_tag>
   <favorite_blogs>
      <CSSTricks><![CDATA[http://css-tricks.com]]></CSSTricks>
      <AJAXian><![CDATA[http://ajaxian.com]]></AJAXian>
   </favorite_blogs>
   <invalid_characters>
      <tag___><![CDATA[00-&*]]></tag___>
      <tag__><![CDATA[&#39;]]></tag__>
      <tag__><![CDATA[&#62;]]></tag__>
      <tag__><![CDATA[&#60;]]></tag__>
      <tag__><![CDATA[&#38;]]></tag__>
      <tag__><![CDATA[&#45;]]></tag__>
      <tag___><![CDATA[&#176;]]></tag___>
   </invalid_characters>
</data>


/* After parse xml, array would look like this: */ 

$xmlParser = new XmlToArrayParser($xmlString);

print_r($xmlParser); 

xmlToArrayParser Object
(
    [array] => Array
        (
            [data] => Array
                (
                    [first_name] => Pritom
                    [middle_name] => Kumar
                    [last_name] => Mondal
                    [url] => http://pritomkumar.blogspot.com
                    [languages] => Array
                        (
                            [php_language____] => <!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇
                            [tag_0] => Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨
                            [tag_1] => Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐
                            [tag_2] => CSS
                            [tag_3] => CakePhp<Help]>]]\/\/\/\/\/\/
                            [tag_4] => jQuery
                        )

                    [title] => Pritom Kumar (Web Developer)
                    [inline_tag] => <name><first>Pritom</first><last>Kumar</last></name>
                    [favorite_blogs] => Array
                        (
                            [CSSTricks] => http://css-tricks.com
                            [AJAXian] => http://ajaxian.com
                        )

                    [invalid_characters] => Array
                        (
                            [tag___] => Array
                                (
                                    [0] => 00-&*
                                    [1] => &#176;
                                )

                            [tag__] => Array
                                (
                                    [0] => &#39;
                                    [1] => &#62;
                                    [2] => &#60;
                                    [3] => &#38;
                                    [4] => &#45;
                                )

                        )

                )

        )

    [parse_error] =>
    [parser:xmlToArrayParser:private] => Resource id #4
    [pointer:xmlToArrayParser:private] => Array
        (
            [data] => Array
                (
                    [first_name] => Pritom
                    [middle_name] => Kumar
                    [last_name] => Mondal
                    [url] => http://pritomkumar.blogspot.com
                    [languages] => Array
                        (
                            [php_language____] => <!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇
                            [tag_0] => Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨
                            [tag_1] => Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐
                            [tag_2] => CSS
                            [tag_3] => CakePhp<Help]>]]\/\/\/\/\/\/
                            [tag_4] => jQuery
                        )

                    [title] => Pritom Kumar (Web Developer)
                    [inline_tag] => <name><first>Pritom</first><last>Kumar</last></name>
                    [favorite_blogs] => Array
                        (
                            [CSSTricks] => http://css-tricks.com
                            [AJAXian] => http://ajaxian.com
                        )

                    [invalid_characters] => Array
                        (
                            [tag___] => Array
                                (
                                    [0] => 00-&*
                                    [1] => &#176;
                                )

                            [tag__] => Array
                                (
                                    [0] => &#39;
                                    [1] => &#62;
                                    [2] => &#60;
                                    [3] => &#38;
                                    [4] => &#45;
                                )

                        )

                )

        )

)


?>