WordPress funtions

$path = get_home_path();  //  Return “Path: /var/www/htdocs/”
echo get_home_url();/ echo get_site_url(); //  Return “domain”
the_title( $before, $after, $echo );
echo get_the_title();
get_the_content( );//However get_the_content( ); in a WordPress template does one very important thing. It does not pass the content through the_content. Which means that it does not auto-embed videos, or expand shortcodes, among other things.
Just use get_the_content(); and you will remove those tags.

Advertisements

Run foreach loop just one iteration with PHP and get post child images

function marty_get_images($post_id) {
global $post;

$thumbnail_ID = get_post_thumbnail_id();

$images = get_children( array(‘post_parent’ => $post_id, ‘post_status’ => ‘inherit’, ‘post_type’ => ‘attachment’, ‘post_mime_type’ => ‘image’, ‘order’ => ‘ASC’, ‘orderby’ => ‘menu_order ID’) );

if ($images) :

foreach ($images as $attachment_id => $image) :

if ( $image->ID != $thumbnail_ID ) :

$img_title = $image->post_title; // title.
$img_caption = $image->post_excerpt; // caption.
$img_description = $image->post_content; // description.

$img_alt = get_post_meta($attachment_id, ‘_wp_attachment_image_alt’, true); //alt
if ($img_alt == ”) : $img_alt = $img_title; endif;

$big_array = image_downsize( $image->ID, ‘large’ );
$big_img_url = $big_array[0];

$thumb_array = image_downsize( $image->ID, ‘thumbnail’ );
$thumb_img_url = $thumb_array[0];

?>

<a href="” class=”thumb”><img src="” alt=”” title=”” />

<?php endif;

sort wordpres get_posts with advanced custom fields

$my_posts_array = get_posts( array(
‘post_type’ => ‘events’,
‘posts_per_page’ => ‘7’,
‘offset’ => 0,
‘post_status’ => ‘publish’,
‘suppress_filters’ => 0,
‘meta_query’ => array(
array(
‘key’ => ‘is_event’,
‘value’ => ‘a:1:{i:0;s:4:”true”;}’,
‘compare’ => ‘=’
)
),
‘orderby’ => ‘meta_value_num’,
‘meta_key’ => ‘closing_date’,
‘order’ => ‘ASC’,
)
);

PHP Interview quesitons

Tags

,

 What is Constants in PHP

A constant is an identifier (name) for a simple value. A constant value cannot change during the execution of the script (except for magic constants). Constants are useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings (such as database usernames and passwords).

Constants are defined using define() function, which accepts two arguments: the name of the constant, and its value. Here is an example of defining and using a constant in a script:
Example
Run this code »

<?php

// Defining constants

define(“PROGRAM”, “PHP”);

define(“VERSION”, “5.5.14”);

// Using constants

echo ‘Current ‘ . PROGRAM . ‘ version is: ‘ . VERSION;

?>

Question : What is the difference between split() and explode()?

The split() function splits the string into an array using a regular expression and returns an array.
Ex: split (:India:Nepal:Srilanka); returns an array that contains India, Nepal, Srilanka.

The explode () function splits the string by string.
Ex: explode (and India and Nepal and Srilanka); returns an array that contains India, Nepal, Srilanka.

What are rules to follow in wordpress plugin development?

Find a unique name
Setup a prefix (related to your brand)
Create the plugin’s folder
Create sub-folders for PHP files, assets, and translations
Create the main plugin file and fill in obligatory header information
Create a readme.txt file
Use proper constants and functions to detect paths to plugin files
Create additional PHP files and include them inside the main one
Create activation and deactivation functions
Create an uninstall script

Question :  Is multiple inheritance supported in PHP?

PHP includes only single inheritance, it means that a class can be extended from only one single class using the keyword ‘extended’.

In PHP, what are magic methods and how are they used?

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

Question :  What is the meaning of a final class and a final method?

‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overrided.

Question :  What is the use of the function ‘imagetypes()’?

imagetypes() gives the image format and types supported by the current version of GD-PHP.

Question :  What are the functions to be used to get the image’s properties (size, width and height)?

The functions are getimagesize() for size, imagesx() for width and imagesy() for height.

Question :  How can we check the value of a given variable is a number?

It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.

Question :  Is it possible to remove the HTML tags from data?

The strip_tags() function enables us to clean a string from the HTML tags.

Question :  what is the static variable in function useful for?

A static variable is defined within a function only the first time and its value can be modified during function calls as follows:

Question : How can we define a variable accessible in functions of a PHP script?

This feature is possible using the global keyword.
Question :  How can you pass a variable by reference?

To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2

Question :  What is the function func_num_args() used for?

The function func_num_args() is used to give the number of parameters passed into a function.

Question :  In PHP, objects are they passed by value or by reference?

In PHP, objects passed by value.

Question :  What’s the difference between __sleep and __wakeup?

__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.

Question : What is faster?

1- Combining two variables as follows:

$variable1 = ‘Hello ‘;

$variable2 = ‘World’;

$variable3 = $variable1.$variable2;

Or

2- $variable3 = “$variable1$variable2?;

$variable3 will contain “Hello World”. The first code is faster than the second code especially for large large sets of data.

Question :  what is the definition of a session?

A session is a logical object enabling us to preserve temporary data across multiple PHP pages.

Question :  How to initiate a session in PHP?

The use of the function session_start() lets us activating a session.

Question : How is it possible to propagate a session id?

It is possible to propagate a session id via cookies or URL parameters.

Question :  What is the meaning of a Persistent Cookie?

A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.

Question :  When sessions ends?

Sessions automatically ends when the PHP script finishs executing, but can be manually ended using the session_write_close().

Question :  What does $_SERVER means?

$_SERVER is an array including information created by the web server such as paths, headers, and script locations.

Question :  what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?

$a and $b:    TRUE if both $a and $b are TRUE.

$a & $b:        Bits that are set in both $a and $b are set.

Question : What is the difference between the functions strstr() and stristr()?

The string function strstr(string allString, string occ) returns part of allString from the first occurrence of occ to the end of allString. This function is case-

sensitive. stristr() is identical to strstr() except that it is case insensitive.

Question :  what is the difference between for and foreach?

for is expressed as follows:

for (expr1; expr2; expr3)

statement

The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is TRUE, the loop continues and the statements inside for are

executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested at the end of each iteration.

However, foreach provides an easy way to iterate over arrays and it is only used with arrays and objects.

1) Is it possible to submit a form with a dedicated button?

It is possible to use the document.form.submit() function to submit the form. For example: <input type=button value=”SUBMIT” onClick=”document.form.submit()”>

Question :  What is the difference between ereg_replace() and eregi_replace()?

The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.

Question :  Is it possible to protect special characters in a query string?

Yes, we use the urlencode() function to be able to protect special characters.

Question :  What are the different tables(Engine) present in MySQL, which one is default?
A. Following tables (Storage Engine) we can create
1. MyISAM(The default storage engine IN MYSQL 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. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex)

extension. )
2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)
3. Merge
4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred

term, although HEAP remains supported for backward compatibility. )
5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB

tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions)
6. EXAMPLE
7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )
8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )
9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)
10. BLACKHOLE (The BLACKHOLE storage engine acts as a “black hole” that accepts data but throws it away and does not store it. Retrievals always return an empty

result)

Question :  What is the use of friend function?
A. &nbsp;Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of&nbsp;one class or as

global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that&nbsp;is admitting them. Such functions

can use all attributes of the class which names them as a friend, as if they were themselves members of that&nbsp;class. A friend declaration is essentially a

prototype for a member function, but instead of requiring an implementation with the name of that class&nbsp;attached by the double colon syntax, a global function or

member function of another class provides the match.</p>

Question : What are the differences between public, private, protected, static, transient, final and volatile?

Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized.
volatile: a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.
Question : What are the differences between PHP 3 and PHP 4 and PHP 5?
A. There are lot of difference among these three version of php
Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come
Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language

constructive like C
In PHP5 1. Implementation of exceptions and exception handling<br>
2. Type hinting which allows you to force the type of a specific argument<br>
3. Overloading of methods through the __call function<br>
4. Full constructors and destructors etc through a __constuctor and __destructor function<br>
5. __autoload function for dynamically including certain include files depending on the class you are trying to create.<br>
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 &amp; Abstract Classes
8 Passed by Reference :
9 An __clone method if you really want to duplicate an object

What is an Abstract class?

Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.

 Question :  Difference b/w MyISAM and InnoDB in MySQL?

 

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

 Question :  How do you load classes in PHP?

They are trying to gauge your understanding of how class auto loading works. Review the “autoload” and “spl_autoload_register” function (note:you should use the later). The autoload function basically triggers a function when a class is instantiated, you can put whatever logic you like in it but generally you want to include the class file based on some sort of naming convention.

 

 Question : What Are The Advantages of Ternary Logic?

There are some valuable advantages to using this type of logic:

  • Makes coding simple if/else logic quicker
  • You can do your if/else logic inline with output instead of breaking your output building for if/else statements
  • Makes code shorter
  • Makes maintaining code quicker, easier
  • Job security?
PHP/cURL

step1: Initialize a curl session use curl_init().
step2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term “curl” using parameter “q=”. Set option for CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.
step3: Execute the curl session using curl_exec().
step4: Close the curl session we have created.
step5: Output the return string.

Briefly explain the difference between accessing a class method via -> and via ::?

Ans: When we access a class method via -> we will require object initialization but when we choose :: we can access the methods which performs static operation.

 

question :Swap two variables value without using third variable ?

a = 5;
$b = 6;
list($a, $b) = array($b, $a);
print $a;
print $b;

Output:

6

5

another simple way is

$a = $a + $b; // 5 + 6 = 11
$b = $a – $b; // 11 – 6 = 5
$a = $a – $b; // 11 – 5 = 6
print $a;
print $b;

Output:

6

5

 

Using the strlen() function

The strlen() function is used to find the length of a string.

 

Using the strpos() function

The strpos() function is used to search for a string or character within a string.

 

Magic Methods in PHP

Magic methods in php are some predefined function by php compiler which executes on some event. Magic methods starts with prefix __, for example __call, __get, __set.

 

How to speed up the website?

Enable gzip compression Compressed HTTP respond

“Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today’s Internet traffic travels through browsers that claim to support gzip,” says Yahoo.

Gzipping reduces the size of the HTTP response and helps to reduce response time. It’s an easy way to reduce page weight. You can enable it by adding the following code to your .htaccess file:

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>

Or, use the following PHP code at the top of your HTML/PHP file:

<?php if (substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’], ‘gzip’)) ob_start(“ob_gzhandler”); else ob_start(); ?>

Or, simply use plugins for your CMS (like the WP HTTP Compression plugin for WordPress).

SEOmoz uses gzip. However, some external javascripts (AdRoll, Simpli and CloudFront) could reduce transfer size more than 60% by using gzip.

What are the parameters for the PayPal payment process?

<form name=”frmOS” action=”<?=PAYPAL_URL?>” method=”post”>
<div style=”height:200px;”>
<h1><?=PAGE_TITLE?></h1>
<input type=”hidden” name=”cmd” value=”_xclick”>
<input type=”hidden” name=”business” value=”<?=PAYPAL_BIZ_EMAIL?>” />
<input type=”hidden” name=”item_name” value=”Order on Website Name” />
<input type=”hidden” name=”amount” value=”<?=$value?>” />
<input type=”hidden” name=”notify_url” value=”<?=PAYPAL_NOTIFY_URL?>” />
<input type=”hidden” name=”return” value=”<?=PAYPAL_RETURN_URL?>” />
<input type=”hidden” name=”cancel_return” value=”<?=PAYPAL_CANCEL_URL?>” />
<input type=”hidden” name=”image_url” value=”<?=PAYPAL_LOGO_URL?>” />
<input type=”hidden” name=”currency_code” value=”USD” />
<input type=”hidden” name=”lc” value=”<?=$value?>” />
<input type=”hidden” name=”rm” value=”1″ />
<input type=”hidden” name=”custom” value=”<?=$value?>” />
<input type=”hidden” name=”first_name” value=”<?=$value?>” />
<input type=”hidden” name=”last_name” value=”<?=$value?>” />
<input type=”hidden” name=”city” value=”<?=$value?>” />
<input type=”hidden” name=”state” value=”<?=$value?>” />
<input type=”hidden” name=”zip” value=”<?=$value?>” />
<input type=”hidden” name=”country” value=”<?=$value?>” />
<input type=”hidden” name=”phone” value=”<?=$value?>” />
<input type=”hidden” name=”email” value=”<?=$value?>” />
<input type=”hidden” name=”address1″ value=”<?=$value?>” />
<p align=”center” style=”margin-top:35px;”><input type=”submit” name=”submitPaypal” value=”Proceed to Payment &raquo;” style=”cursor:pointer” /></p>
</div>

Differences between abstract class and interface in PHP

Following are some main difference between abstract classes and interface in php

In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract.
Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.
Method of php interface must be public only. Method in abstract class in php could be public or protected both.
In abstract class you can define as well as declare methods. But in interface you can only defined your methods.

 What is ajax synchronous and asynchronous? 

Synchronous – Script stops and waits for the server to send back a reply before continuing. There are some situations where Synchronous Ajax is mandatory.

In standard Web applications, the interaction between the customer and the server is synchronous. This means that one has to happen after the other. If a customer clicks a link, the request is sent to the server, which then sends the results back.

Asynchronous – Where the script allows the page to continue to be processed and will handle the reply if and when it arrives. If anything goes wrong in the request and/or transfer of the file, your program still has the ability to recognize the problem and recover from it.
Processing asynchronously avoids the delay while the retrieval from the server is taking place because your visitor can continue to interact with the web page and the requested information will be processed with the response updating the page as and when it arrives.