Friday, April 12, 2013


Laravel- Working with namespace


Starting with Laravel, soon had found that there is a lac of documentation. As a beginner, got a bunch of issues while starting with a modular Namespaced   approach for my project.

 Dont SKIP any paragraph of this doc, else one can get nasty issues.
Creating a new module, with namespace
Step 1: Namespaced directory structure
In our Laravel projects, we will separate each features/modules, with separate namespaces.  But Laravel's Autoloader class makes a difference, with the way- traditional PHP namespace works.
In Laravel, namespace works like JAVA, we have to create a directory same as namespace & keep those files for that namespace under it.

Namespace is applicable only for Models & Views. The Controllers cant be namespaced
For e.g- if we create a Ratings module in our project with 'rating' namespace, then the directory structure will be-
 - application/models/rating/ratingmodel.php
 - application/models/rating/ratingview.php
 - application/controllers/ratings.php  // no namespace for controller

 *We need to add  namespace rating;  at the very TOP of these namespaced files- ratingmodel.php & ratingview.php

Step 3: Calling the namespaced model, views from CONTROLLER

once all the namespacing done- we can call the namespaced classes from controllers like this way
 - nameSpace\Class- name.  // Else the class will not be found
<?php

class Ratings_Controller extends Base_Controller {

    public function action_getRatings()

    {
         .......

         //set the entity of Ratings Type

         $objRatingsModel = new rating\Ratingsmodel();
         // namespace\ClassName, else the class will not be found

Step 4: Calling the Laravel default classes from namespaced files We can call the default Laravel functionalities( like- Validator::make(), DB::raw() ) from namespaced files, by adding a back-slash(\) before the class- to indicate they are from root-level namespace For e.g-
in rating/ratingmodel.php, 
<?php
namespace rating;

class RatingModel{


   public static function validateAndStoreInput($input)
   {
      // Validate the Ratings instance...
      $rules = array(
         'type'  => 'required|alpha',
         'id' => 'required|numeric|min:1'
      );

      $validation = \Validator::make($ratings->input, $rules); 
      // added a back-slash, else the class will not be found
      ....
     
   }
   ....
}
- thats all. Please comment if someone has any query or confusion. Thanks.

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/mysite.com/httpdocs/PROCESS/processScript.php');

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/mysite.com/httpdocs/PROCESS/processScript.php > /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/mysite.com/httpdocs/PROCESS/processScript.php  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'
REPLACE INTO TABLE `table_name`
FIELDS TERMINATED BY '||' 
LINES TERMINATED BY '\n' STARTING BY ''

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-
CREATE TABLE IF NOT EXISTS `users_temp` (
  `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" />
    
    <br/>
    
  <input type="submit" value="Import" />
</form>
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
        move_uploaded_file($tempFile,$targetFile);
        
        // 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);
        
    } 
    else 
    {
        //Error
        echo 'Invalid file type. Please choose .txt or .csv file.';
    }
}
else
{
     //Error
     echo 'Please upload a user list file.';
}
5. Mysql Commned for import the file
function importUsers($filePathFromRoot)
{
 $sql = "LOAD DATA LOCAL INFILE '".$filePathFromRoot."'
                    REPLACE
                    INTO TABLE `users_temp`
                    FIELDS TERMINATED BY '||' 
     LINES TERMINATED BY '\n' STARTING 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.

Monday, April 18, 2011

CURL POSTING ISSUES

In case of, developing a Facebook App, we need to first download the FB Class file (get the download links here- http://developers.facebook.com/docs/sdks/ or from here- https://github.com/facebook/php-sdk/) and need to do all work with its member functions. The First common issue is getting CURL exceptions while Posting in the wall. We can track the CURL error and fix that issue. There is another issue regarding CURL SSL certificate. We can simply turn off the CURL SSL Varifier. Here are the code changes- 1. Download PHP SDK from- https://github.com/facebook/php-sdk/ 2. We need to turn-off the SSL Varification Search for the array-
public static $CURL_OPTS = array(
and add another variable/ CURL-Property into it-
CURLOPT_SSL_VERIFYPEER => false
So, Finally the block will look like-
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-2.0',
CURLOPT_SSL_VERIFYPEER => false
);
3. For the CURL Error 77 (common while Posting through IE) Search for this line-
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
and simply modify this to-
if (curl_errno($ch) == 60 || curl_errno($ch) == 77) { // CURLE_SSL_CACERT
- it will escape the 77 Error as well. - and we are done.

Monday, March 21, 2011

Trick to post Code-Snippets in your Blog

From last Few days, I was searching for a solution to post code, properly designed- obviously for free blogs. Because, currently its a headache to post code in blog as-it-is I want to post. Found some nice tricks. But, some of them needs registered blog-site[ should have FTP-Access, to upload files].
Also, got some template editing tricks, but they were not much good. So, i edited some css snippets, which is now working nicely [ that is currently used in this blog-post].
There are 4 steps to follow-

1.
Enter in your Blog admin and go to Design >> Edit HTML a

2.
Come to the end-of-head-section
OR
Simply search(ctrl+F) for this code ""

Now our new code will go here -






















3.
Now paste the below code here-


pre, code
{
background:#efefef;
border:1px solid #A6B0BF;
font-size:100%;
line-height:130%;
overflow:auto;
padding:5px;
color:#000000 }
pre:hover {
border:1px solid #efefef;
}

.clear { clear:both;
overflow:hidden;
}
pre .comment_in_code, code .comment_in_code
{
color:#999999;
}

and then Save your changes.

4.
Now, write a blog-post with code-snippets
Then parse it using-
http://www.blogcrowds.com/resources/parse_html.php
OR
http://www.elliotswan.com/postable/

Then, find and wrap your codes such that->
<pre> Your Post Code Snippet Here </pre>
Or
<code> Your Post Code Snippet Here</code>

And your comments within the Code goes here-
<span class="comment_in_code"> //This is a comment within the code snippet. </span>


- and thats all. The code-snippets and comments will look like-

Friday, March 11, 2011

treating a BLANK SPACE in REGULAR EXPRESSION

Got a problem while allowing a blank space in regular Expression, for service URL.

-> so the solution is-
"S" (an uppercase 'S')

So at last my regex pattern was like this in php-


[a-z:A-Z;=;\\S]+/[0-9]+
//Now it will allow case-insensitive any alphabet, any number