Wednesday, 15 April 2015

PHP problem solving interview questions and answers for Fresher and Experienced

PHP problem solving interview questions and answers for Fresher and Experienced


Question: How to save image in directory from URL?
In Below code, Just update the  $savePath and$ downloadImagePath.Script is Ready.
try {    
    $downloadImagePath='http://www.aboutcity.net/images/aboutcity.png';
    $savePath = $_SERVER['DOCUMENT_ROOT'];
    $ch = curl_init($downloadImagePath);
    $fp = fopen($savePath . '/aboutcity.png', 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    echo "Image Downloaded Successfully in ".$savePath.' Folder.';
} catch (Exception $e) {
    echo $e->getMessage();
}



Question: How to remove empty elements from array?
Below script will remove all the elements which have null values and empty data including space.
$array = array(
'key1'=>'value1',
'key2'=>'value2',
'key3'=>'value3',
'key4'=>' ',
'key5'=>' ',    
'key6'=>null,    
);
$filterArray = array_map('trim',$array);
$filterArray = array_filter($filterArray);

print_r($filterArray);//Array ( [key1] => value1 [key2] => value2 [key3] => value3 ) 



Question: How to convert object data to array?
It will convert an object to array.
$obj = new stdClass();
$obj->key1 ='Value1';
$obj->key2 ='Value3';
$obj->key3 ='Value3';
$obj->key4 ='Value4';
$array = (Array)$obj;
print_r($array);//Array ( [key1] => Value1 [key2] => Value3 [key3] => Value3 [key4] => Value4 ) 



Question: Is it possible a function with name?
Yes, that known as Anonymous functions.
Anonymous functions, also known as closures, allow the creation of functions which have no specified name.
$greet = function($name)
{
    printf("Hello %s", $name);
};
$greet('Hello');
$greet('Web Technology experts Notes');



Question: What is PHP_EOL in PHP?
End Of Line
PHP_EOL is used, when you want a add new line in cross-platform. It will work DOS/Mac/Unix issues.


Question: What are reserved constants in PHP?
http://php.net/manual/en/reserved.constants.php


Question: How to store array in Constants?
You can not store array in php constants.
Because php constant can store single string only.
BUT if you serialize an array to string then you can store it constants in constnats.
See Examples:
define ("MY_FRUITS", serialize (array ("apple", "cherry", "banana","mango")));



Question: Where to do PHP Practise online?
https://codeanywhere.net/
http://ideone.com/
http://writecodeonline.com/php/
http://codepad.org/
http://sandbox.onlinephpfunctions.com/
http://codepad.viper-7.com/
https://eval.in/


Question: How to start session, if already not started?
If session is started, session_id() will return the string else empty string.
if(session_id() == '') {
    session_start();
}



Question: Create a folder if it doesn't already exist?
file_exists is used to check directory exist OR NOT.
mkdir is used to create the new directory.
$path="/path/to/dir";
if (!file_exists($path)) {
    mkdir($path, 0755, true);
}



Question: How to convert date to timestamp in PHP?
strtotime function is used to convert the full date time into timestamp.
$timestamp = strtotime('22-09-2008');



Question: What is Difference between isset and array_key_exists?
isset: It is used to check, variable is defined OR NOT.
array_key_exists: it is used to check, an key is available in array or not.
bool array_key_exists ( mixed $key , array $array );



Question: How to return JSON from a PHP Script?
$array = array(
'key1'=>'value1',
'key2'=>'value2',
'key3'=>'value3',
'key4'=>' ',
'key5'=>' ',    
'key6'=>null,    
);
header('Content-Type: application/json');
echo json_encode($array);



Question: How to change the maximum upload file size to 60MB?
open php.ini file
//This is max file size
upload_max_filesize = 60M 

//this is form size including file size, that's why its greater 1 MB
post_max_size = 61M



Question: When to use self over $this?
Use $this to refer to the current object.
Use self to refer to the current class.

Example of use of $this
class MyClass1 {
    private $nonStaticMember = 'nonStaticMember  member Called.';        
    
    public function funcName() {
        return $this->nonStaticMember;
    }
}

$classObj = new MyClass1();
echo $classObj->funcName();//nonStaticMember  member Called.


Example of use of self
class MyClass2 {
    private static $staticMember = 'staticMember  member Called.';        
    
    public function funcName() {
        return $this::$staticMember;
    }
}

$classObj = new MyClass2();
echo $classObj->funcName(); //staticMember  member Called.





Tuesday, 14 April 2015

What is Best method for sanitizing user input with PHP?

What is  Best method for sanitizing user input with PHP

Sanitize user-input when using in Mysql Query.
You can use real_escape_string of mysqli.
For Example:
$mysqliObj = new mysqli("localhost", "root", "", "mydb");
$city = $mysqliObj->real_escape_string($_POST['city']);
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}



Sanitize user-input  while insert in database and displaying in Browser.
You can use htmlentities and html_entity_decode.
For Example:
echo htmlentities($data['description']);//at the time of insert in database 
echo html_entity_decode($data['description']); //at the time of display in browser from database



Sanitize user-input when using in Command Prompt.
You can use escapeshellarg.
For Example:
system('ls '.escapeshellarg($data['dir']));