PHP interview questions for experience and fresher
Question: What is Encapsulation?
The wrapping up of "Data member" and "Member functions" into a single unit (called class) is known as encapsulation.
Question: Describe the Encapsulation?
Encapsulation means hiding the internal details of an object.
OR
Encapsulation is a technique used to protect the information in an object from the other object.
Question: Give Example of the Encapsulation?
class
Arithmetic {
private $first = 10;
private $second = 50;
function add() {
return $this->first +
$this->second;
}
function multiply() {
return $this->first * $this->second;
}
}
//Create
the object
$obj
= new Arithmetic( );
//Add
Two number
echo
$obj->add(); //60
//multiply
Two number
echo
$obj->multiply(); //500
Question: How to replace double
quoted string with bold in PHP?
$description='Hello
"dude", how are you?';
echo
preg_replace('/"([^"]+)"/', '<strong>$1</strong>',
$description);
Output
Hello
dude, how are you?
Question: How to replace bracket string with italic in PHP?
$description='Hello
(dude), how are you?';
echo
preg_replace('/\(([^)]+)\)/', '<i>$1</i>', $description);
Output
Hello
dude, how are you?
Question: What is fsockopen?
fsockopen — Open Internet or Unix domain socket connection.
Question: How to check if port is open OR Not in particular IP Address OR Domain?
function
pingDomainWithPort($domain='localhost',$port=80){
$starttime = microtime(true);
$file
= @fsockopen($domain, $port, $errno, $errstr, 10);
$stoptime
= microtime(true);
$status
= 0; //in active
if (!$file) {
$status = -1; // Site is down
} else {
fclose($file);
$status = ($stoptime - $starttime) *
1000;
$status = floor($status);
}
return $status;
}
pingDomainWithPort($_SERVER['REMOTE_ADDR'],1935);
pingDomainWithPort($_SERVER['REMOTE_ADDR'],1458);
pingDomainWithPort($_SERVER['REMOTE_ADDR'],80);
pingDomainWithPort($_SERVER['REMOTE_ADDR'],8080);
You can pass the domain name or Ip Address.
Question: What is the use of the @ symbol in PHP?
It suppresses error messages, means hide the error/warning messages for that statement.
It suppresses error messages, means hide the error/warning messages for that statement.
echo
$noDefinedVar;
Question: How to enable all error in PHP?
ini_set('display_startup_errors',
1);
ini_set('display_errors',
1);
error_reporting(-1);
Question: How to disable all error in PHP?
ini_set('display_startup_errors',
0);
ini_set('display_errors',
0);
error_reporting(0);
Question: How to convert a variable to string?
$myVar='123456987';
$myText
= (string)$myVar; // Casts to string
var_dump($myText);
Question: How to POST request with PHP?
$ch
= curl_init();
$postData='var1=value1&var2=value2&var3=value3';
curl_setopt($ch,
CURLOPT_URL, "http://mydomain.com/ajaxurl");
curl_setopt($ch,
CURLOPT_POST, 1);
curl_setopt($ch,
CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch,
CURLOPT_RETURNTRANSFER, true);
$result
= curl_exec($ch);
curl_close($ch);
echo
$result;die;
Question: Formatting a number with leading zeros in PHP?
echo
sprintf('%08d', 1234567); //01234567
echo
sprintf('%09d', 1234567); //001234567
echo
sprintf('%010d', 1234567); //0001234567
Question: How to Check if PHP session has already started?
if
(session_status() == PHP_SESSION_NONE) {
session_start();
}
Question: Why do we use ob_start()?
define
("FRUITS", serialize (array ("apple", "mongo",
"banana","fig")));
$fruits
= unserialize (FRUITS);
print_r($fruits);
Question: How to increase PHP Execution Time?
ini_set('max_execution_time',
300);
Question: how do you change the key of an array element?
$array=
array ('a'=>"apple", 'm'=>"mongo",
'b'=>"banana",'f'=>"fig");
print_r($array);
$array['bbbbb']=
$array['b'];
unset($array['b']);
print_r($array);
Question: How to get last key in an array?
$array=
array ('a'=>"apple", 'm'=>"mongo",
'b'=>"banana",'f'=>"fig");
end($array);
echo
key($array);//k
Question: Set HTTP header to UTF-8 using PHP?
header('Content-Type:
text/html; charset=utf-8');
Question: How to generate a random, unique, alphanumeric string?
echo
md5(uniqid(rand(), true));
Question: How to run SSH Commands from PHP?
$connection
= ssh2_connect('HOST_OR_IP_ADDRESS', 'PORT');
ssh2_auth_password($connection,
'USERNAME', 'PASSWORD');
$stream
= ssh2_exec($connection, 'ls');
if
($stream) {
echo "fail: unable to execute
command\n";
} else {
// collect returning data from command
stream_set_blocking($stream, true);
$data = "";
while ($buf = fread($stream,4096)) {
$data .= $buf;
$data.="\n";
}
fclose($stream);
echo $data;
}
Question: What is output of below?
$a
= '1';
$b
= &$a;
$b
= "2$b";
echo
$a.", ".$b;
output
21, 21
Question: What is output of below script?
var_dump(0123
== 123);
var_dump('0123'
== 123);
var_dump('0123'
=== 123);
Output
var_dump(0123
== 123);//false
var_dump('0123'
== 123); //true
var_dump('0123'
=== 123);//false
Question: What is output of below script?
var_dump(true
and false);
var_dump(true
&& false);
var_dump(true
|| false);
Output
var_dump(true
and false); //false
var_dump(true
&& false); //false
var_dump(true
|| false); //true
Question: What is output of below script?
$a1=true
and false;
$a2=true
&& false;
$a3=true
|| false;
var_dump($a1);
var_dump($a2);
var_dump($a3);
Output
$a1=true
and false;
$a2=true
&& false;
$a3=true
|| false;
var_dump($a1);//true
var_dump($a2);//false
var_dump($a3);//true
Question: What is output of below script?
echo 10 + "10%" + "$10";
Output
echo 10 + "10%" + "$10"; //20
Reason: First 10 is 10
Second 10 is 10
Third 10 is 0 (Because start with $)
Question: What is output of below script?
$text
= 'HELLO';
$text[1]
= '$';
echo
$text;
Output
$text
= 'HELLO';
$text[1]
= '$';
echo
$text;//H$LLO
Question: What is output of below script?
$x
= NULL;
var_dump($x);
Output
$x
= NULL;
var_dump($x);/null
Question: Why do we use ob_start()?
Ob_start used to active the output buffering .
Question: What is a .htacces file?
.htaccess is a configuration file running on server.
Following task can be done with .htacces?
- URL Rewrite
- Website password protected.
- Restrict ip addresses
- PHP/Apache Configuration
- Set browser caching for Speed up application.
Question: What is the difference between compiler language and interpreted language?
Interpreted language executes line by line, if there is some error on a line it stops the execution of script. Compiler language can execute the whole script at a time and gives all the errors at a time. It does not stops the execution of script ,if there is some error on some line.
Question: What is type hinting?
Type hinting means the function specifies what type of parameters must be and if it is not of the correct type an error will occur.
Question: What will be output of following?
$x
= 5;
echo
$x;
echo
"
";
";
echo
$x+++$x++;
echo
"
";
";
echo
$x;
echo
"
";
";
echo
$x---$x--;
echo
"
";
";
echo
$x;
Output
5
11
7
1
5
Question: What will be output of following?
$a
= 1;
$b
= 2;
echo
$a,$b;
Output
12
Question: What will be output of following?
var_dump(0123
== 123);
var_dump('0123'
== 123);
var_dump('0123'
=== 123);
Output
boolean false
boolean true
boolean false
Question: What is the difference between Unlink And Unset function In PHP?
unlink It is used to delete the file permanent.
unlink("/data/users.csv");
Unset It is used to delete the variable.
unset($newVariable);
Question: What are PHP Traits?
It is a mechanism that allows us to do code reusability the code and its similar as that of PHP class.
trait
Goodmorning {
public function goodmorning() {
echo "Good Morning Viewer";
}
}
trait
Welcome {
public function welcome() {
echo "Welcome Viewer";
}
}
class
Message {
use Welcome,
Goodmorning;
public function sendMessage() {
echo $this->welcome();
echo $this->goodmorning();
}
}
$o
= new Message;
$o->sendMessage();
Output
Welcome
Viewer
Good
Morning Viewer
Question: How to get URL Of The Current Webpage??
Client
side, connect with parameter
Question: What Is Autoloading Classes In PHP? and how it works?
With autoloaders, PHP allows the to load the class or interface before it fails with an error.
spl_autoload_register(function
($classname) {
include
$classname . '.php';
});
$object = new Class1();
$object2
= new Class2();
Question: What s The use of ini_set()?
PHP allows the user to modify its settings mentioned in php.ini using ini_set();
For Example
Display error on page
ini_set('display_errors',
'1');
Set mysql connection timeout
ini_set('mysql.connect_timeout',100);
Set maximum execution time
ini_set('max_execution_time',100000);
Set post max size
ini_set('post_max_size','30000M');
Set upload max file size
ini_set('upload_max_filesize','64000M');
Question: Which PHP Extension Helps To Debug The Code?
The name of that Extension is Xdebug.
It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.
Question: How can we get the properties of browswer?
$_SERVER['HTTP_USER_AGENT']
Question: How to get/set the session id?
Set the session Id
session_id($sessionId)
Get the session Id
echo
session_id()
Question: What is Scrum?
Scrum is an Agile framework for completing complex projects.
Scrum originally was made for software development projects, but it works well for any complex and innovative scope of work.
Question: What are the ways to encrypt the data?
md5() – Calculate the md5 hash of a string.
sha1() – Calculate the sha1 hash of a string.
hash() – Generate a hash value.
crypt() – One-way string hashing.
Question: How to get cookie value?
$_COOKIE
["cookie_name"];
Question: What is use of header?
The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output.
Question: What is Type juggle in PHP?
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used.
If an integer value assign to variable it become integer.
If an string value assign to variable it become string.
If an object assign to variable it become object.
Question: What will be output of following?
$x
= true and false and true;
var_dump($x);
Output
boolean false
Question: What will be output of following?
$text
= 'Arun ';
$text[10]
= 'Kumar';
echo
$text;
Output
Arun K
Question: What is use of header?
header() is used to redirect from one page to another: header("Location: index.php");
header() is used to send an HTTP status code: header("HTTP/1.0 this Not Found");
header() is used to send a raw HTTP header: header('Content-Type: application/json');
Question: What is output of 1...1?
Its Output is 10.1
How?
Divide it into three points.
Its Output is 10.1
How?
Divide it into three points.
1.
.
.1
- 1.0 is equal to 1
- 2nd . is a concatenation operator
- .1 is equal to 0.1
- So {1} {.} {0.1} is EQUAL to 10.1
Question: What is final value of $a, $b in following?
$a
= '1';
$b
= &$a;
$b
= "2$b";
echo
$a;
echo
$b;
output
21
21
Explaination
$a
= '1'; //1
$b
= &$a; //both are equal
$b
= "2$b"; //now $b=21
echo
$a; //21
echo
$b; //21
Question: What is output of 016/2?
Output is : 7. The leading zero indicates an octal number in PHP, so the decimal number 14 instead to decimal 16;
echo
016; //14
echo
016/2; //7
Question: Difference between include
and require?
include: It include a file, It does not find through an warning.
require: It include a file, It does not find through an fatal error, process exit.
Question: How to get IP Address of client?
include: It include a file, It does not find through an warning.
require: It include a file, It does not find through an fatal error, process exit.
Question: How to get IP Address of client?
$_SERVER['REMOTE_ADDR'];
Question: How to get IP Address of Server?
$_SERVER['SERVER_ADDR'];
Question: What is output of following?
$a
= '10';
$b
= &$a;
$b
= "2$b";
echo
$a;
echo
$b;
Output
210
210
Question: What are the main error types?
- Notices: Simple, non-critical errors that are occurred during the script execution.Ideally we should fix all notices.
2. echo
$undefinedVar;
- Warning: more important than Notice but it is also non-critical errors that are occurred during the script execution. It should be fixed.
4. include
"non-ExistFile.php";
- Error: critical errors due to which script execution stopped. It must be fixed.
6. require
"non-ExistFile.php";
Question: How to enable/disable error reporting?
Enable error
error_reporting(E_ALL);
Disable error
error_reporting(0);
Question: What are Traits?
Traits are a mechanism that allows you to create reusable code in PHP where multiple inheritance is not supported. To create a Traits we use keyword trait.
Example of Traits
trait
users {
function getUserType() { }
function getUserDescription() { }
function getUserDelete() { }
}
class
ezcReflectionMethod extends ReflectionMethod {
use users;
}
class
ezcReflectionFunction extends ReflectionFunction {
use users;
}
Question: How to extend a class defined with Final?
No, You can't extend. A class declare with final keyword can't be extend.
Question: What is full form of PSRs?
PHP Standards Recommendations
Question: What is the difference between $message and $$message?
$message is a simple variable whereas $$message is variable whose name is stored in another variable ($message).
Question: How to destroy the session?
session_destroy
Question: How do you execute a PHP script from the command line?
- Get the php.exe path from server (My PHP path is : D:\wamp\bin\php\php5.5.12)
- In environment variable, Add this path path under PATH variable.
- Re-start the computer.
- Now, you can execute php files from command file.
php
hello.php
Question: How to repair the session?
REPAIR
TABLE tablename
REPAIR
TABLE tablename QUICK
REPAIR
TABLE tablename EXTENDED
Question: Are Parent constructors called implicitly inside a class constructor?
No, You need to call explicitly.
parent::constructor($value);
Question: What does $_GLOBALS means?
It is associate variable which have all the global data of GET/POST/SESSION/_FILES/ENV/SERVER/GLOBALS etc.
Array
(
[_GET] => Array
(
)
[_POST] => Array
(
)
[_COOKIE] => Array
(
[_gu] =>
1cf7097e-eaf0-486d-aa34-449cf1164ba8
[_gw] =>
2.127103(sc~1,s~oru42c,a~1)127418(sc~1,s~oru42c)u[~0,~0,~0,~0,~0]v[~ev3o1,~4,~0]a()
[PHPSESSID] =>
ki18pnad1knttqv5i6233sjem7
)
[_FILES] => Array
(
)
[_ENV] => Array
(
)
[_REQUEST] => Array
(
)
[_SERVER] => Array
(
[REQUEST_TIME_FLOAT] =>
1501064295.228
[REQUEST_TIME] => 1501064295
)
[GLOBALS] => Array
*RECURSION*
[_SESSION] => Array
(
)
)
Question: How is it possible to parse a configuration file?
parse_ini_file('config.ini');
Question: What is the difference between characters \034 and \x34?
\034 is octal 34 and \x34 is hex 34.
Question: Explain soundex() and metaphone().?
soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric strings that represents English pronunciation of a word.
Question: Explain soundex() and metaphone().?
soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric strings that represents English pronunciation of a word.
$str=
"hello";
Echo
soundex($str);
metaphone() the metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if pronounced by an English person.
Question: How to start displaying errors in PHP application ? Add following code in PHP.
ini_set('display_errors',
1);
ini_set('display_startup_errors',
1);
error_reporting(E_ALL);
OR
Add following code in .htacess
php_flag
display_startup_errors on
php_flag
display_errors on
php_flag
html_errors on
php_flag log_errors on
Question: What is stdClass?
It is PHP generic empty class.
stdClass is used to create the new Object. For Example
$newObj
= new stdClass();
$newObj->name='What
is your name?';
$newObj->description='Tell
me about yourself?';
$newObj->areYouInIndia=1;
print_r($newObj);
Output
stdClass
Object
(
[name] => What is your name?
[description] => Tell me about yourself?
[areYouInIndia] => 1
)
Question: What is output of below?
$a
= '1';
$b
= &$a;
$b
= "2$b";
echo
$a.", ".$b;
output
21, 21
Question:What is the difference between GET and POST?
- GET displays the submitted data as part of the URL whereas post does not show.
- GET can handle a maximum of 2048 characters, POST has no such restrictions
- GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
- Normally GET is used to retrieve data while POST to insert and update.
Question:What is traits and give example?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
class
Base {
public function sayHello() {
echo 'Hello ';
}
}
trait
SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class
MyHelloWorld extends Base {
use SayWorld;
}
$o
= new MyHelloWorld();
$o->sayHello();
output
Hello World
Question: Why Redis is different as compared to other key-value stores?
- Redis values can contain more complex data types, with atomic operations.
- Redis is an in-memory but persistent on disk database.
Question: How to delete current database?
redis-cli
flushdb
Question: How to remove all database?
redis-cli
flushall
Question: How to check redis is running?
try
{
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Redis is running.";
echo "Server is running: " .
$redis->ping();
}
catch (Exception $e) {
echo $e->getMessage();
}
Question: How to set value in redis?
$redis->set("name",
"Set string in redis");
Question: How to get value from redis?
echo $redis->get('name'); //Set string in
redis
Question: How to set multiple values (Array) in redis?
$redis->lpush("tutorials",
"PHP");
$redis->lpush("tutorials",
"MySQL");
$redis->lpush("tutorials",
"Redis");
$redis->lpush("tutorials",
"Mongodb");
$redis->lpush("tutorials",
"Mysql");
Question: How to get array data from redis?
$list
= $redis->lrange("tutorials", 0 ,5);
print_r($list);
/*Array
( [0] => Mysql [1] => Mongodb [2] => Redis [3] => MySQL [4] =>
PHP [5] => Mysql ) */
Question: How to get all keys from
redis?
$keyList
= $redis->keys("*");
print_r($keyList);
/*Array
( [0] => tutorials [1] => name ) */
Question: How to stop redis?
/etc/init.d/redis-server
stop
Question: How to start redis?
/etc/init.d/redis-server
start
Question: How to re-start redis?
/etc/init.d/redis-server
restart
Question: How do I move a redis database from one server to another?
- use BGSAVE command to Save a spanshot of the database into a dump.rdb
- Copy this dump.rdb file into another server.
Question: How to create Model Object?
$userObj=
D("Common/Users");
Question: How to add simple AND Query?
$map=array();
$userObj=
D("Common/Users");
$map['user_type']
= 2;
$map['city_id']
= 10;
$lists = $userObj
->alias("u")
->where($map)
->order("u.id
DESC")
->select();
Question: How to add simple OR Query?
$map=array();
$userObj=
D("Common/Users");
$map['u.username|u.email']
= 'email@domain.com'; //username OR
email is email@domain.com
$lists = $userObj
->alias("u")
->where($map)
->order("u.id
DESC")
->select();
Question: How to use =, >, < in Query?
$map['id'] = array('eq',1000); //equal to 1000
$map['id'] = array('neq',1000); //Not equal to 1000
$map['id'] = array('gt',1000);//Greater than 1000
$map['id'] = array('egt',1000);//Greater than OR EQual
1000
$map['id'] = array('between','1,8'); //Between 1-8
Question: How to use like Query?
$map=array();
$userObj=
D("Common/Users");
$map['name']
= array('like','test%'); //like test%
$lists = $userObj
->alias("u")
->where($map)
->order("u.id
DESC")
->select();
Question: How to use like Query with NOT?
$map=array();
$userObj=
D("Common/Users");
$map['b']
=array('notlike',array('%test%','%tp'),'AND'); //Not like %test% and %tp
$lists = $userObj
->alias("u")
->where($map)
->order("u.id DESC")
->select();
Question: How to use Inner JOIN ?
$map=array();
$userObj=
D("Common/Users");
$map['name']
= array('like','test%'); //like test%
$lists = $userObj
->alias("u")
->join(C('DB_PREFIX') .
"profile as p ON u.id = p.uid")
->where($map)
->order("u.id
DESC")
->select();
Question: How to use LEFT JOIN ?
$map=array();
$userObj=
D("Common/Users");
$map['name']
= array('like','test%'); //like test%
$lists = $userObj
->alias("u")
->join('LEFT JOIN
'.C('DB_PREFIX') . "profile as p ON u.id = p.uid")
->where($map)
->order("u.id
DESC")
->select();
Question: How to use RIGHT JOIN ?
$map=array();
$userObj=
D("Common/Users");
$map['name']
= array('like','test%'); //like test%
$lists = $userObj
->alias("u")
->join('RIGHT JOIN
'.C('DB_PREFIX') . "profile as p ON u.id = p.uid")
->where($map)
->order("u.id
DESC")
->select();
Question: How to use group by and having?
$map=array();
$userObj=
D("Common/Users");
$map['name']
= array('like','test%'); //like test%
$lists = $userObj
->alias("u")
->join('RIGHT JOIN
'.C('DB_PREFIX') . "profile as p ON u.id = p.uid")
->where($map)
->order("u.id
DESC")
->group('u.id')
->having('count(p.id)
>0')
->select();
Question: How to use count(for total records)?
$map=array();
$userObj=
D("Common/Users");
$map['name']
= array('like','test%'); //like test%
$count = $userObj
->alias("u")
->where($map)
->count();
Question: Are PHP functions case sensitive?
Case sensitive (both user defined and PHP defined)
- variables
- constants
- array keys
- class properties
- class constants
Case insensitive (both user defined and PHP defined)
- functions
- class constructors
- class methods
- keywords and constructs (if, else, null, foreach, echo etc.)
Question: How to return call by reference value from function?
Just use &(ampersand) before the function name.
For Example.
function
&showData($data){
$data.=' New String';
return $data;
}
Question: How to check a form is submited OR Not?
if($_SERVER['REQUEST_METHOD']
== 'POST'){
//form is submitted
}
Question: How to remove all leading zeros from string?
echo
ltrim('00000012', '0'); //12
Question: How to find HTTP Method?
$_SERVER['REQUEST_METHOD']
It will return GET, HEAD, POST, PUT
etc
Question: How to Serializing PHP object to JSON?
Question: How to Serializing PHP object to JSON?
$userModel
= new UserModel();
echo
json_encode($userModel);//serialize data
Question: How to get current URL of web page?
echo
'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Question: How to add N number of days in an data?
echo
date('Y-m-d', strtotime("+30 days"));
Question: How to get Yesterday date?
echo
date("F j, Y", time() - 60 * 60 * 24); //November 1, 2016
Question: What's the maximum size for an int in PHP? The size of an integer is platform-dependent
Maximum value of about two billion for 32 bit system.
Question: How to remove all specific characters at the end of a string?
$string
= 'Hello. * cool';
echo
$string = str_replace(array('*', '.',' '), '', $string); //Remove * . and space
[you can add more as you want]
Question: How to POST Data using CURL in PHP?
$url
= "http://www.example.com/ajax/testurl";
$postData
= 'this is raw data';
try
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,
1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,
CURLOPT_POSTFIELDS,$postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
echo $output = curl_exec($ch);
curl_close($ch);
}
catch (Exception $e) {
echo $e->getMessage();die;
}
Question: How to re-index an array?
$arrayData=array(
1=>'web technology experts',
3=>'web technology experts Notes',
4=>'web technology experts Notes php technology',
10=>'PHP interview questions and
answers'
);
$reIndexArray
= array_values($arrayData);
print_r($reIndexArray);
/*
Array ( [0] => web technology experts [1]
=> web technology experts Notes [2] => web technology experts Notes php
technology [3] => PHP interview questions and answers )
*/
Question: How do I add 24 hours to a in php?
$currentDate
='2016-06-16 14:30:10';
$futureDate=strtotime('+1
day', strtotime($currentDate));
echo
date('Y-m-d H:i:s',$futureDate); //2016-06-17 14:30:10
Question: How to declare a global variable and get them?
//Set
Global value
$GLOBALS['name']
= 'Web technology experts notes';
//Get
Global value
echo
$GLOBALS['name'];
Question: How to get the location of php.ini?
phpinfo();
This is let you know where is your php.ini file located.
Question: How to Serializing PHP object to JSON?
$obj= new stdClass();
$arrayData=array(
1=>'web technology experts',
3=>'web technology experts Notes',
4=>'web technology experts Notes php technology',
10=>'PHP interview questions and
answers'
);
$obj->data
=$arrayData;
echo
json_encode($obj);
Output
{"data":{"1":"web
technology experts","3":"web technology experts
Notes","4":"web technology experts Notes php
technology","10":"PHP interview questions and answers"}}
Question: How to get duplicate values from array?
$array
= array('apple', 'orange', 'pear', 'banana', 'apple',
'pear',
'banana', 'banana', 'orange');
print_r(array_count_values($array));
Output
Array
(
[apple] => 2
[orange] => 2
[pear] => 2
[banana] => 3
)
Question: How to identify server IP address in PHP?
$_SERVER['SERVER_PORT'];
Question: How to generate PDF File in PHP? You can use third party library.
http://www.fpdf.org/
Question: How to explode a string using multiple delimiters("," and "|" )?
$string='php,
interview | questions , and | answers ';
$output
= preg_split( "/(\,|\|)/", $string );
print_r($output
);
/*
Array
( [0] => php [1] => interview [2] => questions [3] => and [4] =>
answers )
*/
Question: What is Late static bindings in PHP?
Late static bindings comes in PHP 5.3.0. It is used to reference the called class in the context of static inheritance.
Question: Why cause $_FILES may be empty when uploading files to PHP?
Following
reason may be for empty of $_FILES
- multipart/form-data is missing in form tag.
2. <form
action="vanilla-upload.php" enctype="multipart/form-data"
method="POST">
3. </form>
- /tmp folder does not have enough permission. In this folder uploaded file moved temporary.
- You have upload heavy files more than allowd in php.ini (post_max_size and upload_max_filesize)
- file_uploads is off in php.ini
Question: How to convert a UNIX Timestamp to Formatted Date?
$timestamp='1463721834';
echo
date("Y-m-d h:i:s A", $timestamp);//2016-05-20 05:23:54 AM
Question: How can we remove a key and value from an associative array?
$arrayData
= array(0=>'one',1=>'two',3=>'three');
print_r($arrayData);
unset($arrayData[1]);
/*
Array
( [0] => one [3] => three )
*/
Question: How can we remove a value from an associative array?
$arrayData
= array(0=>'one',1=>'two',3=>'three');
$arrayData[1]='';
print_r($arrayData);
/*
Array
( [0] => one [1] => [3] =>
three )
*/
Question: What is meaning of ampersand(&) before the function name?
If any function start with ampersand(&), It means its call by Reference function. It will return a reference to a variable instead of the value.
Question: How to detect request is from Search Engine Bots?
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']),
"googlebot"))
{
/*This request is from search engine bots
*/
}
Question: List all files/directory in one directory?
if
($handle = opendir('D:\softwares')) {
while (false !== ($entry =
readdir($handle))) {
if ($entry != "." &&
$entry != "..") {
echo "$entry";
}
}
closedir($handle);
}
Question: What is mod_php?
mod_php means PHP installed as a module in Apache.
Question: How to Add 1 Day in timestamp?
$timestamp='1463721834';//2016-05-20
05:23:54 AM
//Add
1 Day
$timestamp=strtotime('+1
day', $timestamp);
echo
date("Y-m-d h:i:s A", $timestamp);//2016-05-21 05:23:54 AM
Question: How to re-index an array?
$arrayData
= array(0=>'one',1=>'two',3=>'three',66=>'six six',7=>'Seven');
$newArray
= array_values($arrayData);
print_r($arrayData);
/*
* Array ( [0] => one [1] => two [3]
=> three [4] => six six [5] => Seven )
*/
Question: How to restrict the function to be accept only array?
We can define the argument data-type, while defining the function. For Example
function
testmsg(array $data) {
print_r($data);
}
testmsg('string');
It will throw following error.
Catchable
fatal error: Argument 1 passed to testmsg() must be of the type array, none
given
1) What is PHP?
ReplyDeletePHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is widely used for web development. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.
2) Who is known as the father of PHP?
Rasmus Lerdorf
3) What was the old name of PHP?
Personal Home Page.