Download as pdf or txt
Download as pdf or txt
You are on page 1of 112

​Laravel?

 
● Posted by ​Sharad Jaiswal 
● Laravel is free open source “PHP framework” based on MVC design 
pattern. 
● It is created by Taylor Otwell. Laravel provides expressive and elegant 
syntax that helps in creating a wonderful web application easily and 
quickly. 

● 0
● Q2. 
● What are pros and cons of using Laravel Framework? 
● Posted by ​Sharad Jaiswal 
● Pros of using Laravel Framework 
Laravel framework has in-built lightweight blade template 

engine to speed up compiling task and create layouts with 
dynamic content easily. 
○ Hassles code reusability. 
○ Eloquent ORM with PHP active record implementation 
○ Built in command line tool “Artisan” for creating a code skeleton , 
database structure and build their migration 
● Cons of using laravel Framework 
○ Development process requires you to work with standards and 
should have real understanding of programming 
○ Laravel is new framework and composer is not so strong in 
compare to npm (for node.js), ruby gems and python pip. 
○ Development in laravel is not so fast in compare to ruby on rails. 
○ Laravel is lightweight so it has less inbuilt support in compare to 
django and rails. But this problem can be solved by integrating 
third party tools, but for large and very custom websites it may be 
a tedious task 
● 0
● Q3. 
● Explain Events in laravel ? 
● Posted by ​Sharad Jaiswal 
● An event is an action or occurrence recognized by a program that may 
be handled by the program or code. Laravel events provides a simple 
observer implementation, that allowing you to subscribe and listen for 
various events/actions that occur in your application. 
● All Event classes are generally stored in the app/Events directory, while 
their listeners are stored in app/Listeners of your application.

Q4. 
● Explain validations in laravel? 
● Posted by ​Sharad Jaiswal 
● In Programming validations are a handy way to ensure that your 
data is always in a clean and expected format before it gets into 
your database. Laravel provides several different ways to validate 
your application incoming data.By default Laravel’s base 
controller class uses a ValidatesRequests trait which provides a 
convenient method to validate all incoming HTTP requests 
coming from client.You can also validate data in laravel by 
creating Form Request. 
● click here​ read more about data validations in Laravel. 

● 0
● Q5. 
● How to install laravel via composer ? 
● Posted by ​Sharad Jaiswal 
● You can install Laravel via composer by running below command. 
● composer create-project laravel/laravel your-project-name
version

● Also Read ​Core PHP Interview Questions and Answers for 2018 

● 0
● Q6. 
● List some features of laravel 5.0 ? 
● Posted by ​Sharad Jaiswal 
○ Inbuilt CRSF (​cross-site request forgery​ ) Protection. 
○ Inbuilt paginations 
○ Reverse Routing 
○ Query builder 
○ Route caching 
○ Database Migration 
○ IOC (Inverse of Control) Container Or service container. 
● 0
● Q7. 
● What is PHP artisan. List out some artisan 
commands ? 
● Posted by ​Sharad Jaiswal 
● PHP artisan is the command line interface/tool included with 
Laravel. It provides a number of helpful commands that can help 
you while you build your application easily. Here are the list of 
some artisan command:- 
○ php artisan list 
○ php artisan help 
○ php artisan tinker 
○ php artisan make 
○ php artisan –versian 
○ php artisan make model model_name 
○ php artisan make controller controller_name 
● 0
● Q8. 
● List some default packages provided by Laravel 
5.6 ? 
● Posted by ​Sharad Jaiswal 
● Below are list of some official/ default packages provided by 
Laravel 5.6 
○ Cashier 
○ Envoy 
○ Passport 
○ Scout 
○ Socialite 
○ Horizon 
● 0
● Q9. 
● What are named routes in Laravel? 
● Posted by ​Sharad Jaiswal 
● Named routing is another amazing feature of Laravel framework. 
Named routes allow referring to routes when generating 
redirects or Urls more comfortably. 
● You can specify named routes by chaining the name method 
onto the route definition: 
● Route::get('user/profile', function () {
//
})->name('profile');

● You can specify route names for controller actions: 


● Route::get('user/profile',
'UserController@showProfile')->name('profile');
● Once you have assigned a name to your routes, you may use the 
route's name when generating URLs or redirects via the global 
route function: 
● // Generating URLs...
$url = route('profile');
// Generating Redirects...
return redirect()->route('profile');

● 0
● Q10. 
● What is database migration. How to create 
migration via artisan ? 
● Posted by ​Sharad Jaiswal 
● Migrations are like version control for your database, that’s allow 
your team to easily modify and share the application’s database 
schema. Migrations are typically paired with Laravel’s schema 
builder to easily build your application’s database schema. 
● Use below commands to create migration data via artisan. 
● // creating Migration
php artisan make:migration create_users_table
● 0
● Q11. 
● What are service providers ? 
● Posted by ​Sharad Jaiswal 
● Service Providers are central place where all laravel application is 
bootstrapped . Your application as well all Laravel core services 
are also bootstrapped by service providers. 
● All service providers extend the 
Illuminate\Support\ServiceProvider class. Most service providers 
contain a register and a boot method. Within the register 
method, you should only bind things into the service container. 
You should never attempt to register any event listeners, routes, 
or any other piece of functionality within the register method. 
● You can read more about service provider from h
​ ere 

● 0
● Q12. 
● Explain Laravel’s service container ? 
● Posted by ​Sharad Jaiswal 
● One of the most powerful feature of Laravel is its Service 
Container. It is a powerful tool for resolving class dependencies 
and performing dependency injection in Laravel. 
● Dependency injection is a fancy phrase that essentially means 
class dependencies are “injected” into the class via the 
constructor or, in some cases, “setter” methods. 

● 0
● Q13. 
● What is composer ? 
● Posted by ​Sharad Jaiswal 
● Composer is a tool for managing dependency in PHP. It allows 
you to declare the libraries on which your project depends on and 
will manage (install/update) them for you. 
● Laravel utilizes Composer to manage its dependencies. 

● 0
● Q14. 
● What is dependency injection in Laravel ? 
● Posted by ​Sharad Jaiswal 
● In software engineering, dependency injection is a technique 
whereby one object supplies the dependencies of another object. 
A dependency is an object that can be used (a service). An 
injection is the passing of a dependency to a dependent object (a 
client) that would use it. The service is made part of the client’s 
state.[1] Passing the service to the client, rather than allowing a 
client to build or find the service, is the fundamental requirement 
of the pattern. 
● https://en.wikipedia.org/wiki/Dependency_injection 

● You can do dependency injection via Constructor, setter and 


property injection. 

● 0
● Q15. 
● What are Laravel Contract’s ? 
● Posted by ​Sharad Jaiswal 
● Laravel’s Contracts are nothing but a set of interfaces that define 
the core services provided by the Laravel framework. 
● Read more about laravel Contract’s 

● 0
● Q16. 
● Explain Facades in Laravel ? 
● Posted by ​Sharad Jaiswal 
● Laravel Facades provides a static like an interface to classes that 
are available in the application’s service container. Laravel 
self-ships with many facades which provide access to almost all 
features of Laravel ’s. Laravel facades serve as “static proxies” to 
underlying classes in the service container and provide benefits of 
a terse, expressive syntax while maintaining more testability and 
flexibility than traditional static methods of classes. All of Laravel’s 
facades are defined in the Illuminate\Support\Facades 
namespace. You can easily access a facade like so: 

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
return Cache::get('key');
});

● 0
● Q17. 
● What are Laravel eloquent? 
● Posted by ​Sharad Jaiswal 
● Laravel’s Eloquent ORM is simple Active Record implementation 
for working with your database. Laravel provide many different 
ways to interact with your database, Eloquent is most notable of 
them. Each database table has a corresponding “Model” which is 
used to interact with that table. Models allow you to query for 
data in your tables, as well as insert new records into the table. 
● Below is sample usage for querying and inserting new records in 
Database with Eloquent. 

// Querying or finding records from products table where
tag is 'new'
$products= Product::where('tag','new');
// Inserting new record
$product =new Product;
$product->title="Iphone 7";
$product->price="$700";
$product->tag='iphone';
$product->save();

● 0
● Q18. 
● How to enable query log in Laravel ? 
● Posted by ​Sharad Jaiswal 
● Use the enableQueryLog method to enable query log in Laravel 

DB::connection()->enableQueryLog();
You can get array of the executed queries by using
getQueryLog method:
$queries = DB::getQueryLog();

● 0
● Q19. 
● What is reverse routing in Laravel? 
● Posted by ​Sharad Jaiswal 
● Laravel reverse routing is generating URL's based on route 
declarations. Reverse routing makes your application so much 
more flexible. It defines a relationship between links and Laravel 
routes. When a link is created by using names of existing routes, 
appropriate Uri's are created automatically by Laravel. Here is an 
example of reverse routing. 
● // route declaration 
● Route::get(‘login’, ‘users@login’);
● Using reverse routing we can create a link to it and pass in any 
parameters that we have defined. Optional parameters, if not 
supplied, are removed from the generated link. 
● {{ HTML::link_to_action('users@login') }}

● It will automatically generate an Url like http://xyz.com/login in 


view. 

● 0
● Q20. 
● How to turn off CRSF protection for specific 
route in Laravel? 
● Posted by ​Sharad Jaiswal 
● To turn off CRSF protection in Laravel add following codes in 
“app/Http/Middleware/VerifyCsrfToken.php” 

//add an array of Routes to skip CSRF check
private $exceptUrls = ['controller/route1',
'controller/route2'];
//modify this function
public function handle($request, Closure $next) {
//add this condition foreach($this->exceptUrls as $route)
{
if ($request->is($route)) {
return $next($request);
}
}
return parent::handle($request, $next);
}
● 0
● Q21. 
● What are traits in Laravel? 
● Posted by ​Sharad Jaiswal 
● PHP Traits are simply a group of methods that you want include 
within another class. A Trait, like an abstract class cannot be 
instantiated by itself.Trait are created to reduce the limitations of 
single inheritance in PHP by enabling a developer to reuse sets of 
methods freely in several independent classes living in different 
class hierarchies. 
● Here is an example of trait. 
● trait Sharable {

public function share($item)


{
return 'share this item';
}

● You could then include this Trait within other classes like this: 

class Post {

use Sharable;
}

class Comment {

use Sharable;

● Now if you were to create new objects out of these classes you 
would find that they both have the share() method available: 

$post = new Post;
echo $post->share(''); // 'share this item'

$comment = new Comment;


echo $comment->share(''); // 'share this item'

● 0
● Q22. 
● Does Laravel support caching? 
● Posted by ​Sharad Jaiswal 
● Yes, Laravel supports popular caching backends like Memcached 
and Redis. 
● By default, Laravel is configured to use the file cache driver, which 
stores the serialized, cached objects in the file system.For large 
projects, it is recommended to use Memcached or Redis. 

● 0
● Q23. 
● Explain Laravel’s Middleware? 
● Posted by ​Sharad Jaiswal 
● As the name suggests, Middleware acts as a middleman between 
request and response. It is a type of filtering mechanism. For 
example, Laravel includes a middleware that verifies whether the 
user of the application is authenticated or not. If the user is 
authenticated, he will be redirected to the home page otherwise, 
he will be redirected to the login page. 
● There are two types of Middleware in Laravel. 
● Global Middleware: will run on every HTTP request of the 
application. 
● Route Middleware: will be assigned to a specific route. 
● Read more about Laravel middlewares 

● 0
● Q24. 
● What is Lumen? 
● Posted by ​Sharad Jaiswal 
● Lumen is PHP micro-framework that built on Laravel’s top 
components.It is created by Taylor Otwell. It is perfect option for 
building Laravel based micro-services and fast REST API’s. It’s one 
of the fastest micro-frameworks available. 
● You can install Lumen using composer by running below 
command 
● composer create-project --prefer-dist laravel/lumen blog
● 0
● Q25. 
● Explain Bundles in Laravel? 
● Posted by ​Sharad Jaiswal 
● In Laravel, bundles are also called packages.Packages are the 
primary way to extend the functionality of Laravel. Packages 
might be anything from a great way to work with dates like 
Carbon, or an entire BDD testing framework like Behat.In Laravel, 
you can create your custom packages too.You can read more 
about packages from ​here 

● 0
● Q26. 
● How to use custom table in Laravel Modal ? 
● Posted by ​Sharad Jaiswal 
● You can use custom table in Laravel by overriding protected 
$table property of Eloquent. 

Below is sample uses

class User extends Eloquent{


protected $table="my_user_table";

}
● 0
● Q27. 
● List types of relationships available in Laravel 
Eloquent? 
● Posted by ​Sharad Jaiswal 
● Below are types of relationships supported by Laravel Eloquent 
ORM. 
○ One To One 
○ One To Many 
○ One To Many (Inverse) 
○ Many To Many 
○ Has Many Through 
○ Polymorphic Relations 
○ Many To Many Polymorphic Relations 
● You can read more about relationships in Laravel Eloquent from 
here 

● 0
● Q28. 
● Why are migrations necessary? 
● Posted by ​Sharad Jaiswal 
● Migrations are necessary because: 
○ Without migrations, database consistency when sharing 
an app is almost impossible, especially as more and more 
people collaborate on the web app. 
○ Your production database needs to be synced as well. 
● 0
● Q29. 
● Provide System requirements for installation of 
Laravel 5.4 ? 
● Posted by ​Sharad Jaiswal 
● In order to install laravel,make sure your server meets the 
following requirements: 
○ PHP >= 5.6.4 
○ OpenSSL PHP Extension 
○ PDO PHP Extension 
○ Mbstring PHP Extension 
○ Tokenizer PHP Extension 
○ XML PHP Extension 
● 0
● Q30. 
● List some Aggregates methods provided by 
query builder in Laravel ? 
● Posted by ​Sharad Jaiswal 
○ count() 
○ max() 
○ min() 
○ avg() 
○ sum() 
 
 
1) What is the Laravel? 

A) Laravel is an open-source PHP web framework, created for the 


development of web applications following the model–view–controller 
(MVC) architectural pattern. 

2) What is Laravel Horizon? 

A) Laravel Horizon provides a beautiful dashboard and code-driven 


configuration for your Redis queues. 

3) What is Laravel Dusk? 

A) Laravel Dusk provides an expressive, easy-to-use browser automation 


and testing API. You’ll love it. 

4) What is Laravel Echo? 

A) Event broadcasting, evolved. Bring the power of WebSockets to your 


application without the complexity. 

5) How do you install Laravel? 

A) Laravel utilizes Composer to manage its dependencies. So, before using 


Laravel, make sure we have Composer installed on your machine. 

  

6) What is Composer Tool? 


A) Composer is a tool for dependency management in PHP. It allows you to 
declare the libraries your project depends on and it will manage 
(install/update) them for you. 

  

7) What is Laravel service container? 

A) The Laravel service container is a powerful tool for managing class 


dependencies and performing dependency injection. Dependency injection 
is a fancy phrase that essentially means this: class dependencies are 
“injected” into the class via the constructor or, in some cases, “setter” 
methods. 

  

8) What is Binding? 

A) Within a service provider, we always have access to the container via the 
$this->app property. We can register a binding using the bind method, 
passing the class or interface name that we wish to register along with a 
Closure that returns an instance of the class: 

$this->app->bind(‘HelpSpot\API’, function ($app) { 

return new HelpSpot\API($app->make(‘HttpClient’)); 

}); 

9) Explain Binding A Singleton? 

A) The singleton method binds a class or interface into the container that 
should only be resolved one time. Once a singleton binding is resolved, the 
same object instance will be returned on subsequent calls into the container. 

  

10) Explain Binding Instances? 


A) You may also bind an existing object instance into the container using the 
instance method. The given instance will always be returned on subsequent 
calls into the container: 

$api = new HelpSpot\API(new HttpClient); 

$this->app->instance(‘HelpSpot\API’, $api); 

Top 65 Laravel Interview Questions 

Laravel Interview Questions # 11) Explain Binding Primitives? 

A) Sometimes you may have a class that receives some injected classes, but 
also needs an injected primitive value such as an integer. You may easily use 
contextual binding to inject any value your class may need: 

$this->app->when(‘App\Http\Controllers\UserController’) 

->needs(‘$variableName’) 

->give($value); 

  

Laravel Interview Questions # 12) Explain Contextual Binding and how 


does it work? 

A) Sometimes you may have two classes that utilize the same interface, but 
you wish to inject different implementations into each class. For example, 
two controllers may depend on different implementations of the 
Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a 
simple, fluent interface for defining this behavior: 

use Illuminate\Support\Facades\Storage; 

use App\Http\Controllers\PhotoController; 

use App\Http\Controllers\VideoController; 
use Illuminate\Contracts\Filesystem\Filesystem; 

$this->app->when(PhotoController::class) 

->needs(Filesystem::class) 

->give(function () { 

return Storage::disk(‘local’); 

}); 

$this->app->when(VideoController::class) 

->needs(Filesystem::class) 

->give(function () { 

return Storage::disk(‘s3’); 

}); 

Laravel Interview Questions # 13) What is Tagging? 

A) Occasionally, you may need to resolve all of a certain “category” of 


binding. For example, perhaps you are building a report aggregator that 
receives an array of many different Report interface implementations. After 
registering the Report implementations, you can assign them a tag using 
the tag method: 

$this->app->bind(‘SpeedReport’, function () { 

// 

}); 

$this->app->bind(‘MemoryReport’, function () { 
// 

}); 

$this->app->tag([‘SpeedReport’, ‘MemoryReport’], ‘reports’); 

Once the services have been tagged, you may easily resolve them all via the 
tagged method: 

$this->app->bind(‘ReportAggregator’, function ($app) { 

return new ReportAggregator($app->tagged(‘reports’)); 

}); 

  

Laravel Interview Questions # 14) Explain Extending Bindings? 

A) The extend method allows the modification of resolved services. For 


example, when a service is resolved, you may run additional code to 
decorate or configure the service. The extend method accepts a Closure, 
which should return the modified service, as its only argument: 

$this->app->extend(Service::class, function($service) { 

return new DecoratedService($service); 

}); 

Laravel Interview Questions # 15) What is the make Method? 

A) You may use the make method to resolve a class instance out of the 
container. The make method accepts the name of the class or interface you 
wish to resolve: 

$api = $this->app->make(‘HelpSpot\API’); 
Laravel Interview Questions # 16) What are service providers? 

A) Service providers are the central place of all Laravel application 


bootstrapping. Your own application, as well as all of Laravel’s core services 
are bootstrapped via service providers. 

Laravel Interview Questions # 17) What is Register Method? 

A) within the register method, you should only bind things into the service 
container. You should never attempt to register any event listeners, routes, 
or any other piece of functionality within the register method. 

Laravel Interview Questions # 18) Explain the bindings And singletons 


Properties? 

A) If your service provider registers many simple bindings, you may wish to 
use the bindings and singletons properties instead of manually registering 
each container binding. When the service provider is loaded by the 
framework, it will automatically check for these properties and register 
their bindings 

Laravel Interview Questions # 19) What is the Boot Method? 

A) if we need to register a view composer within our service provider? This 


should be done within the boot method. This method is called after all other 
service providers have been registered, meaning you have access to all other 
services that have been registered by the framework. 

Laravel Interview Questions # 20) Where do you r​ egiser​ service providers? 

A) All service providers are registered in the config/app.php configuration 


file. This file contains a providers array where you can list the class names of 
your service providers. 

PHP Laravel Interview Questions And Answers 

Laravel Interview Questions # 21) How do you register service providers? 


A) To register your provider, add it to the array: 

‘providers’ => [ 

// Other Service Providers 

App\Providers\ComposerServiceProvider::class, 

], 

Laravel Interview Questions # 22) What are Facades? 

A) Facades provide a “static” interface to classes that are available in the 


application’s service container. 

Laravel Interview Questions # 23) Where Laravel’s facades are defined? 

A) All of Laravel’s facades are defined in the Illuminate\Support\Facades 


namespace 

Laravel Interview Questions # 24) What are the benefits of Facades? 

A) Facades have many benefits. They provide a terse, memorable syntax that 
allows you to use Laravel’s features without remembering long class names 
that must be injected or configured manually. Furthermore, because of their 
unique usage of PHP’s dynamic methods, they are easy to test. 

Laravel Interview Questions # 25) Difference between Facades Vs. 


Dependency Injection? 

A) One of the primary benefits of dependency injection is the ability to swap 


implementations of the injected class. This is useful during testing since you 
can inject a mock or stub and assert that various methods were called on the 
stub. 

Typically, it would not be possible to mock or stub a truly static class 


method. However, since facades use dynamic methods to proxy method 
calls to objects resolved from the service container, we actually can test 
facades just as we would test an injected class instance. 
Laravel Interview Questions # 26) What is the difference between Facades 
Vs​ Helper Functions? 

A) In addition to facades, Laravel includes a variety of “helper” functions 


which can perform common tasks like generating views, firing events, 
dispatching jobs, or sending HTTP responses. Many of these helper 
functions perform the same function as a corresponding facade. 

Laravel Interview Questions # 27) What are Laravel’s Contracts? 

A) Laravel’s Contracts are a set of interfaces that define the core services 
provided by the framework. For example, a 
Illuminate\Contracts\Queue\Queue contract defines the methods needed for 
queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines 
the methods needed for sending e-mail. 

Laravel Interview Questions # 28) What is the difference between 


Contracts Vs Facades? 

A) Laravel’s facades and helper functions provide a simple way of utilizing 


Laravel’s services without needing to type-hint and resolve contracts out of 
the service container. In most cases, each facade has an equivalent contract. 

Unlike facades, which do not require you to require them in your class’ 
constructor, contracts allow you to define explicit dependencies for your 
classes. Some developers prefer to explicitly define their dependencies in 
this way and therefore prefer to use contracts, while other developers enjoy 
the convenience of facades. 

Laravel Interview Questions # 29) What is Routing in Laravel? 

A) The most basic Laravel routes accept a URI and a Closure, providing a 
very simple and expressive method of defining routes: 

Route::get(‘foo’, function () { 

return ‘Hello World’; 

}); 
Laravel Interview Questions # 30) Where do you locate Route files? 

A) All Laravel routes are defined in your route files, which are located in the 
routes directory. 

Laravel PHP Developer Interview Questions 

Laravel Interview Questions # 31) What are the available Router Methods? 

A) The router allows you to register routes that respond to any HTTP verb: 

Route::get($uri, $callback); 

Route::post($uri, $callback); 

Route::put($uri, $callback); 

Route::patch($uri, $callback); 

Route::delete($uri, $callback); 

Route::options($uri, $callback); 

Laravel Interview Questions # 32) What is CSRF Protection? 

A) aravel makes it easy to protect your application from cross-site request 


forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious 
exploit whereby unauthorized commands are performed on behalf of an 
authenticated user. 

Laravel Interview Questions # 33) What is CSRF Protection Token? 

A) Any HTML forms pointing to POST, PUT, or DELETE routes that are 
defined in the web routes file should include a CSRF token field. Otherwise, 
the request will be rejected. 

<form method=”POST” action=”/profile”> 


@csrf 

… 

</form> 

Laravel Interview Questions # 34) What is Redirect Routes? 

A) If you are defining a route that redirects to another URI, you may use the 
Route::redirect method. 

Route::redirect(‘/here’, ‘/there’, 301); 

Laravel Interview Questions # 35) What is View Routes? 

A) If your route only needs to return a view, you may use the Route:: view 
method. The view method accepts a URI as its first argument and a view 
name as its second argument. In addition, you may provide an array of data 
to pass to the view as an optional third argument. 

Route::view(‘/welcome’, ‘welcome’); 

Route::view(‘/welcome’, ‘welcome’, [‘name’ => ‘Taylor’]); 

Laravel Interview Questions # 36) What is Named Routes? 

A) Named routes allow the convenient generation of URLs or redirects for 


specific routes. You may specify a name for a route by chaining the name 
method onto the route definition: 

Route::get(‘user/profile’, function () { 

// 

})->name(‘profile’); 

Laravel Interview Questions # 37) What are Route Groups? 


A) Route groups allow you to share route attributes, such as middleware or 
namespaces, across a large number of routes without needing to define 
those attributes on each individual route. 

38) What is Route Model Binding? 

A) When injecting a model ID to a route or controller action, you will often 


query to retrieve the model that corresponds to that ID. Laravel route model 
binding provides a convenient way to automatically inject the model 
instances directly into your routes. 

Laravel Interview Questions # 39) What is Rate Limiting? 

A) Laravel includes a middleware to rate limit access to routes within your 


application. To get started, assign the throttle middleware to a route or a 
group of routes. 

The throttle middleware accepts two parameters that determine the 


maximum number of requests that can be made in a given number of 
minutes. For example, let’s specify that an authenticated user may access 
the following group of routes 60 times per minute: 

Route::middleware(‘auth:api’, ‘throttle:60,1’)->group(function () { 

Route::get(‘/user’, function () { 

// 

}); 

}); 

Laravel Interview Questions # 40) What is Middleware? 

A) Middleware provide a convenient mechanism for filtering HTTP requests 


entering your application. 

Advanced Laravel Interview Questions And Answers 


41) How do you define Middleware? 

A) To create a new middleware, use the make:middleware Artisan 


command: 

php artisan make:middleware CheckAge 

This command will place a new CheckAge class within your 


app/Http/Middleware directory. 

42) What are Middleware Groups? 

A) Sometimes you may want to group several middleware under a single key 
to make them easier to assign to routes. You may do this using the 
$middlewareGroups property of your HTTP kernel. 

43) What is X-CSRF-TOKEN? 

A) In addition to checking for the CSRF token as a POST parameter, the 


VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request 
header. You could, for example, store the token in a HTML meta tag: 

<meta name=”csrf-token” content=”{{ csrf_token() }}”> 

44) What is X-XSRF-TOKEN? 

A) Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is 
included with each response generated by the framework. You can use the 
cookie value to set the X-XSRF-TOKEN request header. 

45) What is Response in Laravel? 

A) All routes and controllers should return a response to be sent back to the 
user’s browser. Laravel provides several different ways to return responses. 
The most basic response is returning a string from a route or controller. The 
framework will automatically convert the string into a full HTTP response: 

Route::get(‘/’, function () { 
return ‘Hello World’; 

}); 

46) What are Redirect responses? 

A) Redirect responses are instances of the 


Illuminate\Http\RedirectResponse class, and contain the proper headers 
needed to redirect the user to another URL. There are several ways to 
generate a RedirectResponse instance. The simplest method is to use the 
global redirect helper: 

Route::get(‘dashboard’, function () { 

return redirect(‘home/dashboard’); 

}); 

47) What is Response Macros? 

A) If you would like to define a custom response that you can re-use in a 
variety of your routes and controllers, you may use the macro method on 
the Response facade. 

48) What is View? 

A) Views contain the HTML served by your application and separate your 
controller / application logic from your presentation logic. Views are stored 
in the resources/views directory. A simple view might look something like 
this: 

<!– View stored in resources/views/greeting.blade.php –> 

<html> 

<body> 

<h1>Hello, {{ $name }}</h1> 


</body> 

</html> 

48) What are View Composers? 

A) View composers are callbacks or class methods that are called when a 
view is rendered. If you have data that you want to be bound to a view each 
time that view is rendered, a view composer can help you organize that logic 
into a single location. 

49) What ​are​ View Creators? 

A) View creators are very similar to view composers; however, they are 
executed immediately after the view is instantiated instead of waiting until 
the view is about to render. To register a view creator, use the creator 
method: 

View::creator(‘profile’, ‘App\Http\ViewCreators\ProfileCreator’); 

50) How do you generate URLs? 

A) Laravel provides several helpers to assist you in generating URLs for your 
application. Of course, these are mainly helpful when building links in your 
templates and API responses, or when generating redirect responses to 
another part of your application. 

Laravel Interview Questions For 2, 3, 4, 5 Years Experience 

51) What is u
​ rl​ helper? 

A) The url helper may be used to generate arbitrary URLs for your 
application. The generated URL will automatically use the scheme (HTTP or 
HTTPS) and host from the current request: 

$post = App\Post::find(1); 

echo url(“/posts/{$post->id}”); 
// http://example.com/posts/1 

52) Exceptions are handled by which class? 

A) All exceptions in Laravel are handled by the App\Exceptions\Handler 


class. This class contains two methods: report and render. 

53) What is report method? 

A) The report method is used to log exceptions or send them to an external 


service like Bugsnag or Sentry. By default, the report method passes the 
exception to the base class where the exception is logged. However, you are 
free to log exceptions however you wish. 

54) What is the render method? 

A) The render methos is responsible for converting a given exception into an 
HTTP response that should be sent back to the browser. By default, the 
exception is passed to the base class which generates a response for you. 

55) What are HTTP Exceptions? 

A) Some exceptions describe HTTP error codes from the server. For 
example, this may be a “page not found” error (404), an “unauthorized 
error” (401) or even a developer generated 500 error. 

56) What is Monolog library? 

A) Laravel utilizes the Monolog library, which provides support for a variety 
of powerful log handlers. Laravel makes it a cinch to configure these 
handlers, allowing you to mix and match them to customize your 
application’s log handling. 

57) What is stack channel? 

A) By default, Laravel will use the stack channel when logging messages. 
The stack channel is used to aggregate multiple log channels into a single 
channel. 
58) What are Blade Templates? 

A) Blade is the simple, yet powerful templating engine provided with 


Laravel. Unlike other popular PHP templating engines, Blade does not 
restrict you from using plain PHP code in your views. 

59) Where is the authentication configuration file is located in Laravel? 

A) The authentication configuration file is located at config/auth.php, which 


contains several well documented options for tweaking the behavior of the 
authentication services. 

60) What is fluent query builder in Laravel? 

A) Laravel’s database query builder provides a convenient, fluent interface 


to creating and running database queries. It can be used to perform most 
database operations in your application and works on all supported 
database systems. 

The Laravel query builder uses PDO parameter binding to protect your 
application against SQL injection attacks. There is no need to clean strings 
being passed as bindings. 

61) What is Eloquent ORM in Laravel? 

The Eloquent ORM included with Laravel provides a beautiful, simple 


ActiveRecord implementation for working with your database. Each 
database table has a corresponding “Model” which is used to interact with 
that table. Models allow you to query for data in your tables, as well as insert 
new records into the table. 

62) Laravle supports which databases? 

A) Laravel makes interacting with databases extremely simple across a 


variety of database backends using either raw SQL, the fluent query builder, 
and the Eloquent ORM. Currently, Laravel supports four databases: 

MySQL 
PostgreSQL 

SQLite 

SQL Server 

63) Where do you locate database configuration file? 

A) The database configuration for your application is located at 


config/database.php. In this file you may define all of your database 
connections, as well as specify which connection should be used by default. 

64) What is Redis? 

A) Redis is an open source, advanced key-value store. It is often referred to 


as a data structure server since keys can contain strings, hashes, lists, sets, 
and sorted sets. 

65) Can you explain about Serialization? 

A) When building JSON APIs, you will often need to convert your models and 
relationships to arrays or JSON. Eloquent includes convenient methods for 
making these conversions, as well as controlling which attributes are 
included in your serializations. 

Serializing To Arrays – To convert a model and its loaded relationships to 


an array, you should use the toArray method. 

$user = App\User::with(‘roles’)->first(); 

return $user->toArray(); 

You may also convert entire collections of models to arrays: 

$users = App\User::all(); 

Serializing To JSON – To convert a model to JSON, you should use the toJson 
method. Like toArray, the toJson method is recursive, so all attributes and 
relations will be converted to JSON: 
$user = App\User::find(1); 

return $user->toJson(); 

return $users->toArray(); 

1. ​What is Laravel

Laravel is free open source “​PHP framework​” based on MVC Design Pattern.

It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in
creating a wonderful web application easily and quickly.

Read More

2. ​List some official packages provided by Laravel


Below are some official packages provided by Laravel

● Cashier :​​Laravel Cashier provides an expressive, fluent interface to Stripe’s and


Braintree’s subscription billing services. It handles almost all of the boilerplate
subscription billing code you are dreading writing. In addition to basic subscription
management, Cashier can handle coupons, swapping subscription, subscription
“quantities”, cancellation grace periods, and even generate invoice PDFs.​Read More
● Envoy :​​Laravel Envoy provides a clean, minimal syntax for defining common tasks you
run on your remote servers. Using Blade style syntax, you can easily setup tasks for
deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and
Linux operating systems.
● Read More
● Passport :​​Laravel makes API authentication a breeze using Laravel Passport, which
provides a full OAuth2 server implementation for your Laravel application in a matter of
minutes. Passport is built on top of the League OAuth2 server that is maintained by Alex
Bilbie.
● Read More
● Scout :​​Laravel Scout provides a simple, driver based solution for adding full-text search
to your Eloquent models. Using model observers, Scout will automatically keep your
search indexes in sync with your Eloquent records.​Read More
● Socialite :​​Laravel Socialite provides an expressive, fluent interface to OAuth
authentication with Facebook, Twitter, Google, LinkedIn, GitHub and Bitbucket. It handles
almost all of the boilerplate social authentication code you are dreading writing.​Read
More

3. ​What is Lumen?

Lumen ​is PHP micro framework that built on Laravel’s top components. It is created by Taylor
Otwell.

It is the perfect option for building Laravel based micro-services and fast REST API’s.

It’s one of the fastest micro-frameworks available.​ Read More

4. ​List out some benefits of Laravel over other


Php frameworks ?
Top benifits of laravel framework

1. Setup and customization process is easy and fast as compared to others.


2. Inbuilt Authentication System.
3. Supports multiple file systems
4. Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel
elixir,Passport,Laravel Scout.
5. Eloquent ​ORM (Object Relation Mapping) with PHP active record implementation.
6. Built in command line tool “Artisan” for creating a code skeleton ,​database structure​ and
build their ​migration​.

6. ​What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.

It allows you to declare the libraries your project depends on and it will manage (install/update)
them for you.

It provides us a nice way to reuse any kind of code. Rather than all of us reinventing the wheel
over and over, we can instead download popular packages.

7. ​How to install Laravel via composer ?

To install Laravel with composer run below command on your terminal.

composer create-project Laravel/Laravel your-project-name version

8. ​What is php artisan. List out some artisan


commands ?
PHP artisan is the command line interface/tool included with Laravel. It provides a number of
helpful commands that can help you while you build your application easily. Here are the list of
some artisian command.

● php artisan list


● php artisan help
● php artisan tinker
● php artisan make
● php artisan –versian
● php artisan make model model_name
● php artisan make controller controller_name

9. ​How to check current installed version of


Laravel ?

Use ​php artisan –version​​ command to check current installed version of Laravel Framework

Usage:

php artisan --version

10. ​List some Aggregates methods provided by


query builder in Laravel ?
Aggregate function is a function where the values of multiple rows are grouped together as input
on certain criteria to form a single value of more significant meaning or measurements such as a
set, a bag or a list

Below is list of some Aggregates methods provided by Laravel query builder.

● count()
● Usage:$products = DB::table(‘products’)->count();
● max()
● Usage:$price = DB::table(‘orders’)->max(‘price’);
● min()
● Usage:$price = DB::table(‘orders’)->min(‘price’);
● avg()
● Usage:$price = DB::table(‘orders’)->avg(‘price’);
● sum()
● Usage: $price = DB::table(‘orders’)->sum(‘price’);

11. ​Explain Events in Laravel ?

what are laravel events

An event is an incident or occurrence detected and handled by the program.Laravel event


provides a simple observer implementation, that allow us to subscribe and listen for events in our
application.An event is an incident or occurrence detected and handled by the program.Laravel
event provides a simple observer implementation, that allows us to subscribe and listen for
events in our application.

Below are some events examples in Laravel:-

● A new user has registered


● A new comment is posted
● User login/logout
● New product is added.

12. How to turn off CRSF protection for a route


in Laravel ?
To turn off or diasble​ CRSF protection​​ for specific routes in Laravel open
“app/Http/Middleware/VerifyCsrfToken.php” ​file and add following code in it

//add this in your class


private $exceptUrls = ['controller/route1', 'controller/route2'];

//modify this function

public function handle($request, Closure $next)


{

//add this condition


foreach($this->exceptUrls as $route) {

if ($request->is($route)) {

return $next($request);

}
return parent::handle($request, $next);}

13. What happens when you type “php artisan” in


the command line?
When you type “PHP artisan” it lists of a few dozen different command options.

14. ​Which template engine Laravel use ?


​ ​​ ​​ ​​ Laravel uses Blade Templating Engine.

Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular
PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In
fact, all Blade views are compiled into plain PHP code and cached until they are modified,
meaning Blade adds essentially zero overhead to your application. Blade view files use the
.blade.php file extension and are typically stored in the resources/views directory.

15. How can you change your default database


type ?
By default Laravel is configured to use MySQL.In order to change your default database edit your
config/database.php and search for ​‘default’ => ‘mysql’​​ and change it to whatever you want
(like ​‘default’ => ‘sqlite’​​).

16. ​Explain Migrations in Laravel ? How can you


generate migration .
what are laravel migrations

Laravel Migrations​​ are like version control for your database, allowing a team to easily modify
and share the application’s database schema. Migrations are typically paired with Laravel’s
schema builder to easily build your application’s database schema.

Steps to Generate Migrations in Laravel

● To create a migration, use the make:migration ​Artisan​ command


● When you create a migration file, Laravel stores it in /database/migrations directory.
● Each migration file name contains a timestamp which allows Laravel to determine the
order of the migrations.
● Open the command prompt or terminal depending on your operating system.

17. What are service providers in laravel ?


Service providers are the central place of all Laravel application bootstrapping. Your own
application, as well as all of Laravel’s core services are bootstrapped via service providers.
Service provider basically registers event listeners, middleware, routes to Laravel’s service
container.

All service providers need to be registered in ​providers array​​ of ​app/config.php​​ file.

18. How do you register a Service Provider?


To register a service provider follow below steps

● Open to config/app.php
● Find ‘providers’ array of the various ServiceProviders.
● Add namespace ​‘Iluminate\Abc\ABCServiceProvider:: class,’​​ to the end of the array.

19. What are Implicit Controllers ?


​Implicit Controllers​​ allow you to define a single route to handle every action in the controller.
You can define it in route.php file with Route: controller method.

Usage :

Route::controller('base URI','');

20. What does “composer dump-autoload” do?


Whenever we run ​“composer dump-autoload”

Composer re-reads the​ composer.json​​ file to build up the list of files to autoload.

21. Explain Laravel service container ?


One of the most powerful feature of Laravel is its ​Service Container .

It is a powerful tool for resolving class dependencies and performing dependency injection in
Laravel.
Dependency injection is a fancy phrase that essentially means class dependencies are “injected”
into the class via the ​constructor​​ or, in some cases, ​“setter”​​ methods.

22. How can you get users IP address in Laravel


You can use request’s class ​ip()​​ method to get IP address of user in Laravel.

Usage:

public function getUserIp(Request $request){


// Getting ip address of remote user
return $user_ip_address=$request->ip();

23. How to enable query log in Laravel?


Use the enableQueryLog method: Use the enableQueryLog method:

DB::connection()->enableQueryLog();

You can get an array of the executed queries by using the getQueryLog method:

$queries = DB::getQueryLog();

24. What are Laravel Facades ?


Laravel Facades provides a static like interface to classes that are available in the application’s
service container.

Laravel self ships with many facades which provide access to almost all features of Laravel’s.

Laravel Facades serve as “static proxies” to underlying classes in the service container and
provides benefits of a terse, expressive syntax while maintaining more testability and flexibility
than traditional static methods of classes. All of Laravel’s facades are defined in the
IlluminateSupportFacades namespace. You can easily access a Facade like so:
use IlluminateSupportFacadesCache;
Route::get('/cache', function () {
return Cache::get('key');
});

25. How to use custom table in Laravel Model ?


We can use custom table in Laravel by overriding protected $table property of Eloquent. Below is
sample uses

class User extends Eloquent{


protected $table="my_custom_table";

26. How can you define Fillable Attribute in a


Laravel Model ?​​You can define fillable attribute by overiding the fillable property
of Laravel Eloquent. Here is sample uses

Class User extends Eloquent{


protected $fillable =array('id','first_name','last_name','age');
}

27. What is the purpose of the Eloquent cursor()


method in Laravel ?
The cursor method allows you to iterate through your database records using a cursor, which will
only execute a single query. When processing large amounts of data, the cursor method may be
used to greatly reduce your memory usage.

Example Usage
foreach (Product::where('name', 'bar')->cursor() as $flight) {

//do some stuff

28. ​What are Closures in laravel ?


​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​Closures​​ are an anonymous function that can be assigned to a variable or passed to
another function as an argument.A Closures can access variables outside the scope that it was
created.

29. ​What is Kept in vendor directory of Laravel ?


​ ​​ ​​ ​​ ​​ ​​ Any packages that are pulled from composer is kept in vendor directory of Laravel.

30. ​What are Laravel Contracts ?


​ ​​ ​​ ​​ ​​ ​​
Laravel’s Contracts are nothing but set of interfaces that define the core services provided
by the ​Laravel​​ framework.

You can read about How to Laravel contracts by ​How to use Laravel facade

31. ​What does PHP compact function do ?


​ ​​ ​​ ​​ ​​ ​​ ​compact() laravel

PHP compact function takes each key and tries to find a variable with that same name.If the
variable is found, them it builds an associative array.

32. ​In which directory controllers are located in


Laravel ?
​ ​​ ​​ ​​ We kept all controllers in ​App/Http/Controllers directory

33. Define ORM


Object-relational Mapping (ORM) is a programming technique for converting data between
incompatible type systems in object-oriented programming languages.

34. How to create a record in Laravel using


eloquent ?
To create a new record in the database using Laravel Eloquent, simply create a new model
instance, set attributes on the model, then call the save method: Here is sample Usage.

public function saveProduct(Request $request )


$product = new product;
$product->name = $request->name;
$product->description = $request->name;
$product->save();

35. ​How to get Logged in user info in Laravel ?


​ ​​ ​​ ​​ ​​ ​​ ​Auth::User()​​ function is used to get Logged in user info in Laravel.

Usage:-

if(Auth::check()){
$loggedIn_user=Auth::User();
dd($loggedIn_user);
}

36. ​Does Laravel support caching?


​ ​​ ​​ ​​ ​​ ​​ Yes, Laravel supports popular caching backends like Memcached and Redis.
By default, Laravel is configured to use the file cache driver, which stores the serialized,
cached objects in the file system .For large projects it is recommended to use Memcached
or Redis.

37. ​What are named routes in Laravel ?


​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ Named routing is another amazing feature of Laravel framework. Named routes
allow referring to routes when generating redirects or Url’s more comfortably.

You can specify named routes by chaining the name method onto the route definition:

Route::get('user/profile', function () {
//
})->name('profile');

You can specify route names for controller actions:

Route::get('user/profile', 'UserController@showProfile')->name('profile');

Once you have assigned a name to your routes, you may use the route's name
when generating URLs or redirects via the global route function:

// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

38. What are traits in Laravel ?


what are laravel traits
Laravel Traits are simply a group of methods that you want include within another class.
A Trait, like an abstract classes cannot be instantiated by itself.Trait are created to reduce
the limitations of single inheritance in PHP by enabling a developer to reuse sets of
methods freely in several independent classes living in different class hierarchies.

Here is an example of trait.

trait Sharable {

public function share($item)


{
return 'share this item';
}

}
You could then include this Trait within other classes like this:

class Post {

use Sharable;

class Comment {

use Sharable;

}
Now if you were to create new objects out of these classes you would find
that they both have the share() method available:
$post = new Post;
echo $post->share(''); // 'share this item'

$comment = new Comment;


echo $comment->share(''); // 'share this item'

39. How to create migration via artisan ?


Use below commands to create migration data via artisan.

// creating Migration
php artisan make:migration create_users_table

40. Explain validations in laravel?


In Programming validations are a handy way to ensure that your data is always in a clean
and expected format before it gets into your database. Laravel provides several different
ways to validate your application incoming data.By default Laravel’s base controller class
uses a ValidatesRequests traitwhich provides a convenient method to validate all
incoming HTTP requests coming from client.You can also validate data in laravel by
creating Form Request.

41. Explain Laravel Eloquent


Laravel’s Eloquent ORM is one the most popular PHP ORM (OBJECT RELATIONSHIP
MAPPING).

It provides a beautiful, simple ActiveRecord implementation to work with your database.

In Eloquent each database table has the corresponding MODEL that is used to interact with table
and perform a database related operation on the table.

Sample Model Class in Laravel.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Users extends Model


{

}
42. Can laravel be hacked ?
answers to this question is ​NO​​.Laravel application’s are 100% secure (depends what you mean
by “secure” as well), in terms of things you can do to prevent unwanted data/changes done
without the user knowing.

Larevl have inbuilt CSRF security, input validations and encrypted session/cookies etc. Also,
Laravel uses a high encryption level for securing Passwords.

With every update, there’s the possibility of new holes but you can keep up to date with Symfony
changes and security issues on their site.

43. ​Does laravel support php 7


​ ​​ ​​ ​​ ​​ ​​ Yes,laravel supports php 7

44. Define Active Record Implementation. How to


use it Laravel
Active Record Implementation is an architectural pattern found in software engineering that
stores in-memory object data in relational databases. Active Record facilitates the creation and
use of business objects whose data is required to persistent in the database. Laravel implements
Active Records by Eloquent ORM. Below is sample usage of Active Records Implementation is
Laravel.

$product = new Product;

$product->title = 'Iphone 6s';

$product->save();

Active Record style ORMs map an object to a database row. In the above example, we would be
mapping the Product object to a row in the products table of database.

45. List Types of relationships supported by


Laravel ?
Laravel support 7 types of table relationships, they are

● One To One
● One To Many
● One To Many (Inverse)
● Many To Many
● Has Many Through
● Polymorphic Relations
● Many To Many Polymorphic Relations

46. Explain Laravel Query Builder ?


Laravel’s database query builder provides a suitable, easy interface to creating and organization
database queries. It can be used to achieve most database operations in our application and
works on all supported database systems. The Laravel query planner uses PDO restriction
necessary to keep our application against SQL injection attacks.

47. What is Laravel Elixir ?


Laravel Elixir provides a clean, fluent API for defining basic Gulp tasks for your Laravel
application. Elixir supports common CSS and JavaScript preprocessors like Sass and Webpack.
Using method chaining, Elixir allows you to fluently define your asset pipeline.

48. ​How to enable maintenance mode in Laravel 5


?
You can enable maintenance mode in Laravel 5, simply by executing below command.

//To enable maintenance mode


php artisan down
//To disable maintenance mode
php artisan up

49. List out Databases Laravel supports ?


Currently Laravel supports four major databases, they are :-

● MySQL
● Postgres
● SQLite
● SQL Server

50. How to get current environment in Laravel 5 ?


You may access the current application environment via the environment method.

$environment = App::environment();
dd($environment);

51. What is the purpose of using dd() function iin


laravel ?
Laravel’s dd() is a helper function ,which will dump a variable’s contents to the browser and halt
further script execution.

52. What is Method Spoofing in Laravel ?


As HTML forms does not supports PUT, PATCH or DELETE request. So, when defining PUT,
PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden
_method field to the form. The value sent with the _method field will be used as the HTTP
request method:

<form action="/foo/bar" method="POST">


<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

To generate the hidden input field _method, you may also use the method_field helper function:
<?php echo method_field('PUT'); ?>

In Blade template you can write it as below

{{ method_field('PUT') }}

53. What is the latest version of laravel


Laravel 5.5 is the latest version of Laravel. Here are steps to install and configure ​laravel 5.5

54. How to assign multiple middleware to Laravel


route ?
You can assign multiple middleware to Laravel route by using middleware method.

Example

// Assign multiple multiple middleware to Laravel to specific route

Route::get('/', function () {
//
})->middleware('firstMiddleware', 'secondMiddleware');

// Assign multiple multiple middleware to Laravel to route groups

Route::group(['middleware' => ['firstMiddleware','secondMiddleware']],


function () {
//
});

55. How can you display HTML with Blade in


laravel
To display html in laravel you can use below synatax.

{!! $your_var !!}

● Question 1. Does Laravel Support Caching? 


● Answer : 
● Yes, Its provides. 
● Question 2. How To Use Delete Statement In Laravel? 
● Answer : 
● DB::delete('delete from users where id = ?', [1015]); 
● Question 3. How To Use Update Statement In Laravel? 
● Answer : 
● DB::update('update users set city_id = 10 where id = ?', [1015]); 
● Question 4. How To Use Insert Statement In Laravel? 
● Answer : 
● DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web 
technology',10]); 
● Question 5. How To Use Select Query In Laravel? 
● Answer : 
$users = DB::select('select * from users where city_id = ?', 10); 
● if(!empty($users)){ 
● foreach($users as $user){ 
● } 
● }  
● Question 6. How To Enable The Query Logging? 
● Answer : 
● DB::connection()->enableQueryLog(); 
● Question 7. How To Set Database Connection In Laravel? 
● Answer : 
● Database configuration file path is : config/database.php 
● Following are sample of database file : 
● 'mysql' => [ 
● 'read' => [ 
● 'host' => 'localhost', 
● ], 
● 'write' => [ 
● 'host' => 'localhost' 
● ], 
● 'driver' => 'mysql', 
● 'database' => 'database', 
● 'username' => 'root', 
● 'password' => '', 
● 'charset' => 'utf8', 
● 'collation' => 'utf8_unicode_ci', 
● 'prefix' => '', 
● ], 
● Question 8. What Are Bundles,reverse Routing And The Ioc Container ? 
● Answer : 
○ Bundles:​ These are small functionality which you may download to 
add to your web application. 
○ Reverse Routing:​ This allows you to change your routes and 
application will update all of the relevant links as per this link. 
○ IoC container:​ It gives you Control gives you a method for 
generating new objects and optionally instantiating and referencing 
singletons. 
● Question 9. Compare Laravel With Codeigniter? 
● Answer : 
● Laravel : 
○ Laravel is a framework with expressive, elegant syntax 
○ Development is enjoyable, creative experience 
○ Laravel is built for latest version of PHP 
○ It is more object oriented compared to CodeIgniter 
○ Laravel community is still small, but it is growing very fast. 
● Codeigniter : 
○ CodeIgniter is a powerful PHP framework 
○ Simple and elegant toolkit to create full-featured web applications. 
○ Codeigniter is an older more mature framework 
○ It is less object oriented compared to Laravel. 
○ Codeigniter community is large. 
●   
● Question 10. What Are The Feature Of Laravel 5.0? 
● Answer : 
○ Method injection 
○ Contracts 
○ Route caching 
○ Events object 
○ Multiple file system 
○ Authentication Scaffolding 
○ dotenv – Environment Detection 
○ Laravel Scheduler 

● Question 11. Explain About Laravel Project? 


● Answer : 
○ Laravel is one of the most popular PHP frameworks used for 
Web Development. 
○ This framework is with expressive, elegant syntax.  
○ It is based on model–view–controller (MVC) architectural 
pattern.  
● Question 12. What Are Advantages Of Laravel? 
● Answer : 
○ Easy and consistent syntax 
○ Set-up process is easy 
○ customization process is easy 
○ code is always regimented with Laravel 
● Question 13. What Is Laravel? 
● Answer : 
○ Laravel is a open-source PHP framework developed by Taylor 
Otwell used for Developing the websites.  
○ Laravel helps you create applications using simple, expressive 
syntax.  
● Question 14. What Is System Requirement For Installation Of Laravel 5.2 
(latest Version)? 
● Answer : 
○ PHP >= 5.5.9 
○ OpenSSL PHP Extension 
○ PDO PHP Extension 
○ Mbstring PHP Extension 
○ Tokenizer PHP Extension 
● Question 15. How To Install Laravel? 
● Answer : 
● We can install the Laravel in following ways.  
○ Laravel Installer 
○ Composer Create-Project 
● Question 16. Is Laravel An Open Source? 
● Answer : 
● Yes, Download the framework and use as per your requirement  
● Question 17. What Is Offical Website Url Of Laravel? 
● Answer : 
● laravel.com.  
● Question 18. In Which Language It Was Written? 
● Answer : 
● PHP.  
● Question 19. What Is Current Stable Version Of Laravel? 
● Answer : 
● Version 5.2.36 dated June 6, 2016 
● Question 20. When Laravel Was Launched? 
● Answer : 
● June 2011 
● Question 21. What Developed The Laravel? 
● Answer : 
● Taylor Otwell. 
● Question 22. What Are System Requirement For Laravel 5.0? 
● Answer : 
● Following are system requirements: 
○ PHP >= 5.4, PHP < 7 
○ Mcrypt PHP Extension 
○ OpenSSL PHP Extension 
○ Mbstring PHP Extension 
○ Tokenizer PHP Extension 

PHP QUESTIONS
● Question 11. Explain About Laravel Project? 
● Answer : 
○ Laravel is one of the most popular PHP frameworks used for 
Web Development. 
○ This framework is with expressive, elegant syntax.  
○ It is based on model–view–controller (MVC) architectural 
pattern.  
● Question 12. What Are Advantages Of Laravel? 
● Answer : 
○ Easy and consistent syntax 
○ Set-up process is easy 
○ customization process is easy 
○ code is always regimented with Laravel 
● Question 13. What Is Laravel? 
● Answer : 
○ Laravel is a open-source PHP framework developed by Taylor 
Otwell used for Developing the websites.  
○ Laravel helps you create applications using simple, expressive 
syntax.  
● Question 14. What Is System Requirement For Installation Of Laravel 5.2 
(latest Version)? 
● Answer : 
○ PHP >= 5.5.9 
○ OpenSSL PHP Extension 
○ PDO PHP Extension 
○ Mbstring PHP Extension 
○ Tokenizer PHP Extension 
● Question 15. How To Install Laravel? 
● Answer : 
● We can install the Laravel in following ways.  
○ Laravel Installer 
○ Composer Create-Project 
● Question 16. Is Laravel An Open Source? 
● Answer : 
● Yes, Download the framework and use as per your requirement  
● Question 17. What Is Offical Website Url Of Laravel? 
● Answer : 
● laravel.com.  
● Question 18. In Which Language It Was Written? 
● Answer : 
● PHP.  
● Question 19. What Is Current Stable Version Of Laravel? 
● Answer : 
● Version 5.2.36 dated June 6, 2016 
● Question 20. When Laravel Was Launched? 
● Answer : 
● June 2011 
● Question 21. What Developed The Laravel? 
● Answer : 
● Taylor Otwell. 
● Question 22. What Are System Requirement For Laravel 5.0? 
● Answer : 
● Following are system requirements: 
○ PHP >= 5.4, PHP < 7 
○ Mcrypt PHP Extension 
○ OpenSSL PHP Extension 
○ Mbstring PHP Extension 
○ Tokenizer PHP Extension 
● Question 6. What Is The Difference Between $message And $$message? 
● Answer : 
● $message​ ​is a simple variable whereas​ $$message​ ​is a variable's 

variable,which means 
● value of the variable. Example: 
● $user = 'bob' 

● is equivalent to 

● $message = 'user'; 

● $$message = 'bob'; 
● Question 7. What Is A Persistent Cookie? 
● Answer : 
● A persistent cookie is a cookie which is stored in a cookie file permanently 
on the browser's computer. By default, cookies are created as temporary 
cookies which stored only in the browser's memory. When the browser is 
closed, temporary cookies will be erased. You should decide when to use 
temporary cookies and when to use persistent cookies based on their 
differences: 
● · Temporary cookies can not be used for tracking long-term information. 
● · Persistent cookies can be used for tracking long-term information. 
● · Temporary cookies are safer because no programs other than the browser 
can access them. 
● · Persistent cookies are less secure because users can open cookie files see 
the cookie values. 
● Question 8. How Do You Define A Constant? 
● Answer : 
● Via define() directive, like define ("MYCONSTANT", 100); 
● Question 9. What Are The Differences Between Require And Include, 
Include_once? 
● Answer : 
● require_once() and include_once() are both the functions to include and 
evaluate the specified file only once. If the specified file is included previous 
to the present call occurrence, it will not be done again. 
● But require() and include() will do it as many times they are asked to do. 
● Question 10. What Is Meant By Urlencode And Urldecode? 
● Answer : 
● urlencode() returns the URL encoded version of the given string. URL coding 
converts special characters into % signs followed by two hex digits. For 
example: urlencode("10.00%") will return "10%2E00%25". URL encoded 
strings are safe to be used as part of URLs. 
● urldecode() returns the URL decoded version of the given string. 

● Question 11. How To Get The Uploaded File Information In The Receiving 
Script? 
● Answer : 
● Once the Web server received the uploaded file, it will call the PHP script 
specified in the form action attribute to process them. This receiving PHP 
script can get the uploaded file information through the predefined array 
called $_FILES. Uploaded file information is organized in $_FILES as a 
two-dimensional array as: 
○ $_FILES[$fieldName]['name'] - The Original file name on the 
browser system. 
○ $_FILES[$fieldName]['type'] - The file type determined by the 
browser. 
○ $_FILES[$fieldName]['size'] - The Number of bytes of the file 
content. 
○ $_FILES[$fieldName]['tmp_name'] - The temporary filename of 
the file in which 
○ the uploaded file was stored on the server. 
○ $_FILES[$fieldName]['error'] - The error code associated with 
this file upload. 
○ The $fieldName is the name used in the . 
● Question 12. What Is The Difference Between Mysql_fetch_object And 
Mysql_fetch_array? 
● Answer : 
● MySQL fetch object will collect first single matching record where 
mysql_fetch_array will collect all matching records from the table in an 
array. 
● Question 13. How Can I Execute A Php Script Using Command Line? 
● Answer : 
● Just run the PHP CLI (Command Line Interface) program and provide the 
PHP script file name as the command line argument. For example, "php 
myScript.php", assuming "php" is the command to invoke the CLI program. 
● Be aware that if your PHP script was written for the Web CGI interface, it 
may not execute properly in command line environment. 
● Question 14. I Am Trying To Assign A Variable The Value Of 0123, But It 
Keeps Coming Up With A Different Number, What's The Problem? 
● Answer : 
● PHP Interpreter treats numbers beginning with 0 as octal. Look at the 
similar PHP interview questions for more numeric problems. 
● Question 15. Would I Use Print "$a Dollars" Or "{$a} Dollars" To Print Out 
The Amount Of Dollars In This Example? 
● Answer : 
● In this example it wouldn’t matter, since the variable is all by itself, but if 
you were to print something like "{$a},000,000 mln dollars", then you 
definitely need to use the braces. 
● Question 16. What Are The Different Tables Present In Mysql? Which 
Type Of Table Is Generated When We Are Creating A Table In The 
Following Syntax: Create Table Employee(eno Int(2),ename Varchar(10))? 
● Answer : 
● Total 5 types of tables we can create 
● 1. MyISAM 
● 2. Heap 
● 3. Merge 
● 4. INNO DB 
● 5. ISAM 
● MyISAM is the default storage engine as of MySQL 3.23. When you fire the 
above 
● create query MySQL will create a MyISAM table. 
● Question 17. How To Create A Table? 
● Answer : 
● If you want to create a table, you can run the CREATE TABLE statement as 
shown in the following sample script: 
● <?php
include "mysql_connection.php";
$sql = "CREATE TABLE fyi_links ("
. " id INTEGER NOT NULL"
. ", url VARCHAR(80) NOT NULL"
. ", notes VARCHAR(1024)"
. ", counts INTEGER"
. ", time TIMESTAMP DEFAULT sysdate()"
. ")";
if (mysql_query($sql, $con)) {
print("Table fyi_links created.n");
} else {
print("Table creation failed.n");
}
mysql_close($con);
?>

● Remember that mysql_query() returns TRUE/FALSE on CREATE 


statements. If you run this script, you will get something like this: 
● Table fyi_links created. 
● Question 18. How Can We Encrypt The Username And Password Using 
Php? 
● Answer : 
● You can encrypt a password with the following Mysql>SET 
● PASSWORD=PASSWORD("Password"); 
● Question 19. How Do You Pass A Variable By Value? 
● Answer : 
● Just like in C++, put an ampersand in front of it, like $a = &$b. 
● Question 20. What Is The Functionality Of The Functions Strstr() And 
Stristr()? 
● Answer : 
● string strstr ( string haystack, string needle ) returns part of haystack string 
from the first occurrence of needle to the end of haystack. This function is 
case-sensitive. 
● stristr() is idential to strstr() except that it is case insensitive. 
● Question 21. When Are You Supposed To Use Endif To End The 
Conditional Statement? 
● Answer : 
● When the original if was followed by : and then the code block without 
braces. 
● Question 22. How Can We Send Mail Using Javascript? 
● Answer : 
● No. There is no way to send emails directly using JavaScript. 
● But you can use JavaScript to execute a client side email program send the 
email using the "mailto" code. Here is an example: 
● function myfunction(form) 
● { 
● tdata=document.myform.tbox1.value; 
● location="mailto:mailid@domain.com?subject=..."; 
● return true; 
● } 
● Question 23. What Is The Functionality Of The Function Strstr And Stristr? 
● Answer : 
● strstr() returns part of a given string from the first occurrence of a given 
substring to the end of the string. For example: 
strstr("user@example.com","@") will return "@example.com". 
● stristr() is idential to strstr() except that it is case insensitive. 
● Question 24. What Is The Difference Between Ereg_replace() And 
Eregi_replace()? 
● Answer : 
● eregi_replace() function is identical to ereg_replace() except that it ignores 
case distinction when matching alphabetic characters. 
● Question 25. How Do I Find Out The Number Of Parameters Passed Into 
Function9? 
● Answer : 
● func_num_args() function returns the number of parameters passed in. 
● Question 26. What Is The Purpose Of The Following Files Having 
Extensions: Frm, Myd, And Myi? What These Files Contain? 
● Answer : 
● In MySQL, the default table type is MyISAM. 
● Each MyISAM table is stored on disk in three files. The files have names 
that begin with 
● the table name and have an extension to indicate the file type. 
● The '.frm' file stores the table definition. 
● The data file has a '.MYD' (MYData) extension. 
● The index file has a '.MYI' (MYIndex) extension. 
● Question 27. If The Variable $a Is Equal To 5 And Variable $b Is Equal To 
Character A, What's The Value Of $$b? 
● Answer : 
● 5, it’s a reference to existing variable. 
● Question 28. How To Protect Special Characters In Query String? 
● Answer : 
● If you want to include special characters like spaces in the query string, 
you need to protect them by applying the urlencode() translation function. 
The script below shows how to use urlencode(): 
● <?php 
● print("<html>"); 
● print("<p>Please click the links below" 
● ." to submit comments about FYICenter.com:</p>"); 
● $comment = 'I want to say: "It\'s a good site! :->"'; 
● $comment = urlencode($comment); 
● print("<p>" 
● ."<a href=\"processing_forms.php?name=Guest&comment=$comment\">" 
● ."It's an excellent site!</a></p>"); 
● $comment = 'This visitor said: "It\'s an average site! :-("'; 
● $comment = urlencode($comment); 
● print("<p>" 
● .'<a href="processing_forms.php?'.$comment.'">' 
● ."It's an average site.</a></p>"); 
● print("</html>"); 
● ?> 
● Question 29. Are Objects Passed By Value Or By Reference? 
● Answer : 
● Everything is passed by value. 
● Question 30. What Are The Differences Between Drop A Table And 
Truncate A Table? 
● Answer : 
● DROP TABLE table_name​ - This will delete the table and its data. 
● TRUNCATE TABLE table_name​ - This will delete the data of the table, but 
not the table definition. 
● Question 31. What Are The Differences Between Get And Post Methods In 
Form Submitting, Give The Case Where We Can Use Get And We Can Use 
Post Methods? 
● Answer : 
● When you want to send short or small data, not containing ASCII 
characters, then you can use GET” Method. But for long data sending, say 
more then 100 character you can use POST method. 
● Once most important difference is when you are sending the form with 
GET method. You can see the output which you are sending in the address 
bar. Whereas if you send the form with POST” method then user can not 
see that information. 
● Question 32. How Do You Call A Constructor For A Parent Class? 
● Answer : 
● parent::constructor($value). 
● Question 33. What Are The Different Types Of Errors In Php? 
● Answer : 
● Here are three basic types of runtime errors in PHP: 
○ Notices:​ These are trivial, non-critical errors that PHP encounters 
while executing a script - for example, accessing a variable that 
has not yet been defined. By default, such errors are not 
displayed to the user at all - although you can change this default 
behavior. 
○ Warnings:​ These are more serious errors - for example, 
attempting to include() a file which does not exist. By default, 
these errors are displayed to the user, but they do not result in 
script termination. 
○ Fatal errors:​ These are critical errors - for example, instantiating 
an object of a nonexistent class, or calling a non-existent 
function. These errors cause the immediate termination of the 
script, and PHP's default behavior is to display them to the user 
when they take place. 
● Internally, these variations are represented by twelve different error types. 
● Question 34. What's The Special Meaning Of __sleep And __wakeup? 
● Answer : 
● __sleep returns the array of all the variables than need to be saved, while 
__wakeup retrieves them. 
● Question 35. How Can We Submit A Form Without A Submit Button? 
● Answer : 
● If you don't want to use the Submit button to submit a form, you can use 
normal hyper links to submit a form. But you need to use some JavaScript 
code in the URL of the link. For example: 
● <a href="javascript: document.myform.submit();">Submit Me</a>. 
● Question 36. Would You Initialize Your Strings With Single Quotes Or 
Double Quotes? 
● Answer : 
● Since the data inside the single-quoted string is not parsed for variable 
substitution, it’s always a better idea speed-wise to initialize a string with 
single quotes, unless you specifically need variable substitution. 
● Question 37. What Is The Difference Between The Functions Unlink And 
Unset? 
● Answer : 
● unlink() is a function for file system handling. It will simply delete the file in 
context. 
● unset() is a function for variable management. It will make a variable 
undefined. 
● Question 38. How Come The Code Works, But Doesn't For 
Two-dimensional Array Of Mine? 
● Answer : 
● Any time you have an array with more than one dimension, complex 
parsing syntax is required. print "Contents: {$arr[1][2]}" would’ve worked. 
● Question 39. How Can We Register The Variables Into A Session? 
● Answer : 
● session_register($session_var); 
● $_SESSION['var'] = 'value'; 
● Question 40. What Is The Difference Between Characters \023 And \x23? 
● Answer : 
● The first one is octal 23, the second is hex 23. 
● Question 41. How Can We Submit Form Without A Submit Button? 
● Answer : 
● We can use a simple JavaScript code linked to an event trigger of any form 
field. In the JavaScript code, we can call the document.form.submit() 
function to submit the form. For example: <input type=button value="Save" 
onClick="document.form.submit()">. 
● Question 42. How Can We Create A Database Using Php And Mysql? 
● Answer : 
● We can create MySQL database with the use of 
mysql_create_db($databaseName) to create a database. 
● Question 43. How Many Ways We Can Retrieve The Date In Result Set Of 
Mysql Using Php? 
● Answer : 
● As individual objects so single record or as a set or arrays. 
● Question 44. How Many Ways Can We Get The Value Of Current Session 
Id? 
● Answer : 
● session_id() returns the session id for the current session. 
● Question 45. Can We Use Include ("abc.php") Two Times In A Php Page 
"makeit.php"? 
● Answer : 
● Yes. 
● Question 46. What's The Difference Between Include And Require? 
● Answer : 
● It’s how they handle failures. If the file is not found by require(), it will cause 
a fatal error and halt the execution of the script. If the file is not found by 
include(), a warning will be issued, but execution will continue. 
● Question 47. Explain The Ternary Conditional Operator In Php? 
● Answer : 
● Expression preceding the ? is evaluated, if it’s true, then the expression 
preceding the : is executed, otherwise, the expression following : is 
executed. 
● Question 48. What's The Difference Between Htmlentities() And 
Htmlspecialchars()? 
● Answer : 
● htmlspecialchars only takes care of <, >, single quote ‘, double quote " and 
ampersand. 
● htmlentities translates all occurrences of character sequences that have 
different meaning in HTML. 
● Question 49. How To Store The Uploaded File To The Final Location? 
● Answer : 
● move_uploaded_file ( string filename, string destination) 
● This function checks to ensure that the file designated by filename is a 
valid upload file (meaning that it was uploaded via PHP's HTTP POST 
upload mechanism). If the file is valid, it will be moved to the filename 
given by destination. 
● If filename is not a valid upload file, then no action will occur, and 
move_uploaded_file() will return FALSE. 
● If filename is a valid upload file, but cannot be moved for some reason, no 
action will occur, and move_uploaded_file() will return FALSE. Additionally, 
a warning will be issued. 
● Question 50. What Is The Difference Between Reply-to And Return-path In 
The Headers Of A Mail Function? 
● Answer : 
● Reply-to :​ Reply-to is where to delivery the reply of the mail. 
● Return-path :​ Return path is when there is a mail delivery failure occurs 
then where to delivery the failure notification. 
● Question 51. So If Md5() Generates The Most Secure Hash, Why Would 
You Ever Use The Less Secure Crc32() And Sha1()? 
● Answer : 
● Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, 
depending on the data that you’re encrypting, you might have reasons to 
store a 32-bit value in the database instead of the 160-bit value to save on 
space. Second, the more secure the crypto is, the longer is the 
computation time to deliver the hash value. A high volume site might be 
significantly slowed down, if frequent md5() generation is required. 
● Question 52. How Can We Destroy The Session, How Can We Unset The 
Variable Of A Session? 
● Answer : 
● session_unregister()​ - Unregister a global variable from the current 
session. 
● session_unset()​ - Free all session variables. 
● Question 53. What Type Of Headers Have To Be Added In The Mail 
Function To Attach A File? 
● Answer : 
● $boundary = '--' . md5( uniqid ( rand() ) ); 
● $headers = "From: \"Me\"\n"; 
● $headers .= "MIME-Version: 1.0\n"; 
● $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\""; 
● Question 54. List Out Different Arguments In Php Header Function? 
● Answer : 
● void header ( string string [, bool replace [, int http_response_code]]). 
● Question 55. What Are The Different Functions In Sorting An Array? 
● Answer : 
● Sorting functions in PHP: 
● asort() 
● arsort() 
● ksort() 
● krsort() 
● uksort() 
● sort() 
● natsort() 
● rsort() 
● Question 56. How Can We Know The Count / Number Of Elements Of An 
Array? 
● Answer : 
● 2 ways: 
● sizeof($array)​ - This function is an alias of count(). 
● count($urarray)​ - This function returns the number of elements in an array. 
Interestingly if you just pass a simple var instead of an array, count() will 
return 1. 
● Question 57. How Many Ways I Can Redirect A Php Page? 
● Answer : 
● Here are the possible ways of php page redirection. 
● 1. ​Using Java script: 
● '; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } 

● redirect 
● 2. ​Using php function​: header 
●   
● Question 58. How Many Ways We Can Pass The Variable Through The 
Navigation Between The Pages? 
● Answer : 
● At least 3 ways: 
● 1. Put the variable into session in the first page, and get it back from 
session in the next page. 
● 2. Put the variable into cookie in the first page, and get it back from the 
cookie in the next page. 
● 3. Put the variable into a hidden form field, and get it back from the form in 
the next page. 
● Question 59. What Is The Maximum Length Of A Table Name, A Database 
Name, Or A Field Name In Mysql? 
● Answer : 
● Database name: 64 characters 
● Table name: 64 characters 
● Column name: 64 characters 
● Question 60. How Many Values Can The Set Function Of Mysql Take? 
● Answer : 
● MySQL SET function can take zero or more values, but at the maximum it 
can take 64 values. 
● Question 61. What Are The Other Commands To Know The Structure Of A 
Table Using Mysql Commands Except Explain Command? 
● Answer : 
● DESCRIBE table_name; 
● Question 62. How Can We Find The Number Of Rows In A Table Using 
Mysql? 
● Answer : 
● Use this for MySQL 
● SELECT COUNT(*) FROM table_name; 
● Question 63. What Changes I Have To Do In Php.ini File For File 
Uploading? 
● Answer : 
● Make the following line uncomment like: 
● ; Whether to allow HTTP file uploads. 
● file_uploads = On 
● ; Temporary directory for HTTP uploaded files (will use system default if 
not 
● ; specified). 
● upload_tmp_dir = C:\apache2triad\temp 
● ; Maximum allowed size for uploaded files. 
● upload_max_filesize = 2M 
● Question 64. What's The Difference Between Md5(), Crc32() And Sha1() 
Crypto On Php? 
● Answer : 
● The major difference is the length of the hash generated. CRC32 is, 
evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 
160 bit value. This is important when avoiding collisions. 
● Question 65. How Can We Find The Number Of Rows In A Result Set 
Using Php? 
● Answer : 
● Here is how can you find the number of rows in a result set in PHP: 
● $result = mysql_query($any_valid_sql, $database_link); 
● $num_rows = mysql_num_rows($result); 
● echo "$num_rows rows found"; 
● Question 66. What Is The Default Session Time In Php And How Can I 
Change It? 
● Answer : 
● The default session time in php is until closing of browser. 
● Question 67. How Many Ways We Can We Find The Current Date Using 
Mysql? 
● Answer : 
● SELECT CURDATE(); 
● SELECT CURRENT_DATE(); 
● SELECT CURTIME(); 
● SELECT CURRENT_TIME(); 
● Question 68. How Many Ways We Can Give The Output To A Browser? 
● Answer : 
● HTML output 
● PHP, ASP, JSP, Servlet Function 
● Script Language output Function 
● Different Type of embedded Package to output to a browser. 
● Question 69. Please Give A Regular Expression (preferably Perl/preg 
Style), Which Can Be Used To Identify The Url From Within A Html Link 
Tag? 
● Answer : 
● Try this: /href="([^"]*)"/i. 
● Question 70. Give The Syntax Of Grant Commands? 
● Answer : 
● The generic syntax for GRANT is as following 
● GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY 
[password] 
● Now rights can be: 
● a) ALL privilages 
● b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE 
etc. 
● We can grant rights on all databse by usingh *.* or some specific database 
by database.* or a specific table by database.table_name. 
● Question 71. What Are The Different Ways To Login To A Remote Server? 
Explain The Means, Advantages And Disadvantages? 
● Answer : 
● There is at least 3 ways to logon to a remote server: 
● Use ssh or telnet if you concern with security 
● You can also use rlogin to logon to a remote server. 
● Question 72. Give The Syntax Of Revoke Commands? 
● Answer : 
● The generic syntax for revoke is as following 
● REVOKE [rights] on [database] FROM [username@hostname] 
● Now rights can be: 
● a) ALL privilages 
● b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE 
etc. 
● We can grant rights on all databse by usingh *.* or some specific database 
by database.* or a specific table by database.table_name. 
● Question 73. When Viewing An Html Page In A Browser, The Browser 
Often Keeps This Page In Its Cache. What Can Be Possible 
Advantages/disadvantages Of Page Caching? How Can You Prevent 
Caching Of A Certain Page (please Give Several Alternate Solutions)? 
● Answer : 
● When you use the metatag in the header section at the beginning of an 
HTML Web page, the Web page may still be cached in the Temporary 
Internet Files folder. 
● A page that Internet Explorer is browsing is not cached until half of the 64 
KB buffer is filled. Usually, metatags are inserted in the header section of 
an HTML document, which appears at the beginning of the document. 
When the HTML code is parsed, it is read from top to bottom. When the 
metatag is read, Internet Explorer looks for the existence of the page in 
cache at that exact moment. If it is there, it is removed. To properly prevent 
the Web page from appearing in the cache, place another header section at 
the end of the HTML document. 
● Question 74. When You Want To Show Some Part Of A Text Displayed On 
An Html Page In Red Font Color? What Different Possibilities Are There 
To Do This? What Are The Advantages/disadvantages Of These Methods? 
● Answer : 
● There are 2 ways to show some part of a text in red: 
● 1. Using HTML tag <font color="red"> 
● 2. Using HTML tag </font> 
● Question 75. What Is The Difference Between Char And Varchar Data 
Types? 
● Answer : 
● CHAR is a fixed length data type. CHAR(n) will take n characters of storage 
even if you enter less than n characters to that column. For example, 
"Hello!" will be stored as "Hello! " in CHAR(10) column. 
● VARCHAR is a variable length data type. VARCHAR(n) will take only the 
required storage for the actual number of characters entered to that 
column. For example, "Hello!" will be stored as "Hello!" in VARCHAR(10) 
column. 
● Question 76. How Can We Encrypt And Decrypt A Data Present In A Mysql 
Table Using Mysql? 
● Answer : 
● AES_ENCRYPT() and AES_DECRYPT(). 
● Question 77. How Can We Change The Name Of A Column Of A Table? 
● Answer : 
● MySQL query to rename table: RENAME TABLE tbl_name TO 
new_tbl_name 
● or, 
● ALTER TABLE tableName CHANGE OldName newName. 
● Question 78. How Can Increase The Performance Of Mysql Select Query? 
● Answer : 
● We can use LIMIT to stop MySql for further search in table after we have 
received our required no. of records, also we can use LEFT JOIN or RIGHT 
JOIN instead of full join in cases we have related data in two or more 
tables. 
● Question 79. Will Comparison Of String "10" And Integer 11 Work In Php? 
● Answer : 
● Yes, internally PHP will cast everything to the integer type, so numbers 10 
and 11 will be compared. 
● Question 80. What Type Of Inheritance That Php Supports? 
● Answer : 
● In PHP an extended class is always dependent on a single base class, that 
is, multiple inheritance is not supported. Classes are extended using the 
keyword 'extends'. 
● Question 81. What Is The Functionality Of Md5 Function In Php? 
● Answer : 
● string md5(string) 
● It calculates the MD5 hash of a string. The hash is a 32-character 
hexadecimal number. 
● Question 82. How Can I Load Data From A Text File Into A Table? 
● Answer : 
● The MySQL provides a LOAD DATA INFILE command. You can load data 
from a file. 
● Great tool but you need to make sure that: 
● a) Data must be delimited. 
● b) Data fields must match table columns correctly. 
● Question 83. How Can We Know The Number Of Days Between Two Given 
Dates Using Mysql? 
● Answer : 
● Use DATEDIFF() 
● SELECT DATEDIFF(NOW(),'2006-07-01'); 
● Question 84. How Can We Change The Data Type Of A Column Of A 
Table? 
● Answer : 
● This will change the data type of a column: 
● ALTER TABLE table_name CHANGE colm_name same_colm_name [new 
data type]. 
● Question 85. How Can We Know That A Session Is Started Or Not? 
● Answer : 
● A session starts by session_start() function. 
● This session_start() is always declared in header portion. it always 
declares first. then we write session_ register(). 
● Question 86. What Are The Advantages And Disadvantages Of Cascade 
Style Sheets? 
● Answer : 
● External Style Sheets 
● Advantages 
● Can control styles for multiple documents at once Classes can be created 
for use on multiple HTML element types in many documents Selector and 
grouping methods can be used to apply styles under complex contexts 
● Disadvantages 
● An extra download is required to import style information for each 
document The rendering of the document may be delayed until the external 
style sheet is loaded Becomes slightly unwieldy for small quantities of 
style definitions 
● Embedded Style Sheets 
● Advantages 
● Classes can be created for use on multiple tag types in the document 
Selector and grouping methods can be used to apply styles under complex 
contexts No additional downloads necessary to receive style information 
● Disadvantage 
● This method can not control styles for multiple documents at once 
● Inline Styles 
● Advantages 
● Useful for small quantities of style definitions Can override other style 
specification methods at the local level so only exceptions need to be 
listed in conjunction with other style methods 
● Disadvantages 
● Does not distance style information from content (a main goal of 
SGML/HTML) Can not control styles for multiple documents at once 
Author can not create or control classes of elements to control multiple 
element types within the document Selector grouping methods can not be 
used to create complex element addressing scenarios 
● Question 87. If We Login More Than One Browser Windows At The Same 
Time With Same User And After That We Close One Window, Then Is The 
Session Is Exist To Other Windows Or Not? And If Yes Then Why? If No 
Then Why? 
● Answer : 
● Session depends on browser. If browser is closed then session is lost. The 
session data will be deleted after session time out. If connection is lost 
and you recreate connection, then session will continue in the browser. 
● Question 88. What's The Difference Between Accessing A Class Method 
Via -> And Via ::? 
● Answer : 
● :: is allowed to access methods that can perform static operations, i.e. 
those, which do not require object initialization. 
● Question 89. What Are The Mysql Database Files Stored In System ? 
● Answer : 
● Data is stored in name.myd 
● Table structure is stored in name.frm 
● Index is stored in name.myi 
● Question 90. Explain Normalization Concept? 
● Answer : 
● The normalization process involves getting our data to conform to three 
progressive normal forms, and a higher level of normalization cannot be 
achieved until the previous levels have been achieved (there are actually 
five normal forms, but the last two are mainly academic and will not be 
discussed). 
● First Normal Form 
● The First Normal Form (or 1NF) involves removal of redundant data from 
horizontal rows. We want to ensure that there is no duplication of data in a 
given row, and that every column stores the least amount of information 
possible (making the field atomic). 
● Second Normal Form 
● Where the First Normal Form deals with redundancy of data across a 
horizontal row, Second Normal Form (or 2NF) deals with redundancy of 
data in vertical columns. As stated earlier, the normal forms are 
progressive, so to achieve Second Normal Form, your tables must already 
be in First Normal Form. 
● Third Normal Form 
● I have a confession to make; I do not often use Third Normal Form. In Third 
Normal Form we are looking for data in our tables that is not fully 
dependant on the primary key, but dependant on another value in the table 
● Question 91. What Is The Difference Between Php4 And Php5? 
● Answer : 
● PHP4 cannot support oops concepts and Zend engine 1 is used. 
● PHP5 supports oops concepts and Zend engine 2 is used. 
● Error supporting is increased in PHP5. 
● XML and SQLLite will is increased in PHP5. 
● Question 92. What Are The Advantages Of Stored Procedures, Triggers, 
Indexes? 
● Answer : 
● A stored procedure is a set of SQL commands that can be compiled and 
stored in the server. Once this has been done, clients don't need to keep 
re-issuing the entire query but can refer to the stored procedure. This 
provides better overall performance because the query has to be parsed 
only once, and less information needs to be sent between the server and 
the client. You can also raise the conceptual level by having libraries of 
functions in the server. However, stored procedures of course do increase 
the load on the database server system, as more of the work is done on the 
server side and less on the client (application) side. Triggers will also be 
implemented. A trigger is effectively a type of stored procedure, one that is 
invoked when a particular event occurs. For example, you can install a 
stored procedure that is triggered each time a record is deleted from a 
transaction table and that stored procedure automatically deletes the 
corresponding customer from a customer table when all his transactions 
are deleted. 
● Indexes are used to find rows with specific column values quickly. Without 
an index, MySQL must begin with the first row and then read through the 
entire table to find the relevant rows. The larger the table, the more this 
costs. If the table has an index for the columns in question, MySQL can 
quickly determine the position to seek to in the middle of the data file 
without having to look at all the data. If a table has 1,000 rows, this is at 
least 100 times faster than reading sequentially. If you need to access 
most of the rows, it is faster to read sequentially, because this minimizes 
disk seeks. 
● Question 93. What Are The Difference Between Abstract Class And 
Interface? 
● Answer : 
● Abstract class​: abstract classes are the class where one or more methods 
are abstract but not necessarily all method has to be abstract. Abstract 
methods are the methods, which are declare in its class but not define. The 
definition of those methods must be in its extending class. 
● Interface​: Interfaces are one type of class where all the methods are 
abstract. That means all the methods only declared but not defined. All the 
methods must be define by its implemented class 
● Question 94. Can We Use Include(abc.php) Two Times In A Php Page 
Makeit.php? 
● Answer : 
● Yes we can include that many times we want, but here are some things to 
make sure of: (including abc.PHP, the file names are case-sensitive) there 
shouldn't be any duplicate function names, means there should not be 
functions or classes or variables with the same name in abc.PHP and 
makeit.php. 
● Question 95. How Can I Make A Script That Can Be Bilingual (supports 
English, German)? 
● Answer : 
● You can change char set variable in above line in the script to support bi 
language. 
● Question 96. What Is The Maximum Size Of A File That Can Be Uploaded 
Using Php And How Can We Change This? 
● Answer : 
● You can change maximum size of a file set upload_max_filesize variable in 
php.ini file. 
● Question 97. How Can We Get Second Of The Current Time Using Date 
Function? 
● Answer : 
● $second = date("s"); 
● Question 98. What Are The Differences Between Mysql_fetch_array(), 
Mysql_fetch_object(), Mysql_fetch_row()? 
● Answer : 
● mysql_fetch_array - F​ etch a result row as an associative array and a 
numeric array. 
● mysql_fetch_object -​ Returns an object with properties that correspond to 
the fetched row and moves the internal data pointer ahead. Returns an 
object with properties that correspond to the fetched row, or FALSE if there 
are no more rows. 
● mysql_fetch_row() - ​Fetches one row of data from the result associated 
with the specified result identifier. The row is returned as an array. Each 
result column is stored in an array offset, starting at offset 0. 
● Question 99. What Are The Features And Advantages Of Object Oriented 
Programming? 
● Answer : 
● One of the main advantages of OO programming is its ease of 
modification; objects can easily be modified and added to a system there 
by reducing maintenance costs. OO programming is also considered to be 
better at modeling the real world than is procedural programming. It allows 
for more complicated and flexible interactions. OO systems are also easier 
for non-technical personnel to understand and easier for them to 
participate in the maintenance and enhancement of a system because it 
appeals to natural human cognition patterns. For some systems, an OO 
approach can speed development time since many objects are standard 
across systems and can be reused. Components that manage dates, 
shipping, shopping carts, etc. can be purchased and easily modified for a 
specific system. 
● Question 100. What Are The Reasons For Selecting Lamp (linux, Apache, 
Mysql, Php) Instead Of Combination Of Other Software Programs, Servers 
And Operating Systems? 
● Answer : 
● All of those are open source resource. Security of Linux is very more than 
windows. Apache is a better server that IIS both in functionality and 
security. Mysql is world most popular open source database. Php is more 
faster that asp or any other scripting language. 
● Question 101. What Is Meant By Nl2br()? 
● Answer : 
● nl2br() inserts a HTML tag  
● before all new line characters n in a string. 
● echo nl2br("god bless n you"); 
● output: 
● god bless 
● you 
● Question 102. What Are The Current Versions Of Apache, Php, And 
Mysql? 
● Answer : 
● PHP:​ PHP 5.1.2 
● MySQL:​ MySQL 5.1 
● Apache: ​Apache 2.1 
● Question 103. How Can We Encrypt And Decrypt A Data Presented In A 
Table Using Mysql? 
● Answer : 
● You can use functions: AES_ENCRYPT() and AES_DECRYPT() like: 
● AES_ENCRYPT(str, key_str) 
● AES_DECRYPT(crypt_str, key_str) 
● Question 104. How Can We Destroy The Cookie? 
● Answer : 
● Set the cookie with a past expiration time. 
● Question 105. How Can I Retrieve Values From One Database Server And 
Store Them In Other Database Server Using Php? 
● Answer : 
● For this purpose, you can first read the data from one server into session 
variables. Then connect to other server and simply insert the data into the 
database. 
● Question 106. How Can We Submit From Without A Submit Button? 
● Answer : 
● Trigger the JavaScript code on any event ( like onSelect of drop down list 
box, onfocus, etc ) document. myform.submit(); This will submit the form. 
● Question 107. Who Is The Father Of Php And What Is The Current Version 
Of Php And Mysql? 
● Answer : 
● Rasmus Lerdorf. 
● PHP 5.1. Beta 
● MySQL 5.0 
● Question 108. Tools Used For Drawing Er Diagrams? 
● Answer : 
● Case Studio. 
● Smart Draw. 
● Question 109. In How Many Ways We Can Retrieve Data In The Result Set 
Of Mysql Using Php? 
● Answer : 
● mysql_fetch_array -​ Fetch a result row as an associative array, a numeric 
array, or both 
● mysql_fetch_assoc - F ​ etch a result row as an associative array 
● mysql_fetch_object -​ Fetch a result row as an object 
● mysql_fetch_row - G ​ et a result row as an enumerated array 
● Question 110. What Are The Functions For Imap? 
● Answer : 
● imap_body - R ​ ead the message body 
● imap_check -​ Check current mailbox 
● imap_delete - M ​ ark a message for deletion from current mailbox 
● imap_mail - S ​ end an email message 
● Question 111. Check If A Variable Is An Integer In Javascript ? 
● Answer : 
● var myValue =9.8; 
● if(parseInt(myValue)== myValue) 
● alert('Integer'); 
● else 
● alert('Not an integer'); 
● Question 112. What Are Encryption Functions In Php? 
● Answer : 
● CRYPT() 
● MD5() 
● Question 113. What Types Of Images That Php Supports ? 
● Answer : 
● Using imagetypes() function to find out what types of images are 
supported in your PHP engine. 
● imagetypes() - Returns the image types supported. 
● This function returns a bit-field corresponding to the image formats 
supported by the version of GD linked into PHP. The following bits are 
returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. 
● Question 114. What Is The Difference Between Htmlentities() And 
Htmlspecialchars()? 
● Answer : 
● htmlspecialchars()​ - Convert some special characters to HTML entities 
(Only the most widely used) 
● htmlentities()​ - Convert ALL special characters to HTML entities. 
● Question 115. How To Reset/destroy A Cookie ? 
● Answer : 
● Reset a cookie by specifying expire time in the past: 
● Example: setcookie('Test',$i,time()-3600); // already expired time 
● Reset a cookie by specifying its name only 
● Example: setcookie('Test'); 
● Question 116. What Is The Functionality Of The Function Htmlentities? 
● Answer : 
● htmlentities() - Convert all applicable characters to HTML entities 
● This function is identical to htmlspecialchars() in all ways, except with 
htmlentities(), all characters which have HTML character entity equivalents 
are translated into these entities. 
● Question 117. How Can We Get The Properties (size, Type, Width, Height) 
Of An Image Using Php Image Functions? 
● Answer : 
● To know the image size use getimagesize() function 
● To know the image width use imagesx() function 
● To know the image height use imagesy() function 
● Question 118. How To Set Cookies? 
● Answer : 
● setcookie('variable','value','time')
;
variable - name of the cookie variable
value - value of the cookie variable
time - expiry time

● Example: 
● setcookie('Test',$i,time()+3600); 
● Test - cookie variable name 
● $i - value of the variable 'Test' 
● time()+3600 - denotes that the cookie will expire after an one hour. 
● Question 119. How Can We Increase The Execution Time Of A Php Script? 
● Answer : 
● By the use of void set_time_limit(int seconds) Set the number of seconds a 
script is allowed to run. If this is reached, the script returns a fatal error. 
The default limit is 30 seconds or, if it exists, the max_execution_time 
value defined in the php.ini. If seconds is set to zero, no time limit is 
imposed. 
● When called, set_time_limit() restarts the timeout counter from zero. In 
other words, if the timeout is the default 30 seconds, and 25 seconds into 
script execution a call such as set_time_limit(20) is made, the script will 
run for a total of 45 seconds before timing out. 
● Question 120. In How Many Ways We Can Retrieve Data In The Result Set 
Of Mysql Using Php? 
● Answer : 
● mysql_fetch_array​ - Fetch a result row as an associative array, a numeric 
array, or both. 
● mysql_fetch_assoc​ - Fetch a result row as an associative array. 
● mysql_fetch_object​ - Fetch a result row as an object. 
● mysql_fetch_row​ —- Get a result row as an enumerated array. 
● Question 121. Who Is The Father Of Php And What Is The Current Version 
Of Php And Mysql? 
● Answer : 
● Rasmus Lerdorf. 
● PHP 5.1. Beta 
● MySQL 5.0 
● Question 122. What's The Difference Between Include And Require? 
● Answer : 
● It’s how they handle failures. If the file is not found by require(), it will cause 
a fatal error and halt the execution of the script. If the file is not found by 
include(), a warning will be issued, but execution will continue. 
● Question 123. Steps For The Payment Gateway Processing? 
● Answer : 
● An online payment gateway is the interface between your merchant 
account and your Web site. The online payment gateway allows you to 
immediately verify credit card transactions and authorize funds on a 
customer’s credit card directly from your Web site. It then passes the 
transaction off to your merchant bank for processing, commonly referred 
to as transaction batching. 
● Question 124. Can We Use Include(abc.php) Two Times In A Php Page 
Makeit.php? 
● Answer : 
● Yes we can include that many times we want, but here are some things to 
make sure of: (including abc.PHP, the file names are case-sensitive). 
● there shouldn't be any duplicate function names, means there should not 
be functions or classes or variables with the same name in abc.PHP and 
makeit.php. 
● Question 125. How Many Ways We Can Give The Output To A Browser? 
● Answer : 
● HTML output 
● PHP, ASP, JSP, Servlet Function 
● Script Language output Function 
● Different Type of embedded Package to output to a browser. 
● Question 126. What Are The Different Ways To Login To A Remote 
Server? Explain The Means, Advantages And Disadvantages? 
● Answer : 
● There is at least 3 ways to logon to a remote server: 
● Use ssh or telnet if you concern with security 
● You can also use rlogin to logon to a remote server. 
● Question 127. What Is Meant By Mime? 
● Answer : 
● MIME is Multipurpose Internet Mail Extensions is an Internet standard for 
the format of e-mail. However browsers also uses MIME standard to 
transmit files. MIME has a header which is added to a beginning of the 
data. When browser sees such header it shows the data as it would be a 
file (for example image) Some examples of MIME types: 
● audio/x-ms-wmp 
● image/png 
● application/x-shockwave-flash 
● Question 128. What Is The Difference Between Group By And Order By In 
Sql? 
● Answer : 
● To sort a result, use an ORDER BY clause. 
● The most general way to satisfy a GROUP BY clause is to scan the whole 
table and create a new temporary table where all rows from each group are 
consecutive, and then use this temporary table to discover groups and 
apply aggregate functions (if any). ORDER BY [col1],[col2],...[coln]; Tells 
DBMS according to what columns it should sort the result. If two rows will 
have the same value in col1 it will try to sort them according to col2 and so 
on. 
● GROUP BY [col1],[col2],...[coln]; Tells DBMS to group (aggregate) results 
with same value of column col1. You can use COUNT(col1), SUM(col1), 
AVG(col1) with it, if you want to count all items in group, sum all values or 
view average. 
● Question 129. Who Is The Father Of Php And Explain The Changes In Php 
Versions? 
● Answer : 
● Rasmus Lerdorf is known as the father of PHP.PHP/F1 2.0 is an early and 
no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 
and is a lot nicer. PHP 4 is the current generation of PHP, which uses the 
Zend engine under the hood. PHP 5 uses Zend engine 2 which, among 
other things, offers many additionalOOP features . 
● Question 130. Which Method Do You Follow To Get A Record From A 
Million Records? (searching Not From Database, From An Array In Php)? 
● Answer : 
● use array_searchfl, array_keys, arrayyalues, array_key_exists, and in_array. 
● Question 131. Are Namespaces Are There In Javascript? 
● Answer : 
● A namespace is a container and allows you to bundle up all your 
functionality using a unique name. In JavaScript, a namespace is really just 
an object that you’ve attached all further methods, properties and objects. 
But it is not always necessary to use namespace. 
● Question 132. What Is 'float' Property In Css? 
● Answer : 
● The float property sets where an image or a text will appear in another 
element. 
● Question 133. What Are The Advantages/disadvantages Of Mysql And 
Php? 
● Answer : 
● Both of them are open source software (so free of cost), support cross 
platform. php is faster then ASP and iSP. 
● Question 134. What Are The File Upload Settings In Configuration File? 
● Answer : 
● There are several settings in the PHP configuration file related to file 
uploading: 
● • file_uploads = On/Off - Whether or not to allow HTTP file uploads. 
● • upload_tmp_dir = directory - The temporary directory used for storing files 
when doing file upload. 
● • upload_max_filesize = size - The maximum size of an uploaded file. 
● Question 135. How To Uploaded Files To A Table? 
● Answer : 
● To store uploaded files to MySQL database, you can use the normal 
SELECT statement as shown in the modified 
processing_uploaded_files.php listed below: 
● <?php 
● $con = mysql_connect("localhost", "", ""); 
● mysql_select_db("pickzy"); 
● $error = $_FILES['pickzycenter_logo']['error']; 
● $tmp_name = $_FILES['pickzycenter_logo']['tmp_name']; 
● $size = $_FILES['pickzycenter_logo']['size']; 
● $name = $_FILES['pickzycenter_logo']['name']; 
● $type = $_FILES['pickzycenter_logo']['type']; 
● print(" 
● \n"); 
● if ($error == UPLOAD_ERR_OK && $size > 0) { 
● $fp = fopen($tmp_name, 'r'); 
● $content = fread($fp, $size); 
● fclose($fp); 
● $content = addslashes($content); 
● $sql = "INSERT INTO pickzy_files (name, type, size, content)" 
● . " VALUES ('$name', '$type', $size, '$content')"; 
● mysql_query($sql, $con); 
● print("File stored.\n"); 
● } else { 
● print("Upload faield.\n"); 
● } 
● print(" 
● \n"); 
● mysql_close($con); 
● ?> 
● Note that addslashes() is used to add backslashes to special characters 
that need to be protected in SQL statements. 
● Question 136. How To Create A Table To Store Files? 
● Answer : 
● If you using MySQL database and want to store files in database, you need 
to create BLOB columns, which can holds up to 65,535 characters. Here is 
a sample script that creates a table with a BLOB column to be used to 
store uploaded files: 
● <?php 
● $con = mysql_connect("localhost", "", ""); 
● mysql_select_db("pickzy"); 
● $sql = "CREATE TABLE pickzy_files (" 
● . " id INTEGER NOT NULL AUTO_INCREMENT" 
● . ", name VARCHAR(80) NOT NULL" 
● . ", type VARCHAR(80) NOT NULL" 
● . ", size INTEGER NOT NULL" 
● . ", content BLOB" 
● . ", PRIMARY KEY (id)" 
● . ")"; 
● mysql_query($sql, $con); 
● mysql_close($con); 
● ?> 
● Question 137. Why Do You Need To Filter Out Empty Files? 
● Answer : 
● When you are processing uploaded files, you need to check for empty files, 
because they could be resulted from a bad upload process but the PHP 
engine could still give no error. 
● For example, if a user typed a bad file name in the upload field and 
submitted the form, the PHP engine will take it as an empty file without 
raising any error. The script below shows you an improved logic to process 
uploaded files: 
● <?php 
● $file = '\pickzycenter\images\pickzycenter.logo'; 
● $error = $_FILES['pickzycenter_logo']['error']; 
● $tmp_name = $_FILES['pickzycenter_logo']['tmp_name']; 
● print(" 
● \n"); 
● if ($error==UPLOAD_ERR_OK) { 
● if ($_FILES['pickzycenter_logo']['size'] > 0) { 
● move_uploaded_file($tmp_name, $file); 
● print("File uploaded.\n"); 
● } else { 
● print("Loaded file is empty.\n"); 
● } 
● } else if ($error==UPLOAD_ERR_NO_FILE) { 
● print("No files specified.\n"); 
● } else { 
● print("Upload faield.\n"); 
● } 
● print(" 
● \n"); 
● ?> 
● Question 138. How To Move Uploaded Files To Permanent Directory? 
● Answer : 
● PHP stores uploaded files in a temporary directory with temporary file 
names. You must move uploaded files to a permanent directory, if you 
want to keep them permanently. 
● PHP offers the move_uploaded_file() to help you moving uploaded files. 
The example script, processing_ uploaded_files.php, below shows a good 
example: 
● <?php 
● $file = '\pickzycenter\images\pickzycenter.logo'; 
● print("<pre>\n"); 
● move_uploaded_file($_FILES['pickzycenter_logo']['tmp_name'], $file); 
● print("File uploaded: ".$file."\n"); 
● print("</pre>\n"); 
● ?> 
● Note that you need to change the permanent directory, 
"\pickzycenter\images\", used in this script to something else on your Web 
server. If your Web server is provided by a Web hosting company, you may 
need to ask them which directories you can use to store files. 
● If you copy both scripts, logo_upload.php and 
processing_uploaded_files.php, to your Web server, you can try them to 
upload an image file to your Web server. 
● Question 139. How To Process The Uploaded Files? 
● Answer : 
● How to process the uploaded files? The answer is really depending on your 
application. For example: 
○ You can attached the outgoing emails, if the uploaded files are 
email attachments. 
○ You can move them to user's Web page directory, if the 
uploaded files are user's Web pages. 
○ You can move them to a permanent directory and save the 
files names in the database, if the uploaded files are articles to 
be published on the Web site. 
○ You can store them to database tables, if you don't want store 
them as files. 
● Question 140. How Many Escape Sequences Are Recognized In 
Single-quoted Strings? 
● Answer : 
● There are 2 escape sequences you can use in single-quoted strings: 
● • \\ - Represents the back slash character. 
● • \' - Represents the single quote character. 

● Question 141. What Are The Special Characters You Need To Escape In 
Double-quoted Stings? 
● Answer : 
● There are two special characters you need to escape in a double-quote 
string: the double quote (") and the back slash (\). Here is a PHP script 
example of double-quoted strings: 
● <?php 
● echo "Hello world!"; 
● echo "Tom said: \"Who's there?\""; 
● echo "\\ represents an operator."; 
● ?> 
● This script will print: 
● Hello world!Tom said: "Who's there?"\ represents an operator. 
● Question 142. How Many Escape Sequences Are Recognized In 
Double-quoted Strings? 
● Answer : 
● There are 12 escape sequences you can use in double-quoted strings: 
● • \\ - Represents the back slash character. 
● • \" - Represents the double quote character. 
● • \$ - Represents the dollar sign. 
● • \n - Represents the new line character (ASCII code 10). 
● • \r - Represents the carriage return character (ASCII code 13). 
● • \t - Represents the tab character (ASCII code 9). 
● • \{ - Represents the open brace character. 
● • \} - Represents the close brace character. 
● • \[ - Represents the open bracket character. 
● • \] - Represents the close bracket character. 
● • \nnn - Represents a character as an octal value. 
● • \xnn - Represents a character as a hex value. 
● Question 143. How To Include Variables In Double-quoted Strings? 
● Answer : 
● Variables included in double-quoted strings will be interpolated. Their 
values will be concatenated into the enclosing strings. For example, two 
statements in the following PHP script will print out the same string: 
● <?php 
● $variable = "and"; 
● echo "part 1 $variable part 2\n"; 
● echo "part 1 ".$variable." part 2\n"; 
● ?> 
● This script will print: 
● part 1 and part 2 
● part 1 and part 2 
● Question 144. How To Access A Specific Character In A String? 
● Answer : 
● Any character in a string can be accessed by a special string element 
expression: 
● • $string{index} - The index is the position of the character counted from 
left and starting from 0. 
● Here is a PHP script example: 
● <?php 
● $string = 'It\'s Friday!'; 
● echo "The first character is $string{0}\n"; 
● echo "The first character is {$string{0}}\n"; 
● ?> 
● This script will print: 
● The first character is It's Friday!{0} 
● The first character is I 
● Question 145. How To Assigning A New Character In A String? 
● Answer : 
● The string element expression, $string{index}, can also be used at the left 
side of an assignment statement. This allows you to assign a new 
character to any position in a string. Here is a PHP script example: 
● <?php 
● $string = 'It\'s Friday?'; 
● echo "$string\n"; 
● $string{11} = '!'; 
● echo "$string\n"; 
● ?> 
● This script will print: 
● It's Friday? 
● It's Friday! 
● Question 146. How To Get The Number Of Characters In A String? 
● Answer : 
● You can use the "strlen()" function to get the number of characters in a 
string. Here is a PHP script example of strlen(): 
● <?php 
● print(strlen('It\'s Friday!')); 
● ?> 
● This script will print: 
● 12 
● Question 147. How To Remove The New Line Character From The End Of 
A Text Line? 
● Answer : 
● If you are using fgets() to read a line from a text file, you may want to use 
the chop() function to remove the new line character from the end of the 
line as shown in this PHP script: 
● <?php 
● $handle = fopen("/tmp/inputfile.txt", "r"); 
● while ($line=fgets()) { 
● $line = chop($line); 
● # process $line here... 
● } 
● fclose($handle); 
● ?> 
● Question 148. How To Remove Leading And Trailing Spaces From User 
Input Values? 
● Answer : 
● If you are taking input values from users with a Web form, users may enter 
extra spaces at the beginning and/or the end of the input values. You 
should always use the trim() function to remove those extra spaces as 
shown in this PHP script: 
● <?php 
● $name = $_REQUEST("name"); 
● $name = trim($name); 
● # $name is ready to be used... 
● ?> 
● Question 149. How To Take A Substring From A Given String? 
● Answer : 
● If you know the position of a substring in a given string, you can take the 
substring out by the substr() function. Here is a PHP script on how to use 
substr(): 
● <?php 
● $string = "beginning"; 
● print("Position counted from left: ".substr($string,0,5)."\n"); 
● print("Position counted form right: ".substr($string,-7,3)."\n"); 
● ?> 
● This script will print: 
● Position counted from left: begin 
● Position counted form right: gin 
● substr() can take negative starting position counted from the end of the 
string. 
● Question 150. How To Replace A Substring In A Given String? 
● Answer : 
● If you know the position of a substring in a given string, you can replace 
that substring by another string by using the substr_replace() function. 
Here is a PHP script on how to use substr_replace(): 
● <?php 
● $string = "Warning: System will shutdown in NN minutes!"; 
● $pos = strpos($string, "NN"); 
● print(substr_replace($string, "15", $pos, 2)."\n"); 
● sleep(10*60); 
● print(substr_replace($string, "5", $pos, 2)."\n"); 
● ?> 
● This script will print: 
● Warning: System will shutdown in 15 minutes! 
● (10 minutes later) 
● Warning: System will shutdown in 5 minutes! 
● Like substr(), substr_replace() can take negative starting position counted 
from the end of the string. 
● Question 151. How To Convert Strings To Upper Or Lower Cases? 
● Answer : 
● Converting strings to upper or lower cases are easy. Just use strtoupper() 
or strtolower() functions. Here is a PHP script on how to use them: 
● <?php 
● $string = "PHP string functions are easy to use."; 
● $lower = strtolower($string); 
● $upper = strtoupper($string); 
● print("$lower\n"); 
● print("$upper\n"); 
● print("\n"); 
● ?> 
● This script will print: 
● php string functions are easy to use. 
● PHP STRING FUNCTIONS ARE EASY TO USE. 
● Question 152. How To Convert The First Character To Upper Case? 
● Answer : 
● If you are processing an article, you may want to capitalize the first 
character of a sentence by using the ucfirst() function. You may also want 
to capitalize the first character of every words for the article title by using 
the ucwords() function. Here is a PHP script on how to use ucfirst() and 
ucwords(): 
● <?php 
● $string = "php string functions are easy to use."; 
● $sentence = ucfirst($string); 
● $title = ucwords($string); 
● print("$sentence\n"); 
● print("$title\n"); 
● print("\n"); 
● ?> 
● This script will print: 
● Php string functions are easy to use. 
● Php String Functions Are Easy To Use. 
● Question 153. How To Convert Strings In Hex Format? 
● Answer : 
● If you want convert a string into hex format, you can use the bin2hex() 
function. Here is a PHP script on how to use bin2hex(): 
● <?php 
● $string = "Hello\tworld!\n"; 
● print($string."\n"); 
● print(bin2hex($string)."\n"); 
● ?> 
● This script will print: 
● Hello world! 
● 48656c6c6f09776f726c64210a 
● Question 154. How To Generate A Character From An Ascii Value? 
● Answer : 
● If you want to generate characters from ASCII values, you can use the chr() 
function. 
● chr() takes the ASCII value in decimal format and returns the character 
represented by the ASCII value. chr() complements ord(). Here is a PHP 
script on how to use chr(): 
● <?php 
● print(chr(72).chr(101).chr(108).chr(108).chr(111)."\n"); 
● print(ord("H")."\n"); 
● ?> 
● This script will print: 
● Hello 
● 72 
● Question 155. How To Convert A Character To An Ascii Value? 
● Answer : 
● If you want to convert characters to ASCII values, you can use the ord() 
function, which takes the first charcter of the specified string, and returns 
its ASCII value in decimal format. ord() complements chr(). Here is a PHP 
script on how to use ord(): 
● <?php 
● print(ord("Hello")."\n"); 
● print(chr(72)."\n"); 
● ?> 
● This script will print: 
● 72 
● H 
● Question 156. How To Join Multiple Strings Into A Single String? 
● Answer : 
● If you multiple strings stored in an array, you can join them together into a 
single string with a given delimiter by using the implode() function. Here is 
a PHP script on how to use implode(): 
● <?php 
● $date = array('01', '01', '2006'); 
● $keys = array('php', 'string', 'function'); 
● print("A formated date: ".implode("/",$date)."\n"); 
● print("A keyword list: ".implode(", ",$keys)."\n"); 
● ?> 
● This script will print: 
● A formated date: 01/01/2006 
● A keyword list: php, string, function 
● Question 157. What Is An Array In Php? 
● Answer : 
● An array in PHP is really an ordered map of pairs of keys and values. 
● Comparing with Perl, an array in PHP is not like a normal array in Perl. An 
array in PHP is like an associate array in Perl. But an array in PHP can work 
like a normal array in Perl. 
● Comparing with Java, an array in PHP is not like an array in Java. An array 
in PHP is like a TreeMap class in Java. But an array in PHP can work like 
an array in Java. 
● Question 158. How To Test If A Variable Is An Array? 
● Answer : 
● Testing if a variable is an array is easy. Just use the is_array() function. 
Here is a PHP script on how to use is_array(): 
● <?php 
● $var = array(0,0,7); 
● print("Test 1: ". is_array($var)."\n"); 
● $var = array(); 
● print("Test 2: ". is_array($var)."\n"); 
● $var = 1800; 
● print("Test 3: ". is_array($var)."\n"); 
● $var = true; 
● print("Test 4: ". is_array($var)."\n"); 
● $var = null; 
● print("Test 5: ". is_array($var)."\n"); 
● $var = "PHP"; 
● print("Test 6: ". is_array($var)."\n"); 
● print("\n"); 
● ?> 
● This script will print: 
● Test 1: 1 
● Test 2: 1 
● Test 3: 
● Test 4: 
● Test 5: 
● Test 6: 
● Question 159. How To Retrieve Values Out Of An Array? 
● Answer : 
● You can retrieve values out of arrays using the array element expression 
$array[$key]. 
● Here is a PHP example script: 
● <?php $languages = array(); $languages["Zero"] = "PHP"; $languages["One"] 
= "Perl"; 
● $languages["Two"] = "Java"; print("Array with inserted values:\n"); 
● print_r($languages); ?> 
● This script will print: 
● Array with default keys: 
● The second value: Perl 
● Array with specified keys: 
● The third value: Java 
● Question 160. How Values In Arrays Are Indexed? 
● Answer : 
● Values in an array are all indexed their corresponding keys. Because we 
can use either an integer or a string as a key in an array, we can divide 
arrays into 3 categories: 
○ Numerical Array - All keys are sequential integers. 
○ Associative Array - All keys are strings. 
○ Mixed Array - Some keys are integers, some keys are strings. 
● Question 161. How The Values Are Ordered In An Array? 
● Answer : 
● PHP says that an array is an ordered map. But how the values are ordered 
in an array? 
● The answer is simple. Values are stored in the same order as they are 
inserted like a queue. If you want to reorder them differently, you need to 
use a sort function. Here is a PHP script show you the order of array 
values: 
● <?php 
● $mixed = array(); 
● $mixed["Two"] = "Java"; 
● $mixed["3"] = "C+"; 
● $mixed["Zero"] = "PHP"; 
● $mixed[1] = "Perl"; 
● $mixed[""] = "Basic"; 
● $mixed[] = "Pascal"; 
● $mixed[] = "FORTRAN"; 
● $mixed["Two"] = ""; 
● unset($mixed[4]); 
● print("Order of array values:\n"); 
● print_r($mixed); 
● ?> 
● This script will print: 
● Order of array values: 
● Array 
● ( 
● [Two] => 
● [3] => C+ 
● [Zero] => PHP 
● [1] => Perl 
● [] => Basic 
● [5] => FORTRAN 
● ) 
● Question 162. How To Get The Total Number Of Values In An Array? 
● Answer : 
● You can get the total number of values in an array by using the count() 
function. Here is a PHP example script: 
● <?php 
● $array = array("PHP", "Perl", "Java"); 
● print_r("Size 1: ".count($array)."\n"); 
● $array = array(); 
● print_r("Size 2: ".count($array)."\n"); 
● ?> 
● This script will print: 
● Size 1: 3 
● Size 2: 0 
● Note that count() has an alias called sizeof(). 
● Question 163. How To Find A Specific Value In An Array? 
● Answer : 
● There are two functions can be used to test if a value is defined in an array 
or not: 
○ array_search($value, $array) - Returns the first key of the 
matching value in the array, if found. Otherwise, it returns 
false. 
○ in_array($value, $array) - Returns true if the $value is defined in 
$array. 
● Here is a PHP script on how to use arrary_search(): 
● <?php
$array = array("Perl", "PHP", "Java", "PHP");
print("Search 1: ".array_search("PHP",$array)."n");
print("Search 2: ".array_search("Perl",$array)."n");
print("Search 3: ".array_search("C#",$array)."n");
print("n");
?>

● This script will print: 


● Search 1: 1 
● Search 2: 0 
● Search 3: 
● Question 164. How To Merge Values Of Two Arrays Into A Single Array? 
● Answer : 
● You can use the array_merge() function to merge two arrays into a single 
array. 
● array_merge() appends all pairs of keys and values of the second array to 
the end of the first array. Here is a PHP script on how to use array_merge(): 
● <?php 
● $lang = array("Perl", "PHP", "Java",); 
● $os = array("i"=>"Windows", "ii"=>"Unix", "iii"=>"Mac"); 
● $mixed = array_merge($lang, $os); 
● print("Merged:\n"); 
● print_r($mixed); 
● ?> 
● This script will print: 
● Merged: 
● Array 
● ( 
● [0] => Perl 
● [1] => PHP 
● [2] => Java 
● [i] => Windows 
● [ii] => Unix 
● [iii] => Mac 
● ) 
● Question 165. How To Randomly Retrieve A Value From An Array? 
● Answer : 
● If you have a list of favorite greeting messages, and want to randomly 
select one of them to be used in an email, you can use the array_rand() 
function. Here is a PHP example script: 
● <?php 
● $array = array("Hello!", "Hi!", "Allo!", "Hallo!", "Coucou!"); 
● $key = array_rand($array); 
● print("Random greeting: ".$array[$key]."\n"); 
● ?> 
● This script will print: 
● Random greeting: Coucou! 
● Question 166. How To Pad An Array With The Same Value Multiple 
Times? 
● Answer : 
● If you want to add the same value multiple times to the end or beginning of 
an array, you can use the array_pad($array, $new_size, $value) function. If 
the second argument, $new_size, is positive, it will pad to the end of the 
array. If negative, it will pad to the beginning of the array. If the absolute 
value of $new_size if not greater than the current size of the array, no 
padding takes place. Here is a PHP script on how to use array_pad(): 
● <?php 
● $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); 
● $array = array_pad($array, 6, ">>"); 
● $array = array_pad($array, -8, "---"); 
● print("Padded:\n"); 
● print(join(",", array_values($array))); 
● print("\n"); 
● ?> 
● This script will print: 
● Padded: 
● ---,---,PHP,Perl,Java,>>,>>,>> 
● Question 167. How To Join Multiple Strings Stored In An Array Into A 
Single String? 
● Answer : 
● If you multiple strings stored in an array, you can join them together into a 
single string with a given delimiter by using the implode() function. Here is 
a PHP script on how to use implode(): 
● <?php 
● $date = array('01', '01', '2006'); 
● $keys = array('php', 'string', 'function'); 
● print("A formated date: ".implode("/",$date)."\n"); 
● print("A keyword list: ".implode(", ",$keys)."\n"); 
● ?> 
● This script will print: 
● A formated date: 01/01/2006 
● A keyword list: php, string, function 
● Question 168. How To Define A User Function? 
● Answer : 
● You can define a user function anywhere in a PHP script using the function 
statement like this: "function name() {...}". Here is a PHP script example on 
how to define a user function: 
● <?php 
● function msg() { 
● print("Hello world!\n"); 
● } 
● msg(); 
● ?> 
● This script will print: 
● Hello world! 
● Question 169. How To Invoke A User Function? 
● Answer : 
● You can invoke a function by entering the function name followed by a pair 
of parentheses. If needed, function arguments can be specified as a list of 
expressions enclosed in parentheses. Here is a PHP script example on 
how to invoke a user function: 
● <?php 
● function hello($f) { 
● print("Hello $f!\n"); 
● } 
● hello("Bob"); 
● ?> 
● This script will print: 
● Hello Bob! 
● Question 170. How To Return A Value Back To The Function Caller? 
● Answer : 
● You can return a value to the function caller by using the "return $value" 
statement. Execution control will be transferred to the caller immediately 
after the return statement. If there are other statements in the function 
after the return statement, they will not be executed. Here is a PHP script 
example on how to return values: 
● <?php 
● function getYear() { 
● $year = date("Y"); 
● return $year; 
● } 
● print("This year is: ".getYear()."\n"); 
● ?> 
● This script will print: 
● This year is: 2006 
● Question 171. How To Pass An Argument To A Function? 
● Answer : 
● To pass an argument to a function, you need to: 
● •Add an argument definition in the function definition. 
● •Add a value as an argument when invoking the function. 
● Here is a PHP script on how to use arguments in a function(): 
● <?php 
● function f2c($f) { 
● return ($f - 32.0)/1.8; 
● } 
● print("Celsius: ".f2c(100.0)."\n"); 
● print("Celsius: ".f2c(-40.0)."\n"); 
● ?> 
● This script will print: 
● Celsius: 37.777777777778 
● Celsius: -40 
● Question 172. How Variables Are Passed Through Arguments? 
● Answer : 
● Like more of other programming languages, variables are passed through 
arguments by values, not by references. That means when a variable is 
passed as an argument, a copy of the value will be passed into the 
function. Modipickzyng that copy inside the function will not impact the 
original copy. Here is a PHP script on passing variables by values: 
● <?php 
● function swap($a, $b) { 
● $t = $a; 
● $a = $b; 
● $b = $t; 
● } 
● $x = "PHP"; 
● $y = "JSP"; 
● print("Before swapping: $x, $y\n"); 
● swap($x, $y); 
● print("After swapping: $x, $y\n"); 
● ?> 
● This script will print: 
● Before swapping: PHP, JSP 
● After swapping: PHP, JSP 
● As you can see, original variables were not affected. 
● Question 173. How To Pass Variables By References? 
● Answer : 
● You can pass a variable by reference to a function by taking the reference 
of the original variable, and passing that reference as the calling argument. 
Here is a PHP script on how to use pass variables by references: 
● <?php 
● function swap($a, $b) { 
● $t = $a; 
● $a = $b; 
● $b = $t; 
● } 
● $x = "PHP"; 
● $y = "JSP"; 
● print("Before swapping: $x, $y\n"); 
● swap(&$x, &$y); 
● print("After swapping: $x, $y\n"); 
● ?> 
● This script will print: 
● Before swapping: PHP, JSP 
● After swapping: JSP, PHP 
● As you can see, the function modified the original variable. 
● Note that call-time pass-by-reference has been deprecated. You need to 
define arguments as references. 
● Question 174. Can You Define An Argument As A Reference Type? 
● Answer : 
● You can define an argument as a reference type in the function definition. 
This will automatically convert the calling arguments into references. Here 
is a PHP script on how to define an argument as a reference type: 
● <?php 
● function ref_swap(&$a, &$b) { 
● $t = $a; 
● $a = $b; 
● $b = $t; 
● } 
● $x = "PHP"; 
● $y = "JSP"; 
● print("Before swapping: $x, $y\n"); 
● ref_swap($x, $y); 
● print("After swapping: $x, $y\n"); 
● ?> 
● This script will print: 
● Before swapping: PHP, JSP 
● After swapping: JSP, PHP 
● Question 175. Can You Pass An Array Into A Function? 
● Answer : 
● You can pass an array into a function in the same as a normal variable. No 
special syntax needed. Here is a PHP script on how to pass an array to a 
function: 
● <?php 
● function average($array) { 
● $sum = array_sum($array); 
● $count = count($array); 
● return $sum/$count; 
● } 
● $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); 
● print("Average: ".average($numbers)."\n"); 
● ?> 
● This script will print: 
● Average: 3.75 
● Question 176. How Arrays Are Passed Through Arguments? 
● Answer : 
● Like a normal variable, an array is passed through an argument by value, 
not by reference. That means when an array is passed as an argument, a 
copy of the array will be passed into the function. Modipickzyng that copy 
inside the function will not impact the original copy. Here is a PHP script 
on passing arrays by values: 
● <?php 
● function shrink($array) { 
● array_splice($array,1); 
● } 
● $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); 
● print("Before shrinking: ".join(",",$numbers)."\n"); 
● shrink($numbers); 
● print("After shrinking: ".join(",",$numbers)."\n"); 
● ?> 
● This script will print: 
● Before shrinking: 5,7,6,2,1,3,4,2 
● After shrinking: 5,7,6,2,1,3,4,2 
● As you can see, original variables were not affected. 
● Question 177. Can You Define An Array Argument As A Reference Type? 
● Answer : 
● You can define an array argument as a reference type in the function 
definition. This will automatically convert the calling arguments into 
references. Here is a PHP script on how to define an array argument as a 
reference type: 
● <?php 
● function ref_shrink(&$array) { 
● array_splice($array,1); 
● } 
● $numbers = array(5, 7, 6, 2, 1, 3, 4, 2); 
● print("Before shrinking: ".join(",",$numbers)."\n"); 
● ref_shrink($numbers); 
● print("After shrinking: ".join(",",$numbers)."\n"); 
● ?> 
● This script will print: 
● BBefore shrinking: 5,7,6,2,1,3,4,2 
● After shrinking: 5 
● Question 178. What Is The Scope Of A Variable Defined In A Function? 
● Answer : 
● The scope of a local variable defined in a function is limited with that 
function. Once the function is ended, its local variables are also removed. 
So you can not access any local variable outside its defining function. Here 
is a PHP script on the scope of local variables in a function: 
● <?php 
● ?> 
● function myPassword() { 
● $password = "U8FIE8W0"; 
● print("Defined inside the function? ". isset($password)."\n"); 
● } 
● myPassword(); 
● print("Defined outside the function? ". isset($password)."\n"); 
● ?> 
● This script will print: 
● Defined inside the function? 1 
● Defined outside the function? 
● Question 179. What Is The Scope Of A Variable Defined Outside A 
Function? 
● Answer : 
● A variable defined outside any functions in main script body is called 
global variable. However, a global variable is not really accessible globally 
any in the script. The scope of global variable is limited to all statements 
outside any functions. So you can not access any global variables inside a 
function. Here is a PHP script on the scope of global variables: 
● <?php 
● ?> 
● $login = "pickzycenter"; 
● function myLogin() { 
● print("Defined inside the function? ". isset($login)."\n"); 
● } 
● myLogin(); 
● print("Defined outside the function? ". isset($login)."\n"); 
● ?> 
● This script will print: 
● Defined inside the function? 
● Defined outside the function? 1 
● Question 180. How To Access A Global Variable Inside A Function? 
● Answer : 
● By default, global variables are not accessible inside a function. However, 
you can make them accessible by declare them as "global" inside a 
function. Here is a PHP script on declaring "global" variables: 
● <?php 
● ?> 
● $intRate = 5.5; 
● function myAccount() { 
● global $intRate; 
● print("Defined inside the function? ". isset($intRate)."\n"); 
● } 
● myAccount(); 
● print("Defined outside the function? ". isset($intRate)."\n"); 
● ?> 
● This script will print: 
● Defined inside the function? 1 
● Defined outside the function? 1 
● Question 181. How To Specify Argument Default Values? 
● Answer : 
● If you want to allow the caller to skip an argument when calling a function, 
you can define the argument with a default value when defining the 
function. Adding a default value to an argument can be done like this 
"function name($arg=expression){}. Here is a PHP script on how to specify 
default values to arguments: 
● <?php 
● function printKey($key="download") { 
● print("PHP $key\n"); 
● } 
● printKey(); 
● printKey("hosting"); 
● print("\n"); 
● ?> 
● This script will print: 
● PHP download 
● PHP hosting 
● Question 182. How To Define A Function With Any Number Of 
Arguments? 
● Answer : 
● If you want to define a function with any number of arguments, you need 
to: 
● •Declare the function with no argument. 
● •Call func_num_args() in the function to get the number of the arguments. 
● •Call func_get_args() in the function to get all the arguments in an array. 
● Here is a PHP script on how to handle any number of arguments: 
● <?php 
● function myAverage() { 
● $count = func_num_args(); 
● $args = func_get_args(); 
● $sum = array_sum($args); 
● return $sum/$count; 
● } 
● $average = myAverage(102, 121, 105); 
● print("Average 1: $average\n"); 
● $average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114); 
● print("Average 2: $average\n"); 
● ?> 
● This script will print: 
● Average 1: 109.33333333333 
● Average 2: 107.66666666667 
● Question 183. How To Read The Entire File Into A Single String? 
● Answer : 
● If you have a file, and you want to read the entire file into a single string, 
you can use the file_get_contents() function. It opens the specified file, 
reads all characters in the file, and returns them in a single string. Here is a 
PHP script example on how to file_get_contents(): 
● <?php 
● $file = file_get_contents("/windows/system32/drivers/etc/services"); 
● print("Size of the file: ".strlen($file)."\n"); 
● ?> 
● This script will print: 
● Size of the file: 7116 
● Question 184. How To Open A File For Reading? 
● Answer : 
● If you want to open a file and read its contents piece by piece, you can use 
the fopen($fileName, "r") function. It opens the specified file, and returns a 
file handle. The second argument "r" tells PHP to open the file for reading. 
Once the file is open, you can use other functions to read data from the file 
through this file handle. Here is a PHP script example on how to use 
fopen() for reading: 
● <?php 
● $file = fopen("/windows/system32/drivers/etc/hosts", "r"); 
● print("Type of file handle: " . gettype($file) . "\n"); 
● print("The first line from the file handle: " . fgets($file)); 
● fclose($file); 
● ?> 
● This script will print: 
● Type of file handle: resource 
● The first line from the file handle: # Copyright (c) 1993-1999 
● Note that you should always call fclose() to close the opened file when you 
are done with the file. 
● Question 185. How To Open A File For Writing? 
● Answer : 
● If you want to open a new file and write date to the file, you can use the 
fopen($fileName, "w") function. It creates the specified file, and returns a 
file handle. The second argument "w" tells PHP to open the file for writing. 
Once the file is open, you can use other functions to write data to the file 
through this file handle. Here is a PHP script example on how to use 
fopen() for writing: 
● <?php 
● $file = fopen("/temp/todo.txt", "w"); 
● fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n"); 
● fclose($file); 
● ?> 
● This script will write the following to the file: 
● Download PHP scripts at dev.pickzycenter.com. 
● Note that you should use "\r\n" to terminate lines on Windows. On a Unix 
system, you should use "\n". 
● Question 186. How To Read One Character From A File? 
● Answer : 
● If you have a text file, and you want to read the file one character at a time, 
you can use the fgetc() function. It reads the current character, moves the 
file pointer to the next character, and returns the character as a string. If 
end of the file is reached, fgetc() returns Boolean false. Here is a PHP 
script example on how to use fgetc(): 
● <?php 
● $file = fopen("/windows/system32/drivers/etc/services", "r"); 
● $count = 0; 
● while ( ($char=fgetc($file)) !== false ) { 
● if ($char=="/") $count++; 
● } 
● fclose($file); 
● print("Number of /: $count\n"); 
● ?> 
● This script will print: 
● Number of /: 113 
● Note that rtrim() is used to remove "\n" from the returning string of fgets(). 
● Question 187. How To Read A File In Binary Mode? 
● Answer : 
● If you have a file that stores binary data, like an executable program or 
picture file, you need to read the file in binary mode to ensure that none of 
the data gets modified during the reading process. You need to: 
● •Open the file with fopen($fileName, "rb"). 
● •Read data with fread($fileHandle,$length). 
● Here is a PHP script example on reading binary file: 
● <?php 
● $in = fopen("/windows/system32/ping.exe", "rb"); 
● $out = fopen("/temp/myPing.exe", "w"); 
● $count = 0; 
● while (!feof($in)) { 
● $count++; 
● $buffer = fread($in,64); 
● fwrite($out,$buffer); 
● } 
● fclose($out); 
● fclose($in); 
● print("About ".($count*64)." bytes read.\n"); 
● ?> 
● This script will print: 
● About 16448 bytes read. 
● This script actually copied an executable program file ping.exe in binary 
mode to new file. The new file should still be executable. 
● Question 188. How To Open Standard Output As A File Handle? 
● Answer : 
● If you want to open the standard output as a file handle yourself, you can 
use the fopen("php://stdout") function. It creates a special file handle 
linking to the standard output, and returns the file handle. Once the 
standard output is opened to a file handle, you can use fwrite() to write 
data to the starndard output like a regular file. Here is a PHP script 
example on how to write to standard output: 
● <?php 
● $stdout = fopen("php://stdout", "w"); 
● fwrite($stdout,"To do:\n"); 
● fwrite($stdout,"Looking for PHP hosting provider!\n"); 
● fclose($stdout); 
● ?> 
● This script will print: 
● What's your name? 
● To do: 
● Looking for PHP hosting provider! 
● If you don't want to open the standard output as a file handle yourself, you 
can use the constant STDOUT predefined by PHP as the file handle for 
standard output. 
● If you are using your script in a Web page, standard output is merged into 
the Web page HTML document. 
● print() and echo() also writes to standard output. 
● Question 189. How To Create A Directory? 
● Answer : 
● You can use the mkdir() function to create a directory. Here is a PHP script 
example on how to use mkdir(): 
● <?php 
● if (file_exists("/temp/download")) { 
● print("Directory already exists.\n"); 
● } else { 
● mkdir("/temp/download"); 
● print("Directory created.\n"); 
● } 
● ?> 
● This script will print: 
● Directory created. 
● If you run this script again, it will print: 
● Directory already exists. 
● Question 190. How To Remove An Empty Directory? 
● Answer : 
● If you have an empty existing directory and you want to remove it, you can 
use the rmdir(). Here is a PHP script example on how to use rmdir(): 
● <?php 
● if (file_exists("/temp/download")) { 
● rmdir("/temp/download"); 
● print("Directory removed.\n"); 
● } else { 
● print("Directory does not exist.\n"); 
● } 
● ?> 
● This script will print: 
● Directory removed. 
● If you run this script again, it will print: 
● Directory does not exist. 
● Question 191. How To Remove A File? 
● Answer : 
● If you want to remove an existing file, you can use the unlink() function. 
Here is a PHP script example on how to use unlink(): 
● <?php 
● if (file_exists("/temp/todo.txt")) { 
● unlink("/temp/todo.txt"); 
● print("File removed.\n"); 
● } else { 
● print("File does not exist.\n"); 
● } 
● ?> 
● This script will print: 
● File removed. 
● If you run this script again, it will print: 
● File does not exist. 
● Question 192. How To Copy A File? 
● Answer : 
● If you have a file and want to make a copy to create a new file, you can use 
the copy() function. Here is a PHP script example on how to use copy(): 
● <?php 
● unlink("/temp/myPing.exe"); 
● copy("/windows/system32/ping.exe", "/temp/myPing.exe"); 
● if (file_exists("/temp/myPing.exe")) { 
● print("A copy of ping.exe is created.\n"); 
● } 
● ?> 
● This script will print: 
● A copy of ping.exe is created. 
● Question 193. How To Get The Directory Name Out Of A File Path Name? 
● Answer : 
● If you have the full path name of a file, and want to get the directory name 
portion of the path name, you can use the dirname() function. It breaks the 
full path name at the last directory path delimiter (/) or (\), and returns the 
first portion as the directory name. Here is a PHP script example on how to 
use dirname(): 
● <?php 
● $pathName = "/temp/download/todo.txt"; 
● $dirName = dirname($pathName); 
● print("File full path name: $pathName\n"); 
● print("File directory name: $dirName\n"); 
● print("\n"); 
● ?> 
● This script will print: 
● File full path name: /temp/download/todo.txt 
● File directory name: /temp/download 
● Question 194. How To Break A File Path Name Into Parts? 
● Answer : 
● If you have a file name, and want to get different parts of the file name, you 
can use the pathinfo() function. It breaks the file name into 3 parts: 
directory name, file base name and file extension; and returns them in an 
array. Here is a PHP script example on how to use pathinfo(): 
● <?php 
● $pathName = "/temp/download/todo.txt"; 
● $parts = pathinfo($pathName); 
● print_r($parts); 
● print("\n"); 
● ?> 
● This script will print: 
● Array 
● ( 
● [dirname] => /temp/download 
● [basename] => todo.txt 
● [extension] => txt 
● ) 
● Question 195. How To Create A Web Form? 
● Answer : 
● If you take input data from visitors on your Web site, you can create a Web 
form with input fields to allow visitors to fill in data and submit the data to 
your server for processing. A Web form can be created with the <FORM> 
tag with some input tags. The &FORM tag should be written in the 
following format: 
● <form action=processing.php method=get/post> 
● ...... 
● </form> 
● Where "processing.php" specifies the PHP page that processes the 
submitted data in the form. 
● Question 196. What Are Form Input Html Tags? 
● Answer : 
● HTML tags that can be used in a form to collect input data are: 
● •<SUBMIT ...> - Displayed as a button allow users to submit the form. 
● •<INPUT TYPE=TEXT ...> - Displayed as an input field to take an input 
string. 
● •<INPUT TYPE=RADIO ...> - Displayed as a radio button to take an input 
flag. 
● •<INPUT TYPE=CHECKBOX ...> - Displayed as a checkbox button to take an 
input flag. 
● •<SELECT ...> - Displayed as a dropdown list to take input selection. 
● •<TEXTAREA ...> - Displayed as an input area to take a large amount of 
input text. 
● Question 197. How To Generate A Form? 
● Answer : 
● Generating a form seems to be easy. You can use PHP output statements 
to generate the required <FORM> tag and other input tags. But you should 
consider to organized your input fields in a table to make your form looks 
good on the screen. The PHP script below shows you a good example of 
HTML forms: 
● <?php 
● print("<html><form action=processing_forms.php method=post>"); 
● print("<table><tr><td colspan=2>Please enter and submit your" 
● ." comments about PICKZYCenter.com:</td></tr>"); 
● print("<tr><td>Your Name:</td>" 
● ."<td><input type=text name=name></td></tr>\n"); 
● print("<tr><td>Comments:</td>" 
● ."<td><input type=text name=comment></td></tr>\n"); 
● print("<tr><td colspan=2><input type=submit><td></tr></table>\n"); 
● print("</form></html>\n"); 
● ?> 
● If you save this script as a PHP page, submit_comments.php, on your Web 
site, and view this page, you will see a simple Web form. 
● Question 198. Where Is The Submitted Form Data Stored? 
● Answer : 
● When a user submit a form on your Web server, user entered data will be 
transferred to the PHP engine, which will make the submitted data 
available to your PHP script for processing in pre-defined arrays: 
● • $_GET - An associate array that store form data submitted with the GET 
method. 
● • $_POST - An associate array that store form data submitted with the 
POST method. 
● • $_REQUEST - An associate array that store form data submitted with 
either GET or POST method. $_REQUEST also contains the cookie values 
received back from the browser. 
● Question 199. What Happens If An Expected Input Field Was Not 
Submitted? 
● Answer : 
● Obviously, if an expected input field was not submitted, there will no entry 
in the $_REQUEST array for that field. You may get an execution error, if 
you are not checking the existence of the expected entries in $_REQUEST. 
For example, if you copy processing_forms.php to your local Web server, 
and run your browser with 
http://localhost/processing_forms.php?name=Joe, you will an error page 
like this: 
● You have submitted the following information: 
● Name = Joe 
● Comments = 
● Thank you! 
● PHP Notice: Undefined index: 
● comment in ...\processing_forms.php on line 3 
● Question 200. How To Avoid The Undefined Index Error? 
● Answer : 
● If you don't want your PHP page to give out errors as shown in the previous 
exercise, you should consider checking all expected input fields in 
$_REQUEST with the isset() function as shown in the example script below: 
● <?php 
● if (isset($_REQUEST['name'])) { 
● $name = $_REQUEST['name']; 
● } else { 
● $name = ""; 
● } 
● if (isset($_REQUEST['comment'])) { 
● $comment = $_REQUEST['comment']; 
● } else { 
● $comment = ""; 
● } 
● print("<html><pre>"); 
● print("You have submitted the following information:\n"); 
● print(" Name = $name\n"); 
● print(" Comments = $comment\n"); 
● print("Thank you!\n"); 
● print("</pre></html>\n"); 
● ?> 

● Question 200. How To Avoid The Undefined Index Error? 


● Answer : 
● If you don't want your PHP page to give out errors as shown in the previous 
exercise, you should consider checking all expected input fields in 
$_REQUEST with the isset() function as shown in the example script below: 
● <?php 
● if (isset($_REQUEST['name'])) { 
● $name = $_REQUEST['name']; 
● } else { 
● $name = ""; 
● } 
● if (isset($_REQUEST['comment'])) { 
● $comment = $_REQUEST['comment']; 
● } else { 
● $comment = ""; 
● } 
● print("<html><pre>"); 
● print("You have submitted the following information:\n"); 
● print(" Name = $name\n"); 
● print(" Comments = $comment\n"); 
● print("Thank you!\n"); 
● print("</pre></html>\n"); 
● ?> 
● Question 201. How To List All Values Of Submitted Fields? 
● Answer : 
● If you want list all values of submitted fields, you can write a simple loop to 
retrieve all entries in the $_REQUEST array. Below is an improved version of 
processing_forms.php to list all submited input values: 
● <?php 
● print("<html><pre>"); 
● $count = count($_REQUEST); 
● print("Number of values: $count\n"); 
● foreach ($_REQUEST as $key=>$value) { 
● print(" $key = $value\n"); 
● } 
● print("</pre></html>\n"); 
● ?> 
● Question 202. How To Retrieve The Original Query String? 
● Answer : 
● If you have coded some values in the URL without using the standard form 
GET format, you need to retrieve those values in the original query string in 
$_SERVER['QUERY_STRING']. The script below is an enhanced version of 
processing_forms.php which print the original query string: 
● <?php 
● print("<html><pre>"); 
● print(" query_string = {$_SERVER['QUERY_STRING']}\n"); 
● $count = count($_REQUEST); 
● print("Number of values: $count\n"); 
● foreach ($_REQUEST as $key=>$value) { 
● if (is_array($value)) { 
● print(" $key is an array\n"); 
● for ($i = 0; $i < count($value); $i++) { 
● $sub_value = $value[$i]; 
● if (get_magic_quotes_gpc()) { 
● $sub_value = stripslashes($sub_value); 
● } 
● print(" ".$key."[".$i."] = ".$sub_value."\n"); 
● } 
● } else { 
● if (get_magic_quotes_gpc()) { 
● $value = stripslashes($value); 
● } 
● print(" $key = $value\n"); 
● } 
● } 
● print("</pre></html>\n"); 
● ?> 
● Question 203. How To Support Multiple-page Forms? 
● Answer : 
● If you have a long form with a lots of fields, you may want to divide the 
fields into multiple groups and present multiple pages with one group of 
fields on one page. This makes the a long form more user-friendly. 
However, this requires you to write good scripts that: 
● • When processing the first page and other middle pages, you must keep 
those input values collected so far in the session or as hidden values in the 
next page form. 
● • When processing the last page, you should collect all input values from 
all pages for final process, like saving everything to the database. 
● Question 204. What Is A Cookie? 
● Answer : 
● A cookie is a small amount of information sent by a Web server to a web 
browser and then sent back unchanged by the browser each time it 
accesses that server. HTTP cookies are used for authenticating, tracking, 
and maintaining specific information about users, such as site preferences 
and the contents of their electronic shopping carts. The term "cookie" is 
derived from "magic cookie", a well-known concept in computing which 
inspired both the idea and the name of HTTP cookies. 
● A cookie consists of a cookie name and cookie value. 
● Question 205. How To Send A Cookie To The Browser? 
● Answer : 
● If you want to sent a cookie to the browser when it comes to request your 
PHP page, you can use the setcookie( ) function. Note that you should call 
setcookie() function before any output statements. The following script 
shows you how to set cookies: 
● <?php 
● setcookie("LoginName","XYZ"); 
● setcookie("PreferredColor","Blue"); 
● print("2 cookies were delivered.\n"); 
● ?> 
● Question 206. How To Receive A Cookie From The Browser? 
● Answer : 
● If you know that a cookie has been sent to the browser when it was visiting 
the server previously, you can check the built-in $_COOKIE array, which 
contains all cookies that were sent by the server previously. The script 
below shows you how to pickup one cookie from the $_COOKIE and loop 
through all cookies in $_COOKIE: 
● <?php 
● if (isset($_COOKIE["LoginName"])) { 
● $loginName = $_COOKIE["LoginName"]; 
● print("Received a cookie named as LoginName: ".$loginName."\n"); 
● } else { 
● print("Did not received any cookie named as LoginName.\n"); 
● } 
● print("All cookies received:\n"); 
● foreach ($_COOKIE as $name => $value) { 
● print " $name = $value\n"; 
● } 
● ?> 
● Question 207. How Cookies Are Transported From Servers To Browsers? 
● Answer : 
● Cookies are transported from a Web server to a Web browser in the header 
area of the HTTP response message. Each cookie will be included in a 
separate "Set-Cookie:" header line in the following format: 
● Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal. 
● Question 208. How Cookies Are Transported From Browsers To Servers? 
● Answer : 
● Cookies are transported from a Web browser to a Web server in the header 
area of the HTTP request message. Each cookie will be included in a 
separate "Cookie:" header line in the following format: 
● GET / HTTP/1.1 
● Cookie: name1=value1 
● Cookie: name2=value2 
● Cookie: name3=value3 
● ...... 
● Accept: */* 
● Question 209. Where Are The Persistent Cookies Stored On Your 
Computer? 
● Answer : 
● The location and file names where persistent cookies are stored on your 
computer depend on which browser you are using. If you using Microsoft 
Internet Explorer, persistent cookies are stored in the \Documents and 
Settings\$user\Cookies directory. Cookies are stored in multiple cookie 
files with one file per Web server. Check your cookie directory on your local 
system, you will be surprised to see how many Web servers are setting 
persistent cookies to your computer. 
● Question 210. How To Delete Cookie Files On Your Computer? 
● Answer : 
● A simple way to delete cookie files on your computer is to use the function 
offered by the IE browser. The following tutorial exercise shows you how to 
delete cookie files created by IE: 
● • Open IE (Internet Explorer) 
● • Go to Options/Internet Options 
● • Click the Delete Cookies button on the options dialog window. 
● Check the cookie directory again. All cookie files should be deleted. 
● Question 211. How Does Firefox Manage Cookies? 
● Answer : 
● FireFox browser allows you to delete old cookies, and gives you options to 
keep persistent cookies in cookie files until they reach their expiration 
time. The following tutorial shows you how to manage cookies in FireFox: 
● • Run FireFox 
● • Go to Tools/Options 
● • Click Privacy and then Cookies 
● • Click the Clear button to delete all old cookies 
● • Change the Keep Cookies option to "until they expire" to allow persistent 
cookies to be store a cookie file. 
● Question 212. What Are The Options To Transfer Session Ids? 
● Answer : 
● Once a new session is created, its session ID must be transferred to the 
client browser and included in the next client request, so that the PHP 
engine can find the same session created by the same visitor. The PHP 
engine has two options to transfer the session ID to the client browser: 
○ As URL parameter ​- The Session ID will be embedded in all 
URLs in the HTML document delivered to the client browser. 
When the visitor clicks any of those URLs, the session ID will 
be returned back to the Web server as part of the requesting 
URL. 
○ As a cookie -​ The session ID will be delivered as a cookie to 
the client browser. When visitor requests any other pages on 
the Web server, the session ID will be returned back to the Web 
server also as a cookie. 
● The PHP engine is configured to use URL parameters for transferring 
session IDs by default. 
● Question 213. Is It More Secure To Use Cookies To Transfer Session Ids? 
● Answer : 
● yes, because attacking your Web site using URL parameters is much easier 
than using cookies. 
● So if you are the system administrator of your Web server, you should set 
session.use_only_cookies=1. 
● If your Web server is provided by a hosting service provider, ask them to 
set session.use_only_cookies=1. 
● Question 214. What Is The Timeout Period On Session Values? 
● Answer : 
● The PHP engine has no direct settings on session timeout period. But it 
has a session garbage collection mechanism that you can set to remove 
those special files containing session values. There are 3 settings you can 
use to define the session garbage collection mechanism: 
● session.gc_probability = 1 
● session.gc_divisor = 1000 
● session.gc_maxlifetime = 1440 
● The first two settings tell the PHP engine to run the garbage collection 
process once every 1000 requests received by the Web server. The last 
setting tells the PHP engine to treat session values as garbage 1440 
seconds after they have not been used. 
● Putting all settings together, your session values probably be removed 
1440 seconds after the visitor stopping using your Web site. The 
probability of this removal is one over 1000 requests received after the 
1440-second period. 
● In another word, if visitor John stopped using your site, and there is no 
other visitors coming to your site, session values created for John will 
never be removed. However, if you have a busy site, like 1000 requests per 
minute, John's session values will be removed about one minute plus 1440 
seconds after John stopped using the site. 
● Question 215. How To Set Session.gc_maxlifetime Properly? 
● Answer : 
● As you know that session.gc_maxlifetime is the session value timeout 
period. You should set this value based on the usage pattern of your 
visitors. Here are some suggestions: 
● # Set it to 20 minutes for a normal Web site: 
● session.gc_maxlifetime = 1200 
● # Set it to 24 hours if visitors comes to the site many time a day: 
● # Example: Yahoo email site expires your session in 24 hours. 
● session.gc_maxlifetime = 86400 
● Question 216. How To Set Session.gc_divisor Properly? 
● Answer : 
● As you know that session.gc_divisor is the frequency of when the session 
garbage collection process will be executed. You should set this value 
based on the income request traffic. Here are some suggestions: 
● # Set it to 10, if traffic is less than 10,000 per day: 
● session.gc_divisor = 10 
● # Set it to 100, if traffic is between 10,000 and 100,000 per day: 
● session.gc_divisor = 100 
● # Set it to 1000, if traffic is greater than 100,000 per day: 
● session.gc_divisor = 1000 
● Question 217. How To Remove Values Saved In The Current Session? 
● Answer : 
● If you want to remove values saved in the current session, you should use 
the unset() function on those saved values in $_SESSION, or use array() to 
empty $_SESSION: 
○ unset($_SESSION['MyColor']) - Removes one value named 
MyColor in the current session. 
○ $_SESSION = array() - Removes all values in the current 
session. 
○ unset($_SESSION) - Bad statement. It may affect the session 
mechanism. 
● Question 218. How To Close A Session Properly? 
● Answer : 
● Let's say you site requires users to login. When a logged in user clicks the 
logout button, you need to close the session associated with this user 
properly in 3 steps: 
● 1. Remove all session values with $_SESSION = array(). 
● 2. Remove the session ID cookie with the setcookie() function. 
● 3. Destroy the session object with the session_destroy() function. 
● Below is a good sample script: 
● <?php 
● session_start(); 
● $_SESSION = array(); 
● if (isset($_COOKIE[session_name()])) { 
● setcookie(session_name(), '', time()-42000, '/'); 
● } 
● session_destroy(); 
● print("<html><pre>"); 
● print("Thank you for visiting PICKZYCenter.com.\n"); 
● print(" <a href=login.php>Login Again.</a>\n"); 
● print("</pre></html>\n"); 
● ?> 
● Question 219. What Is Session_register()? 
● Answer : 
● session_register() is old function that registers global variables into the 
current session. You should stop using session_register() and use array 
$_SESSION to save values into the current session now. 
● Question 220. What Do You Need To Connect Php To Mysql? 
● Answer : 
● If you want to access MySQL database server in your PHP script, you need 
to make sure that MySQL module is installed and turned on in your PHP 
engine. Check the PHP configuration file, php.ini, to make sure the 
extension=php_mysql.dll is not commented out. 
● The MySQL module offers a number of functions to allow you to work with 
MySQL server. Some commonly used MySQL functions are: 
● • mysql_connect -- Open a connection to a MySQL Server 
● • mysql_close -- Close MySQL connection 
● • mysql_db_query -- Send a MySQL query 
● • mysql_fetch_array -- Fetch a result row as an associative array, a numeric 
array, or both 
● • mysql_free_result -- Free result memory 
● • mysql_list_tables -- List tables in a MySQL database 
● • mysql_list_fields -- List MySQL table fields 
● Question 221. How To Connect To Mysql From A Php Script? 
● Answer : 
● If you want access the MySQL server, you must create a connection object 
first by calling the mysql_connect() function in the following format: 
● $con = mysql_connect($server, $username, $password); 
● If you are connecting to a local MySQL server, you don't need to specify 
username and password. If you are connecting to a MySQL server offered 
by your Web hosting company, they will provide you the server name, 
username, and password. 
● The following script shows you how to connect to a local MySQL server, 
obtained server information, and closed the connection: 
● <?php 
● $con = mysql_connect('localhost'); 
● print(mysql_get_server_info($con)."\n"); 
● print(mysql_get_host_info($con)."\n"); 
● mysql_close($con); 
● ?> 
● Question 222. How To Run A Sql Statement? 
● Answer : 
● You can run any types of SQL statements through the mysql_query() 
function. It takes the SQL statement as a string and returns different types 
of data depending on the SQL statement type and execution status: 
● • Returning FALSE, if the execution failed. 
● • Returning a result set object, if the execution is successful on a SELECT 
statement or other statement returning multiple rows of data. 
● • Returning TRUE, if the execution is successful on other statements. 
● Here is a good example of running a SQL statement with the mysql_query() 
function: 
● <?php 
● include "mysql_connection.php"; 
● $sql = 'SELECT sysdate() FROM dual'; 
● $rs = mysql_query($sql, $con); 
● $row = mysql_fetch_array($rs); 
● print("Database current time: ". $row[0] ."\n"); 
● mysql_close($con); 
● ?> 
● Question 223. How To Get The Number Of Rows Selected Or Affected By 
A Sql Statement? 
● Answer : 
● There are two functions you can use the get the number of rows selected 
or affected by a SQL statement: 
○ mysql_num_rows($rs)​ - Returns the number of rows selected 
in a result set object returned from SELECT statement. 
○ mysql_affected_rows()​ - Returns the number of rows affected 
by the last INSERT, UPDATE or DELETE statement. 
● Question 224. What Is A Result Set Object? 
● Answer : 
● A result set object is a logical representation of data rows returned by 
mysql_query() function on SELECT statements. Every result set object has 
an internal pointer used to identify the current row in the result set. Once 
you get a result set object, you can use the following functions to retrieve 
detail information: 
● • mysql_free_result($rs) - Closes this result set object. 
● • mysql_num_rows($rs) - Returns the number rows in the result set. 
● • mysql_num_fields($rs) - Returns the number fields in the result set. 
● • mysql_fetch_row($rs) - Returns an array contains the current row indexed 
by field position numbers. 
● • mysql_fetch_assoc($rs) - Returns an array contains the current row 
indexed by field names. 
● • mysql_fetch_array($rs) - Returns an array contains the current row with 
double indexes: field position numbers and filed names. 
● • mysql_fetch_lengths($rs) - Returns an array contains lengths of all fields 
in the last row returned. 
● • mysql_field_name($rs, $i) - Returns the name of the field of the specified 
index. 
● Question 225. What Is File Upload? 
● Answer : 
● File upload is Web page function which allows visitor to specify a file on 
the browser's system and submit it to the Web server. This is a very useful 
function for many interactive Web sites. Some examples are: 
○ Web base email systems for users to send attachments. 
○ Forums that allows user to submit pictures. 
○ Web sites file managers for users to build their own Web 
pages. 
● Which HTML Tag Allows Users to Specify a File for Uploading? 
● To present an input field on your Web page to allow users to specify a local 
file to upload, you need to use the <INPUT TYPE="FILE" ...> tag inside a 
<FORM ...> tag. The <INPUT TYPE="FILE" ...> will be displayed as a text 
input field followed by a button called "Browse...". Users can either enter 
the full path name of a local file, or click Browse button to go through a 
dialog box to select a file interactively. The following PHP code shows you 
a good example of the file upload tag: 
● <?php
print("<html><form>n");
print("<input type=file>n");
print("<input type=submit>n");
print("</form></html>n");
?>

You might also like