Wednesday, August 8, 2012

Triggering an Asynchronous Process from PHP, Without Waiting to Complete

Triggering an Asynchronous Process from PHP, Without Waiting to Complete

Sometimes, we need to send a large amount of emails, sms or pushnotification from current script & the current page waits until al the stuffs are done.

To, overcome this thing, we can simply trigger a new process asynchronously and pass parameters to it, without making any wait conditions. The process will start and take its time to complete, without affecting the parent script.

we can use exec() or system() function for that. The difference is System() also prints the output.
Structure- exec('PATH/TO/PHP PATH/TO/FILE.PHP');

1. Here is a sample command to call another script from current file as a separate process-

exec('/usr/bin/php5 /var/www/vhosts/');

2. Doing the above will start the script as a new process, but the parent script will still wait - this process to complete. To overcome that we will modify our command to this-

exec('/usr/bin/php5   /var/www/vhosts/ > /dev/null 2>&1 &');

3. Now, the process will execute, without keeping the parent to wait. But, we surely need to pass parameters to the process Script. That will be simply accomplished using $argv. $argv returns an array of arguments passed to script.

In this example, we will pass a parameter: 15 to the processScript.php-

exec('/usr/bin/php5   /var/www/vhosts/  15 > /dev/null 2>&1 &');

- we are done.
- In processScript.php, we will get the parameter: 15 by-

$paramID = $argv[1];  //$argv[0] is always the name that was used to run the script

- and that's all- we need to run a new PHP process. Please post a comment if you have any query or if you like the post.

Saturday, July 14, 2012

Android key hash for Facebook App

Its pretty confusing to get a Key hash value for creating Facebook Apps for Android.

Here are the detailed steps for doing that-

1. We need to download openssl from Google code (64 bit users must download openssl-0.9.8e X64, not the latest version)

2. Extract it.
create a folder- OpenSSL in C:/ and copy the extracted code here.

3. Detect debug.keystore file path.
If we can't find one, then lets do a search in C:/ and we will use the Path in the command in next step.

4. Detect keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-
> keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator\.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

Now, it will ask for password, put android
That's all. It will return a key-hash.

Please post a comment, in case of any issue.

Importing a deliminator-ed .txt or .csv file to MySQL DB, in PHP, directly from web form

Its a common & handy thing to import data, directly into database- by a Website Admin user. Its much more efficient process for the Admin to insert data into table. Else- its kinda boring and irritating procedure to insert into table from 'Add User Form' or Phpmyadmin or whatever. Import from File MySQL Sample Command
LOAD DATA LOCAL INFILE 'from_import_file'

Details from Scratch

At very first, we'll take the file from the user, using simple form. Then we'll use LOAD DATA INFILE to load into DB. Here is the code snippet-

1. Create a Temporary table which will have same field number as the imported DB file. For e.g- importUsers.txt content( file to be imported- with deliminated string || )
John Doe||user_id_123||The XYZ Company||Chicago
Mike Blinov||user_id_140||The ABC Company||New York
Austin Steven||user_457||WWE Tech LTD||Los Angeles
2. Then create the temporary table with exact 4 columns-
  `name` varchar(50) NOT NULL,
  `userId` varchar(50) NOT NULL,
  `company` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL
3. Have an HTML Form
<form enctype="multipart/form-data"  action="" method="post" >
    <label for="file_upload">Import Users</label>
    <input type="file" name="file_upload" id="file_upload" />
  <input type="submit" value="Import" />
4. On Submit Form PHP Code, upload the file with a unique name (This name is going to be used in the LOAD DATA Query) & getting the path of the uploaded file- from root
if (!empty($_FILES)) 
    $tempFile = $_FILES['file_upload']['tmp_name'];

    // Validate the file type
    $fileTypes = array('txt','csv','CSV'); // Valid File Extensions
    $fileParts = pathinfo($_FILES['file_upload']['name']);
    if (in_array($fileParts['extension'],$fileTypes))
        //ploading with a unique name
        $uploadedFileName = 'import_users_'.time().'_'.rand(100,999999).'.'.$fileParts['extension'];
        $targetFile = 'ImportUser/' . $uploadedFileName;
        //File Uploaded
        // Getting the Full Path
        $fullPath = $_SERVER['SCRIPT_FILENAME'];
        $pathParts = pathinfo($fullPath);
        $pathToCurFile = $pathParts['dirname'];
        // Getting the Full path of uploaded file- FROM ROOT
        $uploadedFilepath = $pathToCurFile.'/'.$targetFile;
        // Function defined later
        $result  = importUsers($uploadedFilepath);
        echo 'Invalid file type. Please choose .txt or .csv file.';
     echo 'Please upload a user list file.';
5. Mysql Commned for import the file
function importUsers($filePathFromRoot)
 $sql = "LOAD DATA LOCAL INFILE '".$filePathFromRoot."'
                    INTO TABLE `users_temp`
                    FIELDS TERMINATED BY '||' 
 $res = mysql_query($sql) or die ("Import Error");
6. Now after a successful import every-time, we can read from this temporary table and populate our actual table & then make this temporary table empty.
- thats all.
Please comment in case of any issue.