Categories
DRUPAL HTML HTML5 JavaScript jQuery LAMP MySQL PHP

PHP ARCHITECT QUESTIONS AND ANSWERS

What’s the difference between  <SPAN> and  <div> tags?
Span is for inline elements. Div is for block elements.
<div>tags are block elements that allow you to position elements contained within block.
tags used for inline styling of text.
<div> tags create line breaks, <span> tags doesn’t.
div elements are placed in a row, in other words automatic break is inserted. Whereas in case of span elements all are coming one after the other without any breaks.
Note: Can change inline element into block level element through CSS and vise-versa.
div{display:inline}
span{display:block}
Explain Data encryption in PHP ?
The PHP crypt() function can be used to encrypt data.
MD5 is a one way HASH
base64_encode is for encoding data.
Echo, print, printf – what is the difference between these?
Print and echo both output what is passed to them. Print acts like a function, so you can use it in complex statements. Printf is used to format the output
how variables are passed to functions by reference and by value?
A variable is passed by value unless the variable is passed with an &, such as functionName(&$variableName)
How can I execute a PHP script using command line?
PHP script using command line can be executed using SAPI
(Server Application programming Interface). Using SAPI
Command Line Interface the PHP code can be passed to execute
directly
Example:
Php –r ‘print_r(get_defined_constanrs());’
php filename
From a shell/cmd prompt, php –v will display whether the SAPI is CLI or CGI
explain YAHOO’s 20 points for web performance optimization ?
1. Flush the buffer early [server]
2. Use GET for AJAX requests [server]
3. Post-load components [content]
4. Preload components [content]
5. Reduce the number of DOM elements [content]
6. Split components across domains [content]
7. Minimize the number of iframes [content]
8. No 404s [content]
9. Reduce cookie size [cookie]
10. Use cookie-free domains for components [cookie]
11. Minimize DOM access [javascript]
12. Develop smart event handlers [javascript]
13. Choose <link> over @import [css]
14. Avoid filters [css]
15. Optimize images [images]
16. Optimize CSS sprites [images]
17. Don’t scale images in HTML [images]
18. Make favicon.ico small and cacheable [images]
19. Keep components under 25K [mobile]
20. Pack components into a multipart document [mobile]
FMI : http://developer.yahoo.com/performance/rules.html
What are all the new changes in PHP6 ?
Here is the list :

  1. FILE_BINARY and FILE_TEXT constants available for use with filesystem functions.
  2. register_globals will be gone.
  3. magic_quotes will also disappear.
  4. $HTTP_*_VARS has been removed, in favour for $_GET, $_POST, etc.
  5. ereg() no longer available in core PHP6.
  6. Initiating objects with the reference operator (& new Object()) will generate E_STRICT error.
  7. E_STRICT error messages are included in E_ALL errors.
  8. {} for string offsets no longer available.
  9. [] un-deprecated for accessing characters in a string.
  10. ASP-style tags can no longer be used.
  11. Better Unicode Support.
  12. var will be an alias of public, and raises E_STRICT warning.
  13. Support for 64 bit integers.
  14. With ternary operator, the “true” expression is no longer required – this can be done: $a = $s ?: ‘b’; (Not clear yet exactly how this will work).
  15. zend.ze1_compatibility_mode removed.
  16. safe_mode is being removed.
  17. Freetype1 and GD1 support removed.
  18. dl() is only enabled when a SAPI layers registers it explicitly.
  19. Support for dynamic break levels removed.
  20. XMLReader and XMLWriter will be in the core distribution.
  21. mime_magic removed from the core.
  22. Fileinfo moved to the core.
  23. ext/soap on by default.
  24. foreach supports multi-dimensional arrays: foreach($a as $b => list($c, $d))
  25. microtime() will return as float by default.
  26. opcode cache included in core distribution, but turned off by default.
  27. flags parameter available for file_get_contents().
  28. before_needle parameter added to strstr() – allows strstr() to return part of haystack before occurence of the needle.
  29. namespace, import, and goto become reserved words.

FMI : http://blog.tuvinh.com/one-minute-with-php6/

Categories
LAMP Linux PHP

How to Upgrade PhpMyAdmin in Linux

How to Upgrade PhpMyAdmin in Linux distributions OS like Ubuntu, Redhat etc.. ?

There are 2 ways to install & maintain upgrade phpmyadmin in Linux operating systems.


First way :

Automated installations by using the personal archive repository for phpmyadmin


For adding repository list to Linux –

sudo add-apt-repository ppa:nijel/phpmyadmin

For first time installations

sudo apt-get install phpmyadmin

For updating the existing phpmyadmin second time onward where installation was done using the above command

sudo apt-get update phpmyadmin

Second way :


Manual installation by using the phpmyadmin download package

Make sure you have the sudo/root permissions for all software installations. 


Example takes was to upgarde to 4.8.1 version phpmyadmin –


Goto your home directory

cd /home/{username}


Download phpmyadmin package

wget https://files.phpmyadmin.net/phpMyAdmin/4.8.1/phpMyAdmin-4.8.1-all-languages.tar.gz


extract the downloaded package to folder

tar -zxvf phpMyAdmin-4.8.1-all-languages.tar.gz


rename it to proper folder as used in the webserver configurations

mv phpMyAdmin-4.8.1-all-languages phpmyadmin


Goto user share directory where all shared software installations are managed

cd /usr/share


Move if any existing phpmyadmin folder to rename as old folder

sudo mv phpmyadmin phpmyadmin_old


Goto your home directory

cd /home/{username}


move the download& extracted phpmyadmin folder to user share directory

sudo mv phpmyadmin /usr/share/phpmyadmin


Goto user share directory

cd /usr/share


Provide the required permissions for www-data webserver user to read/write/execute

sudo chgrp -R www-data phpmyadmin

sudo chmod -R ug+rwx phpmyadmin


Your phpmyadmin has been upgraded to latest version.

Categories
CSS DRUPAL JavaScript LAMP MySQL PHP

Drupal 8 Interview Questions and Answers

How do I add external CSS OR JS libraries in Drupal 8 ? 

You need to add external library (CSS, JS) into your_theme.libraries.yml and attach the library either in twig or in your controller


myLibrary:
js:
https://xyz.com/bootstrap/4.1.11/js/bootstrap.min.js: { type: external, minified: true }
css:
component:
https://xyz.com/bootstrap/4.1.11/css/bootstrap.min.css: { type: external, minified: true }

{{ attach_library ('mythemename/mylibrary') }}

What is TWIG ? 
Drupal uses a new theme engine called Twig. Its a flexible, fast, and secure PHP based theme engine.its templates are written in a syntax that’s less complex than a PHP template and easier to create interactive and more functional Drupal templates using Twig.

What is Clean URLs ? 
user-friendly URLs, or search engine-friendly URLs, are Uniform Resource Locators (URLs) intended to improve the usability and accessibility of a website is called Clean URLs.
In Drupal 8, ‘Clean URLs’ are enabled by default and can’t be disabled. Check your site’s URLs which should not contain ?q= within the URL. It has certain dependencies on Webserver modules to work properly.

Which are all the Symfony components used by Drupal 8 ?
Symfony Components used by Drupal 8 project :
ClassLoader
Console
CssSelector
Debug
DependencyInjection
EventDispatcher
HttpFoundation
HttpKernel
PHPUnit Bridge
Polyfill Iconv
Process
Routing
Serializer
Translation
Validator
Yaml

how to improve DRUPAL performance for anonymous and authenticated users ?
Anonymous Traffic
Lighter user, basic configuration and performance tuning should handle more use cases.

Authenticated Traffic
Heavier user, can lead to more complex configurations to handle load and performance.
Caching for Drupal Websites

so here are five of the most important caching solutions for a Drupal website:

Drupal’s built-in caching
Boost module
Memcached
Varnish
Views caching

Categories
LAMP MySQL PHP

12 Essential PHP Interview Questions

 Our Toptal Engineering Blog has published a great post called “12 Essential PHP Interview Questions,” and I think it would be of interest to all of you.
See the preview of article given below :
Consider the following code:
$str1 = ‘yabadabadoo’;
$str2 = ‘yaba’;
if (strpos($str1,$str2)) {
echo “\”” . $str1 . “\” contains \”” . $str2 . “\””;
} else {
echo “\”” . $str1 . “\” does not contain \”” . $str2 . “\””;
}
The output will be:
“yabadabadoo” does not contain “yaba”
Why? How can this code be fixed to work correctly?
To see more goto : www.toptal.com/php/interview-questions

Categories
DRUPAL LAMP MySQL PHP

Mindtree – DRUPAL interview questions

1) how to improve DRUPAL performance for anonymous and authenticated users ?
Anonymous Traffic
Lighter user, basic configuration and performance tuning should handle more use cases.
Authenticated Traffic
Heavier user, can lead to more complex configurations to handle load and performance.
Caching for Drupal Websites
so here are five of the most important caching solutions for a Drupal website:
Drupal’s  built-in caching
Boost module
Memcached
Varnish
Views caching
There are other options, of course, but these five cover most of the ground. Let’s briefly go through them one at a time.
Drupal’s Built-in Caching
Most of a Drupal site is stored in the database – nodes, information about blocks, etc. – and enabling the default caching will store the results of these database queries so that they aren’t executed every time a page is requested. Enabling these settings alone can have a big impact on performance, particularly if your pages use a lot of views. This one is kind of a no-brainer.
Boost Module
The Boost module is pretty great. It works very well in tandem with Drupal caching, but it requires some additional configuration. What you end up with after you have the module installed and configured is a caching system that stores the output of your Drupal site as static HTML pages. This takes PHP processing out of the equation, leading to another nice bump in performance.
Memcached
Memcached can speed up dynamic applications (like Drupal) by storing objects in memory. With Boost and Drupal caching, the data being cached is stored on the server’s hard drive. With memcached, it’s being stored in memory instead of on the drive, something that can greatly speed up the response time for a page request.
Memcached works great in conjunction with both Boost and Drupal caching. For most folks, however, it’s something a server administrator will have to help install and configure.
Varnish
Varnish is an HTTP accelerator that, similar to memcached, stores data in memory. It’s capable of serving pages much faster than Apache (the most common web server for Drupal sites).
It can also be used in conjunction with memcached, although it’s often the case that they are not used together and other advanced caching methods are instead implemented alongside Varnish. Most people will need a server admin to help set up Varnish on their server.
Views Caching
Another type of database caching is Views caching. Views is a very popular, but rather resource intensive, Drupal module. Implementing Views caching can give your site a nice additional performance boost by possibly removing a few database queries from the build process.
To set views caching, go to your view. On the right hand side, under Advanced > Other, you’ll see a link for Caching. Just go in and set a value – an hour is usually a good default – for each view on your site.
Performance and Scalability in Drupal 7
Less SQL.
One of the most commonly mentioned performance issues in Drupal 5 and 6 was the number of queries executed per page, with most of these coming from path alias lookups. Path aliases allow a link to example.com/about to be converted to example.com/node/1 automatically in both directions. What is less known is that these queries were introduced in Drupal 4.7 to fix a scalability issue in earlier versions of Drupal.
Paths, round trips and mass transit
In Drupal 7 two large changes to the path system were introduced:
The path system maintains a white-list of which kinds of paths to look up aliases for, to avoid making round trips when there is nothing there to find – if there’s no aliases for user/*, it doesn’t bother looking for them.
Each page builds a cache of paths that were last requested, replaced every 24 hours or on cache clears. This allows those aliases to be queried in one go on the next request. If a path isn’t in the cache, it’s looked up individually until the next time the cache is refreshed.
The combination of these two optimizations means that on cache misses only a subset of paths are queried.
Entities on the wagon
In Drupal 7, introduced the Entity API and the concept of ‘multiple load’. The entity_load() function takes an array of entity IDs so database queries and hooks can all act on the list of entities at the same time. If a single node takes five database queries to build, it will only take five queries to build 30 nodes in Drupal 7, compared to 150 queries for the same objects in Drupal 6.
Big data, big queries
As Drupal has become more popular, the number of Drupal sites storing large amounts of data has increased. Drupal 7 introduces a number of measures to deal with this.
The new database layer and query builder allows drivers to specify case-insensitive operators. This allows MySQL to use LIKE() for auto-complete and user name lookups instead of LOWER(), allowing these queries to use indexes rather than doing a full table scan.
Forum, taxonomy and tracker modules now build de-normalized tables containing the data needed to build listings. Queries that used to require conditions and sorts across multiple tables can now be run against a single table, fully indexed.
InnoDB is enabled by default, providing much better safety and performance than MyISAM, particularly in situations with a large number of writes.
Fields and NoSQL
These de-normalized tables help with specific pain points encountered by Drupal 6 sites using those core features. However, a bigger issue facing Drupal sites is the combination of highly flexible storage via modules like CCK and Flag combined with the need to display that data in many different ways (often using the equally flexible Views module). This flexibility tends to lead to slow queries.
A plug for pluggability
In addition to the pluggable watchdog, cache and session backends in Drupal 6, Drupal 7 added pluggable lock and queue APIs. This means the storage for these systems can be moved out of SQL to MongoDB, Memcached, APC, Beanstalkd and other technologies better suited to handle these tasks at high volume.
Files and front end
Alongside swapping out SQL, Drupal 7 also allows you to swap out your local filesystem much easier, both for saving and serving files. Core file handling now uses PHP stream wrappers, meaning any file storage method supported by a stream wrapper can be used for file operations. Support already exists for Amazon S3 and the PHP hash wrapper in contributed modules. CDN support also got easier, with the CDN project providing drop-in support from contrib.
2) Explain panels and page layout ?

Features of Panels

  • Panels supports styles, which can control how individual content panes, regions within a panel, and the entire panel will be rendered. While Panels ships with few styles, styles can be provided as plugins by modules, as well as by themes!
  • The layout builder is nice for visually designing a layout, but a real HTML guru doesn’t want the somewhat weighty HTML that this will create. Modules and themes can provide custom layouts that can fit a designer’s exacting specifications, but still allow the site builder to place content wherever you like.
  • Panels includes a pluggable caching mechanism. A single cache type is included, the ‘simple’ cache which is time-based. Since most sites have very specific caching needs based upon the content and traffic patterns, this system was designed to let sites that need to devise their own triggers for cache clearing and implement plugins that will work with Panels. Panels can be cached as a whole, meaning the entire output of the panel can be cached, or individual content panes that are heavy can be cached.
  • Panels can be integrated with Organic Groups through the og_panels module to allow individual groups to have their own customized layouts.
  • Panels integrates with Views to allow administrators to add any view as content. Or, for uses where the layout editor needs more tightly controlled content, Views can be given custom displays to provide only what the site administrator wants the panels builder to use.

Panels module is a User Interface on top of theme() and hook_theme()
It’s very easy to get overwhelmed by the number of options, buttons and links. So let’s start simpler: a two column layout.
Explaining Panels blog post image
The code needed to declare that this two column layout exists at all is really small. Browse around the directory declaring it. There is not much there. An info array tells us most importantly that we have left and right regions.
‘regions’ => array(
‘left’ => t(‘Left side’),
‘right’ => t(‘Right side’)
),
And there’s a template file that prints the left and right regions.

>

</div>

</div>
</div>
Page Manager is a UI on top of hook_menu() and hook_menu_alter()
The response you get when visiting a URL on a Drupal site is determined largely by hook_menu(). When you go to the user register page you see a registration form because the user module told hook_menu() that a registration form belonged there. Other stuff may appear in Blocks in sidebars, footer and headers that are outside the knowledge of hook_menu(). hook_menu() primarily controls the main response that shows up in the “content” region of page.tpl.php
Here the distinction between Panels and Page Manager becomes cloudy. Page Manager tells Drupal “I know taxonomy module told you how term pages look, but I am overriding that. Use this Panels configuration instead.” Page Manager changes the way Drupal responds to existing paths as well as telling Drupal about new ones.
Panels is not even necessary to use Page Manager. Out of the box, Page Manager gives you the option to override existing URL paths just to change the HTTP response code (for that rare case where you want node/%node to respond with a 403 for anonymous users but don’t want to use the node access system). There are even other modules like Contextual Adminstration https://www.drupal.org/project/context_admin which use Page Manager to add more administrative options.
To go over that Jazz use case one more time, Page Manager:
Overrides the normal ‘list all nodes’ behavior declared by Taxonomy module.
Replaces it with a package of Panels configuration which
Declares the layout it wants
Contains instructions for populating the regions of that layout based on the given “context” (the taxonomy term “Jazz”)
Panels Everywhere is a UI alternative to page.tpl.php and Blocks UI
I just mentioned above that Page Manager is the way to control the the “content” region inside page.tpl.php. Panels Everywhere is meant to entirely replace your typical page.tpl.php customizations and the Block configurations that feed that file.
This block will show up on every page except those the pages whose URL paths match a certain pattern. Blocks can also be restricted by user role.
Mini Panels is a UI on top of individual Blocks If Panels Everywhere is a way to replace Core’s mechanism for organizing and displaying existing Blocks, Mini Panels is a way to add more individual Blocks. If you are writing a new Block with Core you will need a few pieces. You will need a machine name like “online” for the user module’s “Who’s online” block that lists currently logged in users, and you might need a configuration form for something like the number of users to show
Mini Panels allows you to accomplish those same concepts with less new code or no code at all. Mini Panels is perhaps the purest implementation of Panels in that it contains just the base concepts of Panels. You pick a layout plugin which is how the Mini Panel will actually render.
Panelizer is a (replacement) UI on top of View Modes Panelizer became famous/infamous in the Drupal community for the way it allows editors to make per-node overrides to Page Manager variants (which again almost always contain Panels configurations). Forget about that part for a moment. Panelizer has expanded its scope and is now best understood as a UI on top of View Modes. When you enable Panelizer it will give you a giant grid of checkboxes.
If you Panelize an article teaser view mode and you use Page Manager plus Panels to control the article listing URL and Panels Everywhere to control the global level then you’ll have three layers of Panels. Yes, you can do that.
http://www.palantir.net/blog/explaining-panels-overview-drupal-developers
3) DRUPAL 7 – how to create Sub themes ?
Creating a sub-theme is really simple. A sub-theme inherits a lot of the design resources from its parent theme. We can have multiple sub-themes inheriting only one base theme.
It is important to know that what a sub-theme inherits from its parent theme.
A sub theme will inherit:
All style sheets
Template files
Functions and overrides defined in the template.php
A sub-theme will not inherit:
Logos and Favicons
Block regions
Advanced theme settings
Creating a sub theme
Theme Directory: Create a directory in your custom theme directory in the same way you create a theme. Give it a name. For example: mysubtheme.
.info file: Create an .info file in the directory mysubtheme as similar to the parent theme. The only difference will be the following line:
base theme = theme_name
Logo: Add the logo in the sub-theme directory.
Screenshot: Theme screenshot is inherited from the base’s theme. To override the same, just create a new screenshot.png in the sub theme directory.
Style Sheets: You must declare at least one stylesheet in your sub-theme for any of the parent theme’s stylesheets to be inherited. To override any particular css file (for instance, style.css), add the following line in your .info file and add a new css file with the same name in your sub-theme’s directory.
stylesheets[all][] = style.css
Javascripts: All the js files defined in the parent theme will be inherited. To override any particular js file, add the following line in your .info file and add a new js file (for instance, script.js), with the same name in your sub-theme’s directory.
scripts[] = script.js
Regions: You can declare a new set of regions in the sub-theme. To inherit the custom regions of the parent theme, the regions should be copied in the sub-theme’s .info file.
Template Files: You can add any template files in your sub theme. If the template file is found in your sub-theme’s directory, then Drupal will override the parent’s template files. Otherwise, it will use the parent’s template files.
Images: The images used in the theme can also be copied in the sub theme directory. If the image is found in your sub-theme’s directory then Drupal will override the parent theme’s image with the same name. Otherwise, it will use the parent’s image.
4) explain Hooks and give any example worked on ?
Hooks are how modules can interact with the core code of Drupal. They make it possible for a module to define new urls and pages within the site (hook_menu), to add content to pages (hook_block, hook_footer, etc.), to set up custom database tables (hook_schema), and more. This page lists the hooks provided in the core, but modules can define hooks of their own. For example the cck module defines hook_field_info, which can be used by modules that want to define a new type of content field. Most modules that define hooks will also provide documentation about them.
A hook is a PHP function that can be called from Drupal, or third-party modules, when necessary to do a task. Instead of having a prefixed list of functions to call, the list is build checking the enabled modules, and the functions they implement.
For example, Drupal uses hook_node_update(); when a node is being saved with node_save(), the following code is executed.
// Call the node specific callback (if any). This can be
// node_invoke($node, ‘insert’) or
// node_invoke($node, ‘update’).
node_invoke($node, $op);
What node_invoke() does is the following:
Getting the list of all the enabled modules
Checking if the enabled modules has a function whose name ends in “_node_update” and starts with the short name of the module
Calling that function, passing $node as parameter
Hooks can save their own data in a database, or alter the value returned from a function. The last case is, for example, what happens with hook_form_alter(), which alters the value of $form passed as reference to drupal_prepare_form().
Drupal hooks are generally invoked using three functions:
drupal_alter()
module_invoke()
module_invoke_all()
drupal_alter() is the function used to invoke specific hooks whose purpose is to alter the data passed them as reference, such as hook_form_alter(), hook_hook_info_alter(), and hook_tokens_alter().
There are other functions that are used to invoke hooks, such as node_invoke(), but those functions essentially use one of the functions I listed before.
5) Explain DRUPAL bootstrap ?
Bootstrap is the process during the which Drupal initializes itself; the process actually includes:
Setting the error, and the exception handlers
Initializing the value of some spec-global variables contained in $_SERVER
Initializing some variables with init_set()
Finding the cached version of the page to serve
Initializing the database
Setting the handlers that load files when a class, or an interface is not found
Initializing the Drupal variables
Initializing the PHP session
Initializing the language variable
Loading the enabled modules
6) explain features ? How do features work?
The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.
The purpose of the Features module is to copy configuration setups from one drupal site to another. It creates “packages” of the settings that can be shared among different sites. Today it is used in almost every development workflow to deploy changes from one environment to the other.
Assume that the developer creates a new content type and he wants to copy it to the development server. Here is what he will do with features:
1. He adds the content type to an existing feature (or creates a new one). features will automatically detect any dependencies (eg modules implementing the fields)
2. He downloads the features and copies it to the custom modules folder. Then he pushes it to the version control system.
3. The features module is pulled to the development site
4. The feature is enabled and the content type is automatically created.
Now assume that he makes some changes to the content type. Here is how he copies to changes to the site:
1. Updates the feature using the features UI or using drush (this causes the feature to pick up the changes)
2. Pushes the feature to the live site
3. He reverts the feature in the live site so that the changes are activated.
7) what are entitles and entitiy types?
An entity type is a useful abstraction to group together fields. Let’s consider some examples of entity types:
Nodes (content)
Comments
Taxonomy terms
User profiles
You can also build new kinds of entity types where the options above don’t suit your needs.
Bundles
Bundles are an implementation of an entity type to which fields can be attached. You can consider bundles as subtypes of an entity type. With content nodes (an entity type), for example, you can generate bundles (subtypes) like articles, blog posts, or products. Not all entity types have bundles, however. For example, users do not have separate bundles (subtypes). For the entity types that do allow bundles, you can create as many bundles (subtypes) as you want. Then, using the Field system, you can add different fields to each bundle. Examples include a file download field on Basic Pages and a subtitle field on Articles.
Fields
A field is a reusable piece of content. In technical terms, each field is a primitive data type, with custom validators and widgets for editing and formatters for display.
Entity
An entity would be one instance of a particular entity type such as a comment, taxonomy term or user profile or a bundle such as a blog post, article or product.
You can use entity_load to load any entity. Note, however, that the core does not provide a save or delete function, but thanks to Entity API module the missing pieces are added (entity_create(), entity_save(), entity_delete(), entity_view() and entity_access()).
Entity API module
The project Entity API extends the entity API of Drupal core in order to provide a unified way to deal with entities and their properties. Additionally, it provides an entity CRUD controller, which helps in simplifying the creation of new entity types.
Putting this in Object-Oriented Design/Programming terms
An entity type is a base class
A bundle is an extended class
A field is a class member, property, variable or field instance (depending on your naming preference)
An entity is an object or instance of a base or extended class
8)Multi Language translation in DRUPAL ?
There are two basic components to the translation system, the translation of the interface and the translation of content.
Translating the interface has to do with the translation of miscellaneous text strings used all over the site (like the label used on Submit buttons). These are elements that are the same on all sites no matter what actual content it contains. Because these strings are standardized, Drupal is able to create a system to provide everyone with translated values for all these elements in various languages. To take advantage of this you enable the core Locale module, which will allow you to grab translated text from the Drupal Localizer site and import them into your site
Content Translation
in earlier versions of Drupal by creating a complete copy of each node that needs translation. So the French node would have all the French values of the content and the English node would have all the English values. Then they are organized together in translation sets.
it is still available in Drupal 7, if you enable the core Content Translation module.
Entity Translation
In Drupal 7, a new model for content translation was created. In this system each piece of content consists of a single node, but each field on the node can have multiple copies, in different languages, all attached to the same entity.
The API to get this system working went into core, but there was no time (and not enough agreement) to get a UI into core. So the Entity Translation module was created to provide a way for site administrators and translators to use the new field translation system.
Creating a Site Using Entity Translation
The minimum list of modules we will need include:
Locale (included in core)
Entity Translation
Title (to translate the node titles)
Entity (required by Title)
To add some usability to the site, we’ll also use:
Internationalization (i18n)
Variable (required by many of the translation modules)
Localization Update
Language Icons

Categories
AJAX CSS LAMP MySQL PHP XML

MNC php interview questions and answers

1) what is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

2) what is garbage collection? default time ? refresh time? Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. arbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.

There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini  value

name                                          default

session.gc_maxlifetime     1440 seconds or 24 minutes

session.gc_probability      1

session.gc_divisor              100

3) PHP how to know user has read the email? Using Disposition-Notification-To: in mailheader we can get read receipt.

Add the possibility to define a read receipt when sending an email.

It’s quite straightforward, just edit email.php, and add this at vars definitions:

var $readReceipt = null;

And then, at ‘createHeader’ function add:

if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }

4) Runtime library loading ? without default mysql support, how to run mysql with php?

dl — Loads a PHP extension at runtime int dl ( string $library )

Loads the PHP extension given by the parameter library .

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

bool extension_loaded ( string $name ) — Find out whether an extension is loaded

Warning :This function has been removed from some SAPI’s in PHP 5.3.

5) what is XML-RPC ? XML-RPC is a remote procedure call protocol which uses XML to encode its calls and HTTP as a transport mechanism. An XML-RPC message is an HTTP-POST request. The body of the request is in XML. A procedure executes on the server and the value it returns is also formatted in XML.

6) default session time ? default session time in PHP is 1440 seconds or 24 minutes.

7) default session save path ? Default session save path id temporary folder /tmp

8) What is the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used) htmlentities() – Convert ALL special characters to HTML entities

9) how to do session using DB?

bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc ) using this function we can store sessions in DB.

PHP has a built-in ability to override its default session handling. The function session_set_save_handler() lets the programmer specify which functions should actually be called when it is time to read or write session information. by overriding the default functions using session_set_save_handler handle we can store session in Db like below example

class SessionManager {

var $life_time;

function SessionManager() {

// Read the maxlifetime setting from PHP $this->life_time = get_cfg_var(“session.gc_maxlifetime”);

// Register this object as the session handler session_set_save_handler( array( &$this, “open” ), array( &$this, “close” ), array( &$this, “read” ), array( &$this, “write”), array( &$this, “destroy”), array( &$this, “gc” ) );

}

function open( $save_path, $session_name ) {

global $sess_save_path;

$sess_save_path = $save_path;

// Don’t need to do anything. Just return TRUE.

return true;

}

function close() {

return true;

}

function read( $id ) {

// Set empty result $data = ”;

// Fetch session data from the selected database

$time = time();

$newid = mysql_real_escape_string($id); $sql = “SELECT `session_data` FROM `sessions` WHERE `session_id` = ‘$newid’ AND `expires` > $time”;

$rs = db_query($sql); $a = db_num_rows($rs);

if($a > 0) { $row = db_fetch_assoc($rs); $data = $row[‘session_data’];

}

return $data;

}

function write( $id, $data ) {

// Build query $time = time() + $this->life_time;

$newid = mysql_real_escape_string($id); $newdata = mysql_real_escape_string($data);

$sql = “REPLACE `sessions` (`session_id`,`session_data`,`expires`) VALUES(‘$newid’, ‘$newdata’, $time)”;

$rs = db_query($sql);

return TRUE;

}

function destroy( $id ) {

// Build query $newid = mysql_real_escape_string($id); $sql = “DELETE FROM `sessions` WHERE `session_id` = ‘$newid'”;

db_query($sql);

return TRUE;

}

function gc() {

// Garbage Collection

// Build DELETE query. Delete all records who have passed the expiration time $sql = ‘DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();’;

db_query($sql);

// Always return TRUE return true;

}

}

10) how to track user logged out or not? when user is idle ? By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.

The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

11) how to track no of user logged in ? whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.

12) in PHP for pdf which library used?

The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module.

FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.

FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

13) for image work which library?

You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

14) what is oops? encapsulation? abstract class? interface?

Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.

Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.

Abstract class is a template class that contains such things as variable declarations and methods, but cannot contain code for creating new instances. A class that contains one or more methods that are declared but not implemented and defined as abstract. 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.

15) what is design pattern? singleton pattern?

A design pattern is a general reusable solution to a commonly occurring problem in software design.

The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

16) what are magic methods?

Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()

17) what is magic quotes? Magic Quotes is a process that automagically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

18) diff b/w php4 & php5 ? In PHP5 1 Implementation of exceptions and exception handling

2. Type hinting which allows you to force the type of a specific argument as object, array or NULL

3. Overloading of methods through the __call function

4. Full constructors and destructors etc through a __constuctor and __destructor function

5. __autoload function for dynamically including certain include files depending on the class you are trying to create.

6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

7 Interfaces & Abstract Classes

8 Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.

9 An __clone method if you really want to duplicate an object

19) in php4 can you define a class? how to call class in php4? can you create object in php4?

yes you can define class and can call class by creating object of that class. but the diff b/w php4 & php5 is that in php4 everything was passed by value where as in php5 its by reference. And also any value change in reference object changes the actucal value of object also. And one more thing in introduction of __clone object in PHP5 for copying the object.

20) types of error? how to set error settings at run time?

here are three basic types of runtime errors in PHP:

1. 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 behaviour.

2. 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.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP?s default behaviour is to display them to the user when they take place.

by using ini_set function.

21) what is cross site scripting? SQL injection?

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.

SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed

22) what is outerjoin? inner join?

OUTER JOIN in SQL allows us to retrieve all values in a certain table regardless of whether these values are present in other tables

An inner join requires each record in the two joined tables to have a matching record. An inner join essentially combines the records from two tables (A and B) based on a given join-predicate.

23) what is URL rewriting?

Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users.

along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.

24) what is the major php security hole? how to avoid?

1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you don’t want the file contents to be seen, give the file a .php extension.

25) whether PHP supports Microsoft SQL server ? The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.

26) what is MVC? why its been used? Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.

WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:

A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code

27) what is framework? how it works? what is advantage?

In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance

28) what is CURL?

CURL means Client URL Library

curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks.

CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

29) HOW we can transfer files from one server to another server without web forms?

using CURL we can transfer files from one server to another server. ex:

Uploading file

<?php

/* http://localhost/upload.php: print_r($_POST); print_r($_FILES); */

$ch = curl_init();

$data = array(‘name’ => ‘Foo’, ‘file’ => ‘@/home/user/test.png’);

curl_setopt($ch, CURLOPT_URL, ‘http://localhost/upload.php’);

curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch); ?>

output:

Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 )   )
  30) using CSS can we have a scroll to table? 
No table won't support scrolling of its data. but we can do another workaround like placing a table
 in a DIV  layer and setting the DIV css property to overflow:auto will do the trick.
  31) how to increase session time in PHP ? 
In php.ini by setting session.gc_maxlifetime and session.cookie_lifetime values
we can change the session time in PHP.   
 32) what is UI? What are the five primary user-interface components?  
 A user interface is a means for human beings to interact with computer-based "tools" and"messages".
One presumed goal is to make the user's experience productive, efficient, pleasing, and humane.
 The primary components of UIs are  a) metaphors (fundamental concepts communicated
 through words, images, sounds, etc.)
b) mental models (structure of data, functions, tasks, roles, jobs, and people in organizations of work
and/or play)
 c) navigation (the process of moving through the mental models)
d) interaction (all input-output sequences and means for conveying feedback)
 e) and appearance (visual, verbal, acoustic, etc.).
33) How can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals.
In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.
The easiest way to use crontab is via the crontab command. # crontab This command ‘edits’ the crontab.
Upon employing this command, you will be able to enter the commands that you wish to run.
My version of Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not function properly.
The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command All the variables, with the exception of the command itself, are numerical constants.
In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can also include multiple values for each entry, simply by separating each value with a comma.
command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module).
The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content.
For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell.
If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so: # wget http://www.example.com/file.php Now, let’s go back to the mailstock.php file we created in the first part of this article.
We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.
This is what my crontab will look like: 0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php
34)Difference b/w OOPS concept in php4 and PHP5 ?
version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of objectoriented programming (OOP) were offered in version 4, several deficiencies existed, including: • An unorthodox object-referencing methodology • No means for setting the scope (public, private, protected, abstract) of fields and methods • No standard convention for naming constructors • Absence of object destructors • Lack of an object-cloning feature • Lack of support for interfaces
35) Difference b/w MyISAM and InnoDB in MySQL?
Ans:

  • The big difference between MySQL Table Type MyISAM and InnoDB is that InnoDB supports transaction
  • InnoDB supports some newer features: Transactions, row-level locking, foreign keys
  • InnoDB is for high volume, high performance
  • use MyISAM if they need speed and InnoDB for data integrity.
  • InnoDB has been designed for maximum performance when processing large data volumes
  • Even though MyISAM is faster than InnoDB
  • InnoDB supports transaction. You can commit and rollback with InnoDB but with MyISAM once you issue a command it’s done
  • MyISAM does not support foreign keys where as InnoDB supports
  • Fully integrated with MySQL Server, the InnoDB storage engine maintains its own buffer pool for caching data and indexes in main memory. InnoDB stores its tables and indexes in a tablespace, which may consist of several files (or raw disk partitions). This is different from, for example, MyISAM tables where each table is stored using separate files. InnoDB tables can be of any size even on operating systems where file size is limited to 2GB.
  • 36) how to set session tiem out at run time or how to extend the session timeout at runtime?
    Ans:
    Sometimes it is necessary to set the default timeout period for PHP. To find out what the default (file-based-sessions) session timeout value on the server is you can view it through a ini_get command:

    // Get the current Session Timeout Value
    $currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);

    Change the Session Timeout Value

    // Change the session timeout value to 30 minutes
    ini_set(’session.gc_maxlifetime’, 30*60);

    If you have changed the sessions to be placed inside a Database occasionally implementations will specify the expiry manually. You may need to check through the session management class and see if it is getting the session timeout value from the ini configuration or through a method parameter (with default). It may require a little hunting about.

    Categories
    LAMP MySQL PHP

    Aztecsoft php web developer interview questions and answers

    1) how to increase the web page performance ?
    1) Use lightweight templates
    2) Put Stylesheets at the Top
    3) Put Scripts at the Bottom
    4) Avoid CSS Expressions like As an example, the background color could be set to alternate every hour using CSS expressions.
    background-color: expression( (new Date()).getHours()%2 ? “#B8D4FF” : “#F08A00” );
    5) Make JavaScript and CSS External
    6) Minify JavaScript and CSS : Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times.
    7) Remove Duplicate Scripts
    8) Choose over @import
    9) Don’t Scale Images in HTML
    10) Make favicon.ico Small and Cacheable
    11) use Ajax, JSON, Jquery for fastening results
     
    2) $test=array( 0=>’one’ , 2=> ‘two’ , ‘3 ‘=>’three’ , ‘3a’=>5, ‘myindex’); print_r($test); what will be the output? 
    Array ( [0] => one [2] => two [3 ] => three [3a] => 5 [3] => myindex )
    3) what is output of this mysql function select substring_index(‘abc@123.com’,”@”,-1); 
    Ans:  123.com   explanation is below
    SUBSTRING_INDEX(str,delim,count)

    Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. SUBSTRING_INDEX() performs a case-sensitive match when searching for delim.

    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
            -> 'www.mysql'
    mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
            -> 'mysql.com'

    This function is multi-byte safe.
     
    4) An employee table having columns  id {employee id} , name {employee name},  m_id {manager id }  , write a query to select employee and their manager names  ? 
     

    Main table    
    id name m_id
    1 John 2
    2 Greek Tor 1
    3 Alex John 1
    4 Mike tour 1
    5 Brain J 3
    6 Ronald 3
    7 Kin 4
    8 Herod 3
    9 Alen 2
    10 Ronne 1

    Ans:  INNER join SQL command is mostly used to join one table to it self. The biggest advantage of doing this is to get linking information from the same table. We will try to understand this with an example. The best example of INNER join will be employee table where we will keep the employee and its manager as a single record. This way by linking to the table it self we will generate a report displaying it as two linked tables. Each record will have one additional field storing the data of the manager by keeping the employee ID and we will use M_ID ( manager ID ) to link with main employee ID. This way we will link two virtual tables generated from one main table. 
    let us use inner join to create one report on who is the manager of which employee. Check this SQL 
    SELECT t1.id, t1.name as emp_name, t2.name as manager FROM emp as t1 INNER JOIN emp as t2 on t2.id = t1.m_id

    id emp_name manager
    1 John Greek Tor
    2 Greek Tor John
    3 Alex John John
    4 Mike tour John
    5 Brain J Alex John
    6 Ronald Alex John
    7 Kin Mike tour
    8 Herod Alex John
    9 Alen Greek Tor
    10 Ronne John

    for more :  To generate only the manager table used this SQL
    SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t1.id=t2.m_id 
    Managers Table
     

     
    id emp_name
    2 Greek Tor
    1 John
    1 John
    1 John
    3 Alex John
    3 Alex John
    4 Mike tour
    3 Alex John
    2 Greek Tor
    1 John

     
    To generate only the employee table  used this SQL
    SELECT t1.id,t1.name as emp_name from emp as t1 INNER JOIN emp as t2 on t2.id=t1.m_id 

       
    id emp_name
    1 John
    2 Greek Tor
    3 Alex John
    4 Mike tour
    5 Brain J
    6 Ronald
    7 Kin
    8 Herod
    9 Alen
    10 Ronne

     
    use below dump for your reference 
    CREATE TABLE `emp` (
    `id` int(4) NOT NULL auto_increment,
    `name` varchar(25) NOT NULL default ”,
    `m_id` int(4) NOT NULL default ‘0’,
    UNIQUE KEY `id` (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
    — 
    — Dumping data for table `emp`
    — 
    INSERT INTO `emp` VALUES (1, ‘John’, 2);
    INSERT INTO `emp` VALUES (2, ‘Greek Tor’, 1);
    INSERT INTO `emp` VALUES (3, ‘Alex John’, 1);
    INSERT INTO `emp` VALUES (4, ‘Mike tour’, 1);
    INSERT INTO `emp` VALUES (5, ‘Brain J’, 3);
    INSERT INTO `emp` VALUES (6, ‘Ronald’, 3);
    INSERT INTO `emp` VALUES (7, ‘Kin’, 4);
    INSERT INTO `emp` VALUES (8, ‘Herod’, 3);
    INSERT INTO `emp` VALUES (9, ‘Alen’, 2);
    INSERT INTO `emp` VALUES (10, ‘Ronne’, 1);


    5) write code to read the following file content “rag.txt”  and replace postgre SQL to MySQL and output the content ?
    The postgre SQL database has become the world’s most popular open source database because of its consistent fast performance, high reliability and ease of use. postgre SQL used on every continent — Yes, even Antarctica! — by individual Web developers as well as many of the world’s largest and fastest-growing organizations to save time and money powering their high-volume Web sites, business-critical systems and packaged software by postgre SQL.
    Ans:
     $str = file_get_contents(‘rag.txt’);
    $str = str_replace(‘postgre SQL’ ,’MySQL’, $str);
    echo $str;
     
    6) how we can destroy session cookie?
    Ans: we can use session_destroy() or  to destroy particular cookie set it to past time using  setcookie () function like  setcookie (“TestCookie”“”time() – 3600);
    7) True or False 
    a) session_destroy()  : destroys all of the data from session   TRUE
    b) session_unset() : frees all session variable  TRUE

    c) unset($_SESSION) deletes all session data   FALSE    “Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.”  

    8) $array = array( “hi”, “Hello World” , “what”, “Good Morning”);  write code to output the array contents havng more than one word ?
    Ans: 
        

    <? $array = array( “hi”, “Hello World” , “what”, “Good Morning”); 
    $count = sizeof($array);
    $i =0;
    while ($i < $count )
    {
    echo “<br> ***********<br>”;
    $exp = explode ( ” ” ,$array[$i] );
    if (count($exp) > 1)
    echo $array[$i] .” is having more than  one word in “. $i.” position of array  <br>”;
    $i++;
    }
    ?>
    9) what is the output of the below code 
    $sec_array = array(“red”, “green”, “blue”,”yellow”);
    array_splice( $sec_array , 1, -1);
    print_r($sec_array );   ? 

     

    Ans: Array ( [0] => red [1] => yellow )
    10) how we can get the second value from the last in an array ?
    Ans: 
    example  <? 
    $check = array ( “rag”, “shara”, “sharag”, “man”,”woman”,”child”, “human”);
    echo $check[count($check)-2];
    ?>

    11)  What is the maximum length of a URL?
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL
    Firefox, Safari , Opera  supports more than 100,000 characters.  but some times server like Apache, IIS may not support these longer URL’s. so better to keep it short URL.


    Categories
    LAMP MySQL PHP

    PHP common interview questions – answers

    =,==,=== – what is the difference between these?
    = assigns a value, == checks if value is the same, === checks if value is the same and the variables are of the exact same type.
    Echo, print, printf – what is the difference between these?
    Print and echo both output what is passed to them. Print acts like a function, so you can use it in complex statements. Printf is used to format the output.
    Include, include once, require – what is the difference between these?
    Include will includes a file each time it is called. Include_once would only include a file one time, so if a php program has a file in two include_once statements only the first will be done. Requre is like include, but if the file included is not available a fatal error occurs and processing stops.
    Are variables passed to functions by reference or value?
    A variable is passed by value unless the variable is passed with an &, such as functionName(&$variableName)
    How do you encrypt data?
    The PHP md5() function is very pretty widely used. The PHP crypt() function can also be used to encrypt data. (Honestly, the one time I had this question I drew a complete blank, so I’m not exactly certain what they were looking for.)
    What editor or ide do you use?
    Interesting question, probably does say something about your programming capabilites.  use Eclipse 3.1 with PHP extensions, , Zend Studio  Serious Unix users would be good with vi or emacs.
    PHP  Static, what are they and how do you use them?
    As with Java, if the job is for OO PHP (that is PHP 5), there will be a question on PHP static variables. You may be asked how to reference a static from inside and outside of the class it is in, or just show that you get the basic concept of a variable or function that is for the whole class and not an instance.
    Design Patterns general questions
    Now we are really into OO stuff. As in java job interviews I’ve usually been asked about design patterns in fairly vague terms, such as “describe the design patterns used in the systems you have worked on”. I was asked that so much that I drew out some UML to bring with me to interviews, as I found drawing up the UML during the interview to be distracting and slow.
    How can I maintain the count of how many persons have hit my site?
    The IP of a visitor can be tracked by
    $ip = $_SERVER[‘REMOTE_ADDR’];
    Just insert this value with date into a table.
    What is difference between mysql_fetch_array(), mysql_fetch_row() and mysql_fetch_object()?
    mysql_fetch_array()– Fetche resultset from a table in the form of array
    Eg: $res= mysql_query(’select * from tbl’)
    while ($row=mysql_fetch_array($res))
    mysql_fetch_row()
    Fetch single row
    mysql_fetch_object()
    Fetches resultset as object
    How I can make a chat page in php in simple
    On click on chat submit button store the values in the text area to a text file using PHP file functions.
    you can use ajax fore improved user experiance.
    wrie another javascript + ajax function to call the contents from the text file in each 3 sec


     
    What is the difference between echo and print statement?
    Print is a function and returns a value. Using echo we can use more than one parameter
    echo “and a “, 1, 2, 3; 
    What is differenc between mysql_connect and mysql_pconnect?
    mysql_connect- Creates a connection with db
    mysql_pconnect- creates a persistant connection with db 
    How I can get IP address of the user?
    )$ip = $_SERVER[‘REMOTE_ADDR’]; 
    How I will check that user is logged in or not?
    store user information in session

    I want to make it a function and I want to use it in each page and after login I want to go in current page?
    )store url in a variable and put in session before
    After login redirect page to that url 
    How do we know browser properties?
    var_dump($_SERVER); 
    If you have to work with dates in the following format: “Tuesday, February 14, 2006 @ 10:39 am”, how can you convert them to another format, that is easier to use?
    first remove @ from the string and than use strtime to convert this to unix time stamp.
    What is difference between require_once(), require(), include()?
    all are for including afile into another file
    require- if fails shoot a fatal error
    include- if fails shoot a warning
    include/require_once- for make sure that the page is included once in another page

    Categories
    LAMP MySQL PHP

    PHP Advanced Questions and Answers part one

    PHP Advanced Questions and Answers part one :


    1.Is it possible to set a time expire page in PHP.?

    Yes it is

    Using header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);

    <?php
    header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);
    ?>

    2.How can we SAVE an image from a remote
    web Server to my web server using PHP?

    <?php
    $file_rimg = fopen(“http://w3answers /image23.jpg”,’rb’);
    $newfile_name_img = “/tmp/tutorial.file”;
    $file_wnew = fopen($newfile_name_img,’wb’);
    while (!feof($file_rimg)) {
    $chunk_rd = fread($file_rimg,1024);
    fwrite($file_wnew,$chunk_rd);
    }
    fclose($file_wnew);
    fclose(file_rimg);
    ?>
    3.What is the output of 2^2 in php ?

    The answer is 0 (Zero)
    Important note
    Everyone expected answer would be 4.   But answer is zero.  How it happened only in php ?

    The ^ operator is different in each language.In PHP ^ means the bitwise exlusive or of the two numbers.

    4.What is the output of below script?

    <?php
    $x = 3;
    switch ($x) {
    case 2: echo ‘line 1’; break;
    case 3:
    case 4: echo ‘line 2’; break;
    default: echo ‘line 3’;
    }
    ?>

    a. echo ‘line 3’;
    b. echo ‘line 2’;
    c. Error
    d. None of the above

    Ans: b (Answer is line2)
    5.What is the output here?

    <?php
    $x = ‘raj’;
    echo ‘Hello $x’;

    ?>

    a. helloravj
    b. Parse error
    c. hello $x
    d. syntax error

    ANS: c

    6.What output do you get here?

    <?php
    $list = array(“block”,”cut”,”pens”,”dogs”);
    $list[] = “elephant”;
    $list[] = “dragon”;
    print “$list[4]”;
    ?>

    a. Error
    b. elephant
    c. dragon
    d. nothing
    e. dogs

    ANS: b (elephant)

    7.what is the output for following code?

    <?php
    echo 12+FALSE;
    ?>

    a. 12
    b. no
    c. parse error
    d. T_ECHO error
    e. FALSE

    ANS: 12

    8.What is the output ?

    <?php
    $x=7;
    if ($x < 2) { echo “11”; }
    elseif ($x < 16) { echo “12”; }
    elseif ($x < 14) { echo “13”; }
    elseif ($x > 14) { echo “14”; }
    elseif ($x < 10) { echo “15”; }
    else { echo “16”; }

    ?>

    a.16
    b.15
    c.12
    d.13

    ANS:12

    9.What is the result here?

    <?php
    echo “test”;
    $x = ”;
    switch ($x) {
    case “0”: echo “String”; br;
    case 0: echo “”; break;
    case NULL: echo “NULL”; br;
    case FALSE: echo “integer”; br;
    case “”: echo “no string”; br;
    default: echo “nothing else”; br;
    }

    ?>

    a. Something else
    b. Empty string
    c. Integer
    d. String

    ANS: Integer

    10.What is the output?

    <?php
    function x ($y) {
    function y ($z) {
    return ($z*2); }
    return($y+3); }
    $y = 4;
    $y = x($y)*y($y);
    echo “$y”;
    ?>

    a. None
    b. 54
    c. 56
    d. 58

    ANS:56

     

    source: w3answers.com