Upload file to server, Angularjs using angular-file-upload plugin

Recently I learned some Angularjs, and when I need to upload file to server, I found it difficult to upload it
using only angularjs,  many angular plugin available out there and most of them works in similar way.

In this example I am using “AngularFileUpload” plugin you can download it from Github (https://github.com/danialfarid/angular-file-upload)

in your client side code you need to crate a angular app and include “angularFileUpload” plugin like this:-

var app = angular.module('myApp', ['angularFileUpload']);

Your Controller function will look like this, don’t forget to include “$upload” service.

app.controller('MainCtrl', [ '$scope', '$timeout', '$upload' ,function($scope, $timeout, $upload){
$scope.uploadResult = [];
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'upload.php',
file: $file,
progress: function(e){}
}).then(function(response) {
$timeout(function() {
$scope.uploadResult.push(response.data);
});
});}}
}]);

in your form you need to call “onFileSelect” function in input field like this:-

input type="file" id="i_file" name="file" ng-file-select="onFileSelect($files)" multiple
Download link for code in Github https://github.com/devnegikec/AngularFileUploadExample

Please write to me if you need any help or have a question on angularjs, jquery, knockoutJs or Javascript.


Web Developer Interview Question

Q1. What is the diffrence between PHP GET and POST Methods ?

Ans. There are two ways the browser client can send information to the web server.

The GET Method
The POST Method

Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2

The GET method produces a long string that appears in your server logs, in the browser’s Location: box.

The GET method is restricted to send upto 1024 characters only.

Never use GET method if you have password or other sensitive information to be sent to the server.

GET can’t be used to send binary data, like images or word documents, to the server.

The data sent by GET method can be accessed using QUERY_STRING environment variable.

The PHP provides $_GET associative array to access all the sent information using GET method.

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

The POST method does not have any restriction on data size to be sent.

The POST method can be used to send ASCII as well as binary data.

The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.

The PHP provides $_POST associative array to access all the sent information using GET method.

More information here


PHP Arrays

1.  I have these two arrays


$ar1 = array ( 'book' => array ( 'bookName' => 'two brothers', 'id' => '341345243904', 'writer' => 'Mack Mohan') ) ;
$ar2 = array ( 'book' => array ( 'publicier' => 'Tata Mcgraw Hills' ) );

I want to mearg on ‘book’ key


$result = array_merge($ar1['book'], $ar2['book']);
echo nl2br(print_r($result,1));

$result is


Array
(
[bookName] => two brothers
[id] => 341345243904
[writer] => Mack Mohan
[publicier] => Tata Mcgraw Hills
)

if you have multidimensional array, you can do this


foreach($ar1 as $key=>$value)
{
if($ar2[$key]) // check second array $key exist
$result [] = array_merge($ar1[$key], $ar2[$key]);
else
$result [] = $ar1[$key];
}
echo nl2br(print_r($result,1));

How to get a value in a PHP Array?

$item = array(0=>'red', 1=>'blue', 2=>'green', 3=>'red');

$key = array_keys($item, ‘red’);

print_r($key); // result will be $key = array(0=>’0′, 1=>’3′);

What do you use to print an array on you screen “print_r” or “print”?
try this :-

echo nl2br(print_r($array,1));

Split string with a regular expression match.
I have lot of strings which starts with a name and date of birth, I want to split them to get name of the person.

$string = "John (02/27/1986) , he is working with ....";
$match = preg_split('/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,4})/', $string);
$name = $match[0]; // result $name = "John";

Many times you need to sort multidimensional array, especially when you are fetching data from database.
array_multisort is very useful in such cases.
here is an example.

$city = array( 0 => array( 'name'=>'Bangalore', 'pin'=>'560972', 'code'=> '01'),
1 => array( 'name'=>'Ahemedabad', 'pin'=>'89070', 'code'=> '02'),
2 => array( 'name'=>'Delhi', 'pin'=>'984902', 'code'=> '03')
);
echo nl2br(print_r($city,1)); //print array before sort
foreach ($city as $key => $row) {
$name[$key] = $row['name']; //collect values in a array from witch you want to short you multidimensional array
}
array_multisort($name, SORT_STRING, $city); //$your_array , sorting critaria, $data_you_want_to_short
echo nl2br(print_r($city,1)); //print array after sort

other sorting options are SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING.


String Manupulation

Get last subString

$myString = "800-555-5555";
$result = strrchr($myString, "-");
echo $result; // $result  = -5555

For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php

Remove new line from a string.


$myString = "new sting
with a
new line";
$myString = preg_replace( '/\s+/', ' ',myString);

//$myString = "new sting with a new line";


Yii Upload images using Xupload extension

Upload image to database Yiiframework.

Step 1 :-

Download Xupload extension from the below link

http://www.yiiframework.com/extension/xupload/

and extract  it to your application under   “Your_Application/protected/extensions”

Now you have the extension in Place, lets add an upload button to your view.

Step 2:-

I want to add an upload button to my user profile page, my view file is

<?php
$id = $model->id;
$upload = new XUploadForm;
$this->widget('ext.xupload.XUploadWidget', array(
'url' => Yii::app()->createUrl("profile/upload/",
array("parent_id" =>$id ) ),
'model' => $upload,
'attribute' => 'file',
'options'=>array(
/*'beforeSend' => 'js:function(event, files, index, xhr, handler, callBack) {
handler.uploadRow.find(".upload_start button").click(callBack);
}',*/
'onComplete' => 'js:function (event, files, index, xhr, handler, callBack) {
$("#Profile_avatar").val(\'\'+handler.response.name + \'\' );
}'),
));
//
?>

Step 2:-

add this function to your profile page and remember to change the access rule if applicable


public function actions()
{
return array(
'upload'=>array(
'class'=>'ext.xupload.actions.XUploadAction',
'subfolderVar' => 'parent_id',
'path' => realpath(Yii::app()->getBasePath()."/../images/profile/"),
),
);
}

make sure you have “images” and “profile”  directory in you application folder and they have read/write permission.

Explanation :-   In view file we are calling “profile” controller action, this controller action sending our request to Xupload’s upload function , parent_id is sub-directory name under  “images/profile” directory, Xupload will crate this directory if it don’t exist.

Note:- do not declare any upload action in your “profile controller”, it will overwrite our Xupload’s upload function.

Now try to upload an image, If your upload is successful you can continue with reading otherwise leave a comment, open your firebug and start debugging.

Step4:- Save image path to database.

open XUploadAction.php file path is  (Your_Application\protected\extensions\xupload\actions)

after this line   

$model->file->saveAs($path.$model->name);

line no 129 in my case.

$isProfileImage = strpos($path, 'profile/');

// checking if  image is uploding to profile folder.
if(!($isProfileImage === false))
{
$profileImage = new Profileimage();   //I have a saprate profileimage table and created model for it.
$profileImage ->path = $model->name;
$profileImage ->profile_id = $this->_subfolder;
$profileImage ->save();
}

this is my proflieimag table looks like.

CREATE TABLE IF NOT EXISTS `proflieimag ` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`path` varchar(256) DEFAULT NULL,
`profile_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_proflieimag _profiles1` (`profile_id`),
CONSTRAINT `fk_proflieimag _profiles1` FOREIGN KEY (`profile_id`) REFERENCES `profile` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION

) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;



Drush Installation for Ubuntu 10.04

If you are a new Drupal developer you must know about Drush utility. It makes your life easy when you install new modules and themes.You can install Drush in three simple steps.

STEP 1:-

Install PHP cli package.

root@dev:#apt-get install php5-cli

STEP 2:-
go to /opt directory

root@dev:#cd /opt

Download drush form the link below

root@dev:/opt#wget http://ftp.drupal.org/files/projects/drush-All-versions-4.0-rc1.tar.gz
If this link doesn’t work google for new link.
unzip Drush
root@dev:/opt# tar xvfz drush-All-versions-4.0-rc1.tar.gz

STEP 3:-
root@dev:/opt# ln -s /opt/drush/drush /usr/local/bin/

Test drush
root@dev:/var/www# drush dl drupal

This command download a fresh stable version of Drupal to your Apache document root(/var/www/) and extract it.

Other Helpful links :-
official Drush Page.
http://drupal.org/project/drush
Drush cheat sheet.
http://drupal.org/node/477684


WAMP common instillation problem

If you are trying to setup WAMP and getting error like this …..

Could not execute menu item (internal error)
[Execption] Could not perform service action:
The service has not been started.

It means your Apache is not able to start. because port 80 is occupied by any other program or service.

Test your post 80 :-

Left click WAMP icon ->Apache ->Service -> Test Port 80

Now based on your result, you have to take action

1. Skype

Skype -> Tools -> Options ( Options window will appear )

Click on Advanced it will expand and then click on Connection and your final settings will look like this

Now restart you Skype and WAMP

2. Window Services

(These instructions for Windows 7 users it may different for other version of windows users)

Disable Microsoft “Web Deployment Agent Service” if it is enabled .

Go to Search and type “services” select services and disable “Web Deployment Agent Service”

change Startup Type “Automatic” to “Manual” and Status to Disable.

If it is already disable check other services like IIS (Internet Information Services ) or SQL reporting services.

3. Change Port

If you are facing difficulty to find out which service is causing  problem you can just change the port.

Open file “httpd.conf” (path : wamp\bin\apache\Apache2.2.17\conf)

from WAMP Icon

Search “Listen 80” and change the port i.e. Listen 8080

and Search for “ServerName localhost:80” and change it “ServerName localhost:8080”

Restart WAMP and access your localhost like “localhost:8080”.


Follow

Get every new post delivered to your Inbox.