PHP – HTML5
PHP
Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.
features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.
PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References
Features
Visibility : The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private.
HTML
How do you improve the performance of a website.
- code unification :Each CSS file must be loaded before the page can be displayed in an internet browser.
- compress css and javascript files:We can compress a CSS file by removing unnecessary spaces, comments,
- Using sprite images instead of multiple images
- Always put javascripts at the bottom of the page.
What is bootstrap ?
Bootstrap is CSS framework for developing responsive, mobile first projects on the web. Current version of bootstrap is v3.3.6. Bootstrap also comes with two preprocessors: less and saas.
Bootstrap uses 12 column grid system. Bootstrap’s grid system is responsive, and the columns will re-arrange depending on the screen size
What new features has been added in bootstrap 3?
- New Glyphicons icon font!
- Smallest file size.
- New grid system.
- its uses CSS compressors (Less/Saas)
Difference between container and container-fluid in bootstrap?
.container has a max width pixel value, whereas .container-fluid is max-width 100%.
.container-fluid continuously resizes as you change the width of your window/browser by any amount.
.container resizes in chunks at several certain widths, controlled by media queries (technically we can say it’s “fixed width”
because pixels values are specified, but if you stop there, people may get the
impression that it can’t change size – i.e. not responsive.)
Tell me latest jquery version ?
Latest version of jquery is V-3.1.0 (11-8-2016)
Difference between html5 tag and normal tag ?
HTML5 tag are called as semantic tags.
A semantic element clearly describes its meaning to both the browser and the developer.
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
Difference between live and bind function in jquery.
The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
The live() method was deprecated in jQuery version 1.7, and removed in version 1.9. Use the on() method instead.
Some new fautures of css3?
- border-radius (border-radius: 25px;)
- box-shadow (box-shadow:3px 3px 3px 2px #797979;)
- Text Shadow ( text-shadow: #aaa 2px 2px 2px;)
- Multiple Backgrounds
.container {
/* fallback */
background: url(image/bg1.png) no-repeat;
/* modern browsers */
background: url(image/bg1.png) 0 0 no-repeat,
url(image/bg2.png) 100% 0 no-repeat;
}
- Transition
We can add animation to an element using transition. We need to specify these parameters.
- transition-property
- transition-duration
- transition-timing-function
- transition-delay
div {
width: 150px;
height: 150px;
background: red;
/* For Safari 3.1 to 6.0 */
-webkit-transition-property: height;
-webkit-transition-duration: 2s;
-webkit-transition-timing-function: ease-in-out;
-webkit-transition-delay: 1s;
/* Standard syntax */
transition-property: height;
transition-duration: 2s;
transition-timing-function: linear;
transition-delay: 1s;
}
what is closest in jquery ? What’s the difference between .closest() and .parents(‘selector’)?
.closest() method begins its search with the element itself before progressing up the DOM tree, and stops when current element matches the selector.
.parents() Begins with the parent element, get the parent of each element in the current set of matched elements
What is json?
JSON stands for JavaScript Object Notation. JSON is language independent, lightweight data interchange format. JSON data is written as key value pairs.
Eg :”name”:”Selva”
Explain position property in css?
The CSS positioning properties allow you to position an element. There are four different positioning methods: Static, Fixed, relative, absolute.
Difference between $(this) and this in jquery?
Keyword ‘this’ is a native DOM element. $(this) is a jQuery object that allows you to call functions such as .addClass() on it.
Will HTML5 canvas supported in IE ?
HTML5 canvas is not supported in IE version less than 9. ExplorerCanvas(excanvas) a JS library is the option to render HTML5 canvas for IE6, 7, and 8.
what is jsonp?
JSONP is nothing but JSON with padding. JSONP is mostly used in RESTFull APIs(Cross domain request). JSONP is a simple trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.). JSONP request appends the callback function with URL. Eg: http://www.abcs.com/example.php?callback=simplecallback
Whenever the server receives the callback it will return the data. The data can be accessed using that call back function.
A simple implementation of JSONP request.
//
(function() {
var flickerAPI = “http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?”;
$.getJSON( flickerAPI, {
tags: “mount rainier”,
tagmode: “any”,
format: “json”
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( “” ).attr( “src“, item.media.m ).appendTo( “#images” );
if ( i === 3 ) {
return false;
}
});
});
})();
// ]]>
How do you create a simple plugin in jquery?
Sample plugin creation code is given below:
(function($){
$.fn.showLinkLocation = function() {
return this.filter(‘a’).each(function(){
$(this).append(
‘ (‘ + $(this).attr(‘href’) + ‘)’
);
});
};
}(jQuery));
// Usage example:
$(‘a’).showLinkLocation();
List out some CSS Frameworks for creating responsive templates?
Bootstrap
-> Bootstrap is mobile first framework. It includes predefined classes for easy layout options, as well as powerful mixins for generating more semantic layouts.
Foundation 3
-> Foundation 3 is built with Sass, a powerful CSS preprocessor. “Pricing Tables” is an interesting componenet in foundation 3. Pricing tables are suitable for marketing site for a subscription-based product. It also offers super cool features like Right-to-left text direction support.
Skeleton
Skeleton is a small collection of CSS files that can help to rapidly develop sites that look beautiful at any size, be it a 17″ laptop screen or an iPhone.
YAML 4
YAML 4 is built on SAAS. You can check the documentation in the above link.
ResponsiveAeon
Responsive Aeon is a simple, fast, Intuitive css framework. It contains almost 120 lines of code and only 1kb minified.
What is the difference between canvas and svg?
<canvas> is an HTML element which can be used to draw graphics using JavaScript. This can be used to draw graphs, create animations etc.
The <canvas> element is not supported in older browsers, but is supported in recent versions of all major browsers.
The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the HTML height and width property. The declaration is as follows.
<canvas id=”animate” width=”250″ height=”250″></canvas>
SVG stands for Scalable Vector Graphics (SVG) is based on XML markup language, for describing 2D vector graphics.
Can you explain the difference between cookies, sessionStorage and localStorage.?
LocalStorage stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data – unlike cookie expiry.
Local storage and session storage are perfect for non sensitive data. The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser
so should not be relied upon for storage of sensitive or security related data within applications.
Data stored in the SessionStorage is only available for the duration of the browser session (and is deleted when the window is closed) – it does however survive page reloads.
In cookie, we can store 4096 bytes of data. Data stored in the cookie can be hacked by the user, unless the site uses SSL. We can also prevent injections like Cross-Site Scripting (XSS)/Script injection using httponly in the header.
Explain about quirks mode?
There are three modes used by the layout engines in web browsers: quirks mode, almost standards mode, and full standards mode.
Quirks mode is turned on when there is no correct DOCTYPE declaration, and turned off when there is a DOCTYPE definition.
However, invalid HTML – with respect to the chosen DOCTYPE – can also cause the browser to switch to quirks mode.
What is meant by hardware acceleration?
It means the graphical rendering is done on dedicated hardware (your GPU / graphics card) rather than your CPU. Hardware acceleration generally produces more fluid animation.In general you should always enable hardware acceleration as it will result in better performance of your application.
This will usually be a higher frame rate (the number of images displayed per second), and the higher the frame rate, the smoother the animation.
How can you load css resources conditionally?
Using CSS media querises we can load CSS contidionally. If you want to load the stylesheet for the device less than 600px, then you can declare as below.
<link rel=”stylesheet” media=”screen and (min-width: 600px)” href=”small.css”>
This style sheet will only load for screen size less than 600px.
Difference between article and section tag in HTML5. How can you nest them in your document?
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
So basically the section element should contain related information bunched under a common heading.
The HTML5 <article> element represents a complete composition in a web page or web application that is independently distributable or reusable, e.g. in syndication.
This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
We can nest article inside a section tag and vice versa. This is completely legal interms of HTML5.
What happen when you dont use doctype?
When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications.
Also HTML5 tags such as < article >,< footer >, < header >, < nav >, < section > may not be supported if the Doctype is not declared.
What are data- attributes good for?
The data-* attributes is used to store custom data related to the page or application.The custom data can be used in JavaScript to complete events or animations.
Which set of definitions, HTML attributes or CSS properties, take precedence?
CSS properties take precedence over HTML attributes. If both are specified, HTML attributes will be displayed in browsers without CSS support but won’t have any effect in browsers with CSS support.
How do I eliminate the blue border around linked images?
in your CSS, you can specify the border property for linked images:
a img { border: none ; }
However, note that removing the border that indicates an image is a link makes it harder for users to distinguish quickly and easily which images on a web page are clickable.
Explain about HTML5 local storage ?
There are two ways to store data in HTML as objects locally :
- localStorage – store data across session acess
- sessionStorage – storing data for current session only
Data will be stored in key/value pair format.
example:
localStorage.empid=”420″;
sessionStorage.companyname = “Thiruvarur info tech ”;
explain CSS media queries ?
CSS media queries are used to develop responsive templates for different layout of screen, print, mobile , tablet or any other resolutions
CSS media queries can be added in 3 ways as like CSS style sheet :
Internal stylesheet : <style type=”text/css”>
@media only screen and (max-width: 600px){
/* rules apply to the device resolution is 480px or less */
}
</style>
Imported stylesheet : @import “tablet.css” (min-width: 800px) and (max-width: 1200px);
External stylesheet: <link rel=”stylesheet” type=”text/css” href=”deskto.css” media=”screen and (min-width: 1200px), print and (min-resolution: 300dpi)” />
explain css inheritance ?
Inheritance propagates property values from parent elements to their children. The inherited value of a property on an element is the computed value of the property on the element’s parent element. For the root element, which has no parent element, the inherited value is the initial value of the property.
<div class=”firstClass secondClass thirdClass fourthClass ” > </div >
what is javascript inheritance ?
In simple terms, inheritance is the concept of one thing gaining the properties or behaviours of something else.
Inherited children inherit their parent’s behaviour To say A inherits from B, is saying that A is a type of B.
In JavaScript You must use a special object called prototype.
function Animal() {}; // This is the Animal *Type*
Animal.prototype.eat = function () {
alert(“All animals can eat!”);
};
function Bird() {}; // Declaring a Bird *Type*
Bird.prototype = new Animal(); // Birds inherit from Animal
Bird.prototype.fly = function() {
alert(“Birds are special, they can fly!”);
};
The effect of this is that any Birds you create (called an instance of Bird) all have the properties of Animals
var aBird = new Bird(); // Create an instance of the Bird Type
aBird.eat(); // It should alert, so the inheritance worked
aBird.fly(); // Important part of inheritance, Bird is also different to Animal
var anAnimal = new Animal(); // Let’s check an instance of Animal now
anAnimal.eat(); // Alerts, no problem here
anAnimal.fly(); // Error will occur, since only Birds have fly() in its prototype
explain javascript associative array ?
Associative arrays are where we can associate a key string with a value string
JavaScript objects are also associative arrays.
i.e the property emp.Name can also be read by calling emp[‘Name’]
We can access each property by entering the name of the property as a string into the array
it refers to accessing the DOM elements of HTML also [as object or associative array]
explain JS Namespace ?
Namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace
and also helps to organize blocks of functionality into easily manageable groups that can be uniquely identified.
JavaScript doesn’t builtin support of namespacing but using objects and closures we can achieve a similar effect.
javascript Namespacing patterns :
1) Single global variables :
var myApplication = (function(){
function(){
/*…*/
},
return{
/*…*/
}
})();
2) Object literal notation :
var myApplication = {
getInfo:function(){ /**/ },
// we can also populate our object literal to support
// further object literal namespaces containing anything
// really:
models : {},
views : {
pages : {}
},
collections : {}
};
3) Nested namespacing :
var myApp = myApp || {};
// perform a similar existence check when defining nested
// children
myApp.routers = myApp.routers || {};
myApp.model = myApp.model || {};
myApp.model.special = myApp.model.special || {};
// nested namespaces can be as complex as required
4) Immediately-invoked Function Expressions :
// an (anonymous) immediately-invoked function expression
(function(){ /*…*/})();
// a named immediately-invoked function expression
(function foobar(){ /*..*/}());
// this is technically a self-executing function which is quite different
function foobar(){ foobar(); }
5) Namespace injection :
// define a namespace we can use later
var ns = ns || {}, ns2 = ns2 || {};
// the module/namespace creator
var creator = function(val){
var val = val || 0;
this.next = function(){
return val++
};
this.reset = function(){
val = 0;
}
}
creator.call(ns);
// ns.next, ns.reset now exist
creator.call(ns2, 5000);
// ns2 contains the same methods
// but has an overridden value for val
// of 5000
Type of webservice ?
there are two types of web service….1. SOAP [Simple Object Access Protocol] Webservice and 2. RESTful [REpresentational State Transfer] Webservice.
SOAP is a messaging protocol , REST is a design philosophy , not a protocol.
SOAP:
you define your interface in a .wsdl file, which describes exactly which input parameters are expected and how the return values will look like
there are tools to generate the .wsdl files out of java class hirarchies. JAXB for example
there are also tools to generate java objects/classes as part of eclipse for example (don’t know the name in the moment).
SOAP is very strict. Every request is validatet against the wsdl before processing.
A good but not so easy to start with framework for SOAP WS is Apache CXF
REST: (no hands on experience up to now, feel free to correct and improve 😉 ):
a way to access a webserver or web application to retrieve data from or send to it.
it’s only negotiated, how it is accessed.
common is something like this http://server.domain.com/app/type/id=123 to retrieve object of type type with id=123 very intuitive, but no automatic validation of requests.
The main advantages of REST web services are:
- Lightweight – not a lot of extra xml markup
- Human Readable Results
- Easy to build – no toolkits required
SOAP also has some advantages:
- Easy to consume – sometimes
- Rigid – type checking, adheres to a contract
- Development tools
What is namespacing?
In many programming languages, namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace. They’re also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified.Namespacing Fundamentals
- Single global variables
- Object literal notation
- Nested namespacing
- Immediately-invoked Function Expressions
- Namespace injection
Single global variables
One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:
var myApplication = (function(){
function(){
/*…*/
},
return{
/*…*/
}
})();
Object literal notation
Object literal notation can be thought of as an object containing a collection of key:value pairs with a colon separating each pair of keys and values. It’s syntax requires a comma to be used after each key:value pair with the exception of the last item in your object, similar to a normal array.
var myApplication = {
getInfo:function(){ /**/ },
// we can also populate our object literal to support
// further object literal namespaces containing anything
// really:
models : {},
views : {
pages : {}
},
collections : {}
};
One can also opt for adding properties directly to the namespace:
myApplication.foo = function(){
return “bar”;
}
myApplication.utils = {
toString:function(){
/*..*/
},
export: function(){
/*..*/
}
}
- Nested namespacing
- Immediately-invoked Function Expressions (IIFE)s
- Namespace injection
- Explain about css specificity
- what is the use of box shadow and tell me the syntax.
- how to acheive rounded corners in css3.
- How will you improve the performance of a website.
- What is the use of sprite images.
- What are the different font formats and how will you include in your css stylesheet.
- What is responsive web page layout.
- What is fluid layout and advantages of it ?
- What do you know about css animations. Will you do css3 animation if we give google access?
- what are the css frameworks you know. have you ever used any css frameworks like LESS SAAS?
- Difference between HTML4 and HTML5?
- What is the use of canvas ? have you ever used it.
- What is the main difference between canvas and svg?
- What are semantic tags in html5. What is the main advantage of it.
- How will you add a jquery to your page.
- What is the diiference between javascript and jquery?
- Tell me the difference between document.ready and onload function in jquery?
- how can u apply css in jquery?
- Can you dynamicaaly add a div using jquery ?
- What are filters in jquery?
- What is an anonymous function in jquery and how will you define it?
- Have you ever heared about MVC in javascript?
- Javascript or Jquery which is faster ?
- How can you animate using Jquery?
- Tell me the use of is() , eq() methods in jquery?
- Why we use index() method in jquery.
- Tell me jquery.noConflict() method.
- Have you ever contributed any plugin?
- Tell me what are the Jquery UI you know. And how can you customize them.?
Overview of HADOOP
When we look into the structure of this framework , we find that it is divided into HDFS and MapReduce.
The two hands of Hadoop framework
i.e. HDFS and MapReduce are Hadoop Distributed File System- the storage hand and the processing hand respectively. This skeleton divides the total data into smaller blocks and circulate them in assemblage through the junctions called nodes in the network. The JAR is sent to the nodes where the data needs to be worked on. Here the nodes responsible for those data residing near them work faster in transferring them.
Hadoop carries four programs of study.
They are :
-> Hadoop Common
-> HDFS
-> Hadoop YARN
-> Hadoop MapReduce
1. Hadoop common acts as the information centre that contains the collections of Hadoop libraries.
2. HDFS is the storage part of high band of frequencies.
3.The YARN organizes the properties that line up the user’s function in an assemblage.
4.MapReduce is the processor that processes all sets of data.
Hadoop is such a frame that can store and circulate huge data files without minimum error. Hence it is highly scalable.
1.This software costs very less for storing and performing computations on data in comparison with the traditional databases.
2.Accessing with different kinds of business solution data is done by Hadoop with ultimate comfort. It has been proving to be its best in decision making.
3.It helps in social media, emailing, log processing, data warehousing, error detection etc.
4. Since it maps the data wherever it is placed so Hadoop takes very less time in order to unfold any data. It hardly takes an hour to work on large petabytes of data. Hene, it is super fast.
Hence, the companies using Hadoop are able to gain far better insights. Whenever a data block goes from one node to another in the assemblage of the network, each block gets copied to each node and even if the data is lost, we will always be having a backup copy of it. Hence, fault occurrence is really very low.
Welcome New Year 2014
Hello Guys,
Wishes to everyone who online on this post.
Wish you all the best to you and your family for your bright future.
This year may come the biggest joy and joy so that you can’t explain that.
You all are invited here to wish Happy New Year 2014 each other.
You can easily wish each other just commenting below.
You have a big opportunity to start the new work today, you can enjoy yourself and motivate yourself by opting the following positive lines: –
Say to yourself every morning:
-Today is going to be a great day!
-I can handle more than I think I can!
-Things don’t get better by worrying about them!
-I can be satisfied if I try to do my best!
-There is always something to be happy about!
-I’m going to make someone happy today!
-It’s not good to be down!
-We always have an option!
-Life is great, make the most of it!
BE AN Optimist!
Best Wishes to all
Balt (selvabalaji)
TBS 5th Annual Day Celebration – A walk-through
It all started with a set of big ideas on everyone’s mind. A team was setup to discuss on the activities and arrangements for the celebration. The team members were Kalpana, Diviya, Sharmi, Balaji.
The initial discussion was done few weeks before, but the approval from management was received just 4 days before. We had a very short time to carry out the discussions on arrangements as we were done with our Company outing just a few days before. The team request was
- Sweet distribution
- Cultural activities
- Singing/dancing/skit/mimicry/miming
- Games
- Full day celebration
- Awarding
- Decorations
- Photo hanging
- Logo based gift
- Decoration craft
- Individual own décor items
- Cake cutting
- Theme based dress code (5th year – Wood based could be brown shades)
And the approval was Now we don’t want to give T-Shirt and also we have very very short time
- Morning Pooja with directors + all our team.
- Sweet Distribution
- Decoration and Cultural
- Award Giving
- Lunch.
DAY: 02.12.2013 – The Anniversary Day Eve
It was our tea break in the evening and we requested all our team members to accompany in the decoration task. It started by 4.30 PM in the evening.
Few started pumping the balloons, nearly 250 nos. | |
Few started sticking papers to make thoranam | |
While others drawing the number 5 to hangout showing the completion of 5 successful years, few others were slicing the pictures of individuals of the team to show off everyone that they are the backbone of this growth. | |
Few tied them on the wall. Few tied flowersIt was raining and hot bread bajji were served to enthu the team. The team was working out crossing 9.00 PM and this is how the decorations came out. | |
DAY: 03.12.2013 – The Anniversary Day
The day started with high level of curiosity. Morning pooja preparations were started. Decorated lamps, flower garlands for company name board, door entrance, rangoli with flowers. The ambience was filled with colorful paper decorations and flower decorations
The beautiful gifts made by Velmurugan and Kalaiarasan which decorates our office added more beauty
How Multiple Websites & Stores Work
One of Magento’s advanced features allows for management of multiple websites and stores within one installation, and we have an amazing system to support this: GWS – aka “Global, Website, Store.”
- Global: This refers to the entire installation.
- Website: Websites are ‘parents’ of stores. A website consists of one or more stores. Websites can be set up to share customer data, or not to share any data
- Store (or store view group): Stores are ‘children’ of websites. Products and Categories are managed on the store level. A root category is configured for each store view group, allowing multiple stores under the same website to have totally different catalog structures.
- Store View: A store needs one or more store views to be browse-able in the front-end. The catalog structure per store view will always be the same, it simply allows for multiple presentations of the data in the front. 90% of implementations will likely use store views to allow customers to switch between 2 or more languages.
-
Example scenario
Let’s say you want to sell appliances, consumer electronics, and DVD’s and CD’s. For the purpose of this example we’ll separate the catalog into two stores and three websites. The appliance line will be sold on its own website, and the remaining items on another website. You bought appliances.com and coolstuff.com for this purpose. You don’t want customer data and order data to be shared between the two websites, so data sharing will be turn off in the configuration between them.
Under coolstuff.com you create two stores – Electronics, and Media. Consumer electronics will be sold through the electronics store, and the media items through the Media store. Since each line of items is very extensive, it makes sense to create a separate category structure for the Media store and the Electronics store… otherwise the category tree would be large and cumbersome. When the stores are created, you simply assign a different root category to each store.
In addition, you want to feature your catalog for both websites in English and Spanish. To do this, you will create an English and Spanish store view for each of the three stores. When entering catalog data you can switch store views in the admin to create the additional product titles, descriptions etc…
Configuration
The configuration of Magento uses GWS as a kind of tree when setting up the stores. When it is initially installed, all configuration settings point to “default”, meaning the global installation. A check box next to each configurable item can be un-checked in a particular website or store view, to indicate that this item will be specific to this website or store view. For example, you will offer authorize.net as a payment module on both websites, but you only want to offer google checkout on coolstuff.com. In the configuration, you’d select coolstuff.com in the store view drop-down, find the google API settings, and un-check “use default” in the google checkout tab. For this specific website you can now enable or disable google checkout.
All modules in the configuration function the same way.
Moving on to store views – after a store view has been created, you can configure the layout and visual settings of the store view however you’d like – a drop-down allows customers to switch between store views. This will reload the current page with the alternate view. This can be used for multiple languages, but can also be a way to easily do A-B testing between several design packages to see if one yields more conversions. The possibilities are endless!
The above is meant as a basic overview of this functionality – the best way to learn how to set it all up is to install Magento and get in there and start playing around.
Magento Remove index.php from url
Magento by default added the index,php in url .So,As per the SEO page will not get indexed properly SO here we have try to Remove index.php in url from both End Access Magento URL without index.php
For example:
http://domain.com/index.php/category to
http://domain.com/categoryThen Just follow steps
1) Login to admin section by using the URL http://domain.com/index.php/admin
2) then go to “System >> Configuration >>Web >> Search Engines Optimization” Use Web Server Rewrites : YES
3) Go to “System >> Configuration >>Web >>Secure” Use secure URL Frontend: YES
4)Then create the .htaccess file under your the magento installed folder.
If the magento installed under document root ( /home/username/public_html) then add follogig rules into .htaccess file
RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] and If the magento installed under /shop or directory then add the following rules into ” /home/username/public_html/shop/.htaccess ” file. RewriteEngine On RewriteBase /shop/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /shop/index.php [L]Thst's it just refresh the cache .Hope this will help!
Magento’s Default Files and Folders Structure
This part of the Magento tutorial will provide detailed information regarding the Magento’s default files and folders structure.
You will learn more about the functions of main files and folders included in the Magento package.
The files and folders included in the main directory are as follows:
• .htaccess – contains mod_rewrite rules, which are essential for the Search Engine Friendly URLs. There you can also find standard web server and php directives that can improve your web site performance.
• .htaccess.sample – this is a backup of the .htaccess file. If you modify .htaccess it can be used in order to get the default settings.
• 404 (directory) – The folder stores the default 404 template and skin for Magento.
• app (directory) – This folder contains the modules, themes, configuration and translation files. Also there are the template files for the default administrationtheme and the installation.
• cron.php – a Cron Job should be set for this file. Executing of the file on a defined time period will ensure that the complicated Magento caching system will not affect the web site performance.
• downloader (directory) – This is the storage of the web downloader files. They are used for the installation and upgrade of Magento through your browser.
• favicon.ico – the default favicon for Magento. A small icon that is shown in the browser’s tool bar once your web site is loaded.
• index.php – the main index file for Magento.
• index.php.sample – A backup of the default index file. It can be used to revert the changes in a case of a index.php modification.
• js (directory) – Contains the pre-compiled libraries of the JavaScript code included in Magento.
• lib (directory) – The Magento core code is located in this folder. It contains the software’s PHP libraries.
• LICENSE_AFL.txt – The Academic Free License under which the Magento software is distributed.
• LICENSE.txt – The Open Software License under which the Magento software is distributed.
• media (directory) – This is the storage of the Magento media files – images out of the box, generated thumbnails, uploaded products images. It is also used as a container for importing images through the mass import/export tools.
• mage (in versions older than 1.4.2.0 this tool was called pear)- The file controls the automatic update through the downloader script and SSH. It handles the update of each individual Magento module.
• php.ini.sample – This file contains sample php directives that can be used in order to modify your PHP setup. If you want to alter the default setup edit the file and then rename it to php.ini.
• pkginfo (directory) – Contains files with information regarding the modules upgrades’ changes.
• report (directory) – This folder contains the skin of the Magento errors reports.
• skin (directory) – There are located the themes files – images, JavaScript files, CSS files, Flash files. Also there can be found the skin files for the installation of skins and administration templates.
• var (directory) – Cache, sessions, database backups, data exports and cached error reports can be found in this directory.
If you want to modify an existing template or set a new one you should know that the template files are separated in 3 folders:
• /app/design/frontend/default/YOUR_TEMPLATE_NAME/layout/ – Contains the .xml files that define which modules should be called by the template files and loaded in defined areas on the site.
• /app/design/frontend/default/YOUR_TEMPLATE_NAME/template/ – Contains files and subfolders that structure the final output for the users using the functions located in the layout/ folder.
• /skin/frontend/default/YOUR_TEMPLATE_NAME/ – Contains the CSS, images, JavaScript and Flash files related to the template.
7 Reasons Why WordPress Made PHP Popular, not PHP Frameworks – PHP Classes blog
7 Reasons Why WordPress Made PHP Popular, not PHP Frameworks
1. WordPress is the Most Popular PHP Application
Counting the number of search results on several popular search sites may seem to be a way to measure the relative popularity of a technology, language, application or a product.
However, that way does not seem to be very reliable method. When a search site changes its algorithms, you may see changes in the results that really do not have to do so much changes in the popularity of those technologies.
A more reliable way to measure the relative popularity of a technology is to resort to Google Trends. This is a site that Google provides to show the evolution of the relative number of searches done by given keywords over time.
As you may see in the following Google Trends chart, WordPress is much more popular than other PHP applications like Joomla, Drupal, Magento (which is Zend Framework based).
Google Trends: WordPress, Joomla, Drupal, Magento, Zend Framework
2. WordPress alone is much more popular than any PHP framework
Google Trends: WordPress, Zend Framework, Symfony PHP, CakePHP
3. WordPress does not use third-party PHP frameworks
WordPress has been using some third-party components but they are not really full-stack frameworks. This implies WordPress never needed a full-stack framework to be built. The use of such frameworks would hardly make a difference to its popularity.
4. Applications make technologies popular, not components
In the chart above you may notice that Magento is much more popular than Zend Framework. Magento is built on Zend Framework. This seems to imply that what makes applications popular is whether they solve users problems, not the components that they are built on.
WordPress is also popular because it is useful to many users. When users need to host a WordPress installation they need to seek a PHP hosting service. So they know at least superficially what is PHP and that they need PHP hosting.
This means that WordPress helped making PHP even more popular. The more installations there are of WordPress, the more PHP becomes popular.
5. The Extensible WordPress plugin ecosystem
One of the most important reasons that made WordPress popular is the myriad of plugins that were developed to provide additional features.
There are WordPress plugins for practically everything, including those that can turn it into other applications besides being a blog system. There are plugins that can turn it into forums, e-commerce sites, trouble ticket systems, etc., anything.
If WordPress as blog application was already popular, it became even more popular as a platform that can be turned into any type of application.
6. Non-Programmers develop in PHP just because of WordPress
If you need a site that requires certain features that WordPress does not have, you can develop new plugins to extend WordPress further and taylor it to your needs.
Many of the WordPress users were not really programmers. They started programming because they needed to have features in WordPress for which there was no suitable plugin providing them.
This means that many non-programmers had to learn PHP to be able to develop new WordPress plugins. That helped making PHP more popular even among non-programmers.
7. Pragmatism is better than Purism
In sum I could say that WordPress and PHP in general became popular because they can be used to address practical needs of many users.
Neither WordPress nor PHP are examples of software projects that are technically beautiful, are consistent, always follow well-thought project plans and adopt praised design patterns.
But that does not matter. They were created by people with a very pragmatic sense. They were focused on solving real world needs.
As for many of the PHP frameworks, they seem to have been developed in a totally different planet. They are often developed by purist people that seem to be more concerned with the number of design patterns they employ in the framework components than with being pragmatic and solve real PHP application needs.
To make it worse, many PHP frameworks systematically adopt practices of other frameworks developed for other languages. That raises totally unnecessary difficulties for PHP developers that try to use them.
One example of this problem is the configuration formats. In the Java world it is still usual to use XML as format for storing configuration values. XML is a portable format that can be written by humans. It was certainly a progress when compared with binary formats used to serialize data structures by C++ applications in the past.
This was a fine solution in the year 2000 but the fact is that XML is a drag. You need to keep opening and closing tags for every value. Sometimes values are stored as tag attributes, other times as tag values. It is often a pain to use.
Then Ruby On Rails came with the promise to get rid of some of the pains of the Java world habits. Instead of using XML, they decided to use YAML, which is a simplified markup language. It is simpler than XML but it is yet another format that you need to learn.
Several PHP frameworks were built copying Ruby on Rails practices, including the use of YAML as configuration format. Many years have passed and they still used YAML.
If you are a PHP developer, the format you are most familiar with is PHP. Why don’t these PHP frameworks make the lives of PHP developers better and adopt PHP scripts as configuration formats? PHP scripts can even be cached and so be loaded much faster.
In the worst case, if you need to use a more portable format, why these PHP frameworks do not use the JSON format to store configuration values? JSON is JavaScript. Every PHP developer knows JavaScript. It is only natural to adopt JSON nowadays.
Unfortunately many PHP frameworks as still stuck with formats that are not a natural choice for PHP developers, like XML, YAML or even INI (a legacy format of the Windows world).
I always get this feeling that PHP frameworks are not meant to please PHP developers. They seem to have been thought to please Java or Ruby developers. To make it worse, many of the newer PHP frameworks keep copying the same mistakes of older frameworks.
Obviously there are exceptions. There are indeed some PHP frameworks that were developed in a more pragmatic way for PHP developers. You can easily learn them without having to learn about Java or Ruby frameworks first.
Unfortunately those seem to not be the PHP frameworks that get more visibility. Maybe it is time for the PHP framework developers rethink their approach and think more about the PHP developers than about developers of other languages.
Shall I develop My Sites with WordPress or with a PHP Framework?
One frequent dilemma that PHP developers have is whether they should develop sites on top of WordPress or develop them from scratch based on a existing PHP framework?
This is a tough call. If the site is a blog, it may be an obvious choice to create it based on WordPress and save lots of development time. If the site is more than a blog but there are plugins for the functionality you need, WordPress may still be the best option.
Now if your site is very different than a blog, the amount of code that you would reuse from WordPress would be much less when compared to the whole project size. In that case, it may be better to start the development of the site from scratch.
If you still need a blog, you can use WordPress in a separate domain or a separate directory of your site.
For the bulk of the functionality you need to develop, you can use a existing PHP framework to gain some development time, or use your own framework if you have a good capable framework to address your needs.
Personally I tend to go for the last option. I can have more control of my project, but I am well aware that this route can take me more time to develop and fix eventual bugs in the code.
Frameworks are good when they enforce a productive method
Despite of the problems described above that many PHP frameworks have, for some people adopting a framework is probably the best solution, especially if it is what is called a “opinionated framework”.
That is what are called frameworks that impose a certain development methodology. This means that there is only one way to develop applications with those frameworks.
The reason why this is a good solution for some developers is because they do not have a well defined development methodology. This means that they do not know how to start, how to progress and how to deploy an application, unless somebody tells them how to do it.
Since opinionated frameworks impose a certain development method, the developers learn how to develop their applications following the methodology imposed by the framework.
One example of opinionated framework is Ruby on Rails. PHP frameworks that are inspired in Ruby On Rails tend to be also opinionated.
Opinions are not Facts
Well this article is just about my opinion and my experience of as developer that has been creating software for several decades now.
But opinions are just that, points of view of specific people. Expressing an opinion does not mean it is the only way to interpret the facts.
Just like the Tiobe Index people expressed their opinion stating that PHP popularity growth was due to Zend Framework 2 release last year, other people may express a different interpretation of the facts.
What do you think? Do you have a different opinion about what was discussed in this article? Post a comment to tell what you think.
Get line number of the code
<!--?
class myTest
{
function addMyAddress($street)
{
echo "
In class function at:".__LINE__;
echo "
class function called from:";
$e = new Exception();
$trace = $e->getTrace();
echo '
';print_r($trace);
// OR print_r(debug_backtrace());
}
}
echo "
Class created at:".__LINE__; $obj = new myTest();
echo "
Function called at:".__LINE__; $obj->addMyAddress('A/13 Skyline');
?>
Get any Website Page Title From URL in PHP
Hey guys,here below describe the how to get the page title form any website page using URL. Here for getting the page title we are using the file_get_contents function.This one also achieve using fopen( ) but in some servers disabled this function now a days due to some security reasons.
Here below shows the PHP code to get the page title form the URL.
<!--?php
function pageTitle($page_url)
{
$read_page=file_get_contents($page_url);
preg_match("/<title.*?>[\n\r\s]*(.*)[\n\r\s]*<\/title>/", $read_page, $page_title);
if (isset($page_title[1]))
{
if ($page_title[1] == '')
{
return $page_url;
}
$page_title = $page_title[1];
return trim($page_title);
}
else
{
return $page_url;
}
}
?>
Jquery Timeago Implementation with PHP.
Nowadays timeago is the most important functionality in social networking sites, it helps to updating timestamps automatically. Recent days I received few requests from 9lessons readers that asked me how to implement timeago plugin with dynamic loading live data using PHP. In this post I am just presenting a simple tip to implement timeago in a better way.
Why Live Query
LiveQuery utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
Code
Contains javascipt code. $(this).timeago()- here this element is refers to timeagoclass selector of the anchor tag.
// <![CDATA[
javascript” src=”js/jquery.min.js”>
// ]]>
// <![CDATA[
javascript” src=”js/jquery.livequery.js”>
// ]]>
// <![CDATA[
javascript” src=”js/jquery.timeago.js”>
// ]]>
<script type=”text/javascript”>
$(document).ready(function(){
$(“.timeago”).livequery(function() // LiveQuery
{
$(this).timeago(); // Calling Timeago Funtion
});
});
</script>//HTML & PHP Code
<!–?php
$time=time(); // Current timestamp eg: 1371612613
$mtime=date(“c”, $time); // Converts to date formate 2013-06-19T03:30:13+00:00
?>You opened this page <a href=’#’ class=’timeago’ title=”<!–?php echo$mtime; ?>“></a>
Login with Facebook using PHP SDK in CakePHP
Here we used PHP SDK 3.0 and CakePHP 2.X for the process of authentication and authorizing users for your app.
For Creating an App, which you can obtain from the App Dashboard.
You need App Id and App Secret for integration of the facebook login in cakephp.
In this CakePHP module we included the Facebook PHP SDK 3.0 in vendors of the app directory.And we define Some variables in Core.php
And We create one file which is facebook.php in config folder for the define of AppId and Appsecret.
$config
=
array
(
'Facebook'
=>
array
(
'appId'
=>
'YOUR APP ID'
,
'secret'
=>
'YOUR APP SECRET'
,
)
);
We create one Controller which is FacebookCpsController.php
<?php
App::uses(
'Controller'
,
'Controller'
);
App::import(
'Vendor'
,
'Facebook'
,
array
(
'file'
=>
'Facebook'
.DS.
'facebook.php'
));
class
FacebookCpsController
extends
AppController {
public
$name
=
'FacebookCps'
;
public
$uses
=
array
();
public
function
index(){
$this
->layout=false;
}
function
login()
{
Configure::load(
'facebook'
);
$appId
=Configure::read(
'Facebook.appId'
);
$app_secret
=Configure::read(
'Facebook.secret'
);
=
new
Facebook(
array
(
'appId'
=>
$appId
,
'secret'
=>
$app_secret
,
));
$loginUrl
=
->getLoginUrl(
array
(
'scope'
=>
'email,read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos'
,
'redirect_uri'
=> BASE_URL.
'facebook_cps/facebook_connect'
,
'display'
=>
'popup'
));
$this
->redirect(
$loginUrl
);
}
function
facebook_connect()
{
Configure::load(
'facebook'
);
$appId
=Configure::read(
'Facebook.appId'
);
$app_secret
=Configure::read(
'Facebook.secret'
);
=
new
Facebook(
array
(
'appId'
=>
$appId
,
'secret'
=>
$app_secret
,
));
$user
=
->getUser();
if
(
$user
){
try
{
$user_profile
=
->api(
'/me'
);
$params
=
array
(
'next'
=> BASE_URL.
'facebook_cps/facebook_logout'
);
$logout
=
->getLogoutUrl(
$params
);
$this
->Session->write(
'logout'
,
$logout
);
}
catch
(FacebookApiException
$e
){
error_log
(
$e
);
$user
= NULL;
}
}
else
{
$this
->Session->setFlash(
'Sorry.Please try again'
,
'default'
,
array
(
'class'
=>
'msg_req'
));
$this
->redirect(
array
(
'action'
=>
'index'
));
}
}
function
facebook_logout(){
$this
->Session->
delete
(
'User'
);
$this
->Session->
delete
(
'logout'
);
$this
->redirect(
array
(
'action'
=>
'index'
));
}
}
?>
Here We create two view files for the FacebookCpsController which are located in app/View/FacebookCps directory.
index.ctp
<!--DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<head>
<meta http-equiv=
"Content-Type"
content=
"text/html; charset=utf-8"
/>
<title>Login with Facebook In CakePHP</title>
<?php
echo
$this
->Html->script(
'oauthpopup'
); ?>
<script type=
"text/javascript"
>
$(document).ready(
function
(){
$(
'#facebook'
).click(
function
(e){
$.oauthpopup({
path:
'facebook_cps/login'
,
width:600,
height:300,
callback:
function
(){
window.location.reload();
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<?php
$ses_user
=
$this
->Session->read(
'User'
);
$logout
=
$this
->Session->read(
'logout'
);
if
(!
$this
->Session->check(
'User'
) &&
empty
(
$ses_user
)) {
echo
$this
->Html->image(
'facebook.png'
,
array
(
'id'
=>
'facebook'
,
'style'
=>
'cursor:pointer;float:left;margin-left:550px;'
));
}
else
{
echo
'<img src="https://graph.facebook.com/'
.
$ses_user
[
'id'
] .
'/picture" width="30" height="30"/><div>'
.
$ses_user
[
'name'
].
'</div>'
;
echo
'<a href="'
.
$logout
.
'">Logout</a>'
;
}
?>
</body>
</html>
facebook_connect.ctp
<script type=
"text/javascript"
>
window.close();
</script>
Here I used one jquery plugin oauthpopup.jswhich is used for popup
(this file is located in app/webroot/js directory)
oauthpopup.js
(function (jQuery) {
jQuery.oauthpopup = function (options) {
options.windowName = options.windowName || ‘ConnectWithOAuth’;
options.windowOptions = options.windowOptions || ‘location=0,status=0,width=’+options.width+’,height=’+options.height+’,scrollbars=1′;
options.callback = options.callback || function () {
window.location.reload();
};
var that = this;
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
that._oauthInterval = window.setInterval(function () {
if (that._oauthWindow.closed) {
window.clearInterval(that._oauthInterval);
options.callback();
}
}, 1000);
};
})(jQuery);
In the PHP SDK 3.0,we change the facebook.php file.For the Session We uses the CakePHP core data source which is CakeSession. facebook.php file is located at app/Vendor/Facebook directory
facebook.php
//included this line the above class
App::uses(
'CakeSession'
,
'Model/Datasource'
);
public
function
__construct(
$config
) {
if
(!session_id()) {
//insted of session_start() we used CakeSession::start()
CakeSession::start();
}
parent::__construct(
$config
);
if
(!
empty
(
$config
[
'sharedSession'
])) {
$this
->initSharedSession();
}
}
Payment System with Paypal
I received a tutorial requests from my reader that asked to me how to implement payment gateway system with Paypal API. In this post I want to explain how to work with Paypal Sandbox test accounts for payment system development and sending arguments while click buy now button. It’s simple and very easy to integrate in your web projects.
Sample database design for Payment system. Contains there table users,products and sales.
Users
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(255),
`email` varchar(255) UNIQUE KEY,
)
Products
(
`pid` int(11) AUTO_INCREMENT PRIMARY KEY,
`product` varchar(255),
‘product_img` varchar(100),
`price` int(11),
`currency` varchar(10),
)
Sales
(
`sid` int(11) AUTO_INCREMENT PRIMARY KEY,
`pid` int(11),
`uid` int(11),
`saledate` date,
`transactionid` varchar(125),
FOREIGN KEY(uid) REFERENCES users(uid),
FOREIGN KEY(pid) REFERENCES products(pid)
)
Create a Paypal Sandbox account at https://developer.paypal.com/
Now create test accounts for payment system. Take a look at Sandbox menu left-side top Sandbox->Test Accounts
Here I have created two accounts Buyer (personal) and Seller(merchant/business)
products.php
Contains PHP code. Displaying records from products table product image,product name and product price. Here you have to give your business(seller)$paypal_id id. Modify paypal button form return and cancel_return URLs.
<?php
session_start();
require ‘db_config.php’;
$uid=$_SESSION[‘uid’];
$username=$_SESSION[‘username’];
$paypal_url=’https://www.sandbox.paypal.com/cgi-bin/webscr‘; // Test Paypal API URL
$paypal_id=’your_seller_id‘; // Business email ID
?>
<body>
<h2>Welcome, <?php echo $username;?></h2>
<?php
$result = mysql_query(“SELECT * from products”);
while($row = mysql_fetch_array($result))
{
?>
<img src=”images/<?php echo $row[‘product_img’];?>” />
Name: <?php echo $row[‘product’];?>
Price: <?php echo $row[‘price’];?>$
// Paypal Button
<form action=’<?php echo $paypal_url; ?>‘ method=’post’ name=’form<?php echo $row[‘pid’]; ?>’>
<input type=’hidden’ name=’business’ value=’<?php echo $paypal_id; ?>‘>
<input type=’hidden’ name=’cmd’ value=’_xclick’>
<input type=’hidden’ name=’item_name’ value=’<?php echo$row[‘product’];?>‘>
<input type=’hidden’ name=’item_number’ value=’<?php echo$row[‘pid’];?>‘>
<input type=’hidden’ name=’amount’ value=’<?php echo $row[‘price’];?>‘>
<input type=’hidden’ name=’no_shipping’ value=’1′>
<input type=’hidden’ name=’currency_code’ value=’USD‘>
<input type=’hidden’ name=’cancel_return‘ value=’http://yoursite.com/cancel.php’>
<input type=’hidden’ name=’return‘ value=’http://yoursite.com/success.php’>
<input type=”image” src=”https://paypal.com/en_US/i/btn/btn_buynowCC_LG.gif” name=”submit”>
</form>
<?php
}
?>
</body>
success.php
Paypal payment success return file. Getting Paypal argument like item_number. Paypal data success.php?tx=270233304D340491B&st=Completed&amt=22.00&cc=USD&cm=&item_number=1
session_start();
require ‘db_config.php’;
$uid = $_SESSION[‘uid’];
$username=$_SESSION[‘username’];
$item_no = $_GET[‘item_number’];
$item_transaction = $_GET[‘tx’]; // Paypal transaction ID
$item_price = $_GET[‘amt’]; // Paypal received amount
$item_currency = $_GET[‘cc’]; // Paypal received currency type//Getting product details
$sql=mysql_query(“select product,price,currency from producst where pid=’$item_no'”);
$row=mysql_fetch_array($sql);
$price=$row[‘price’];
$currency=$row[‘currency’];//Rechecking the product price and currency details
if($item_price==$price && item_currency==$currency)
{
$result = mysql_query(“INSERT INTO sales(pid, uid, saledate,transactionid) VALUES(‘$item_no’, ‘$uid’, NOW(),’$item_transaction’)”);
if($result)
{
echo “<h1>Welcome, $username</h1>”;
echo “<h1>Payment Successful</h1>”;
}
}
else
{
echo “Payment Failed”;
}
?>
PHP Innovation Award Winner of 2012
The PHP Programming Innovation Award Winner of 2012 was announced. An interview with the winner, Karl Holz from Canada, was one of the main topics of the episode 33 of the Lately in PHP podcast conducted by Manuel Lemos and Ernani Joppert.
They also discussed the usual batch of PHP topics of interest like Zend Optimizer+ source code that was released, the PHP 5.5 feature freeze and roadmap, as well an article that compares PHP to an Hobbit, as well other languages to Lord Of The Rings story characters.
Listen to the podcast, or watch the podcast video, or read the transcript to learn about these and other interesting PHP topics.
Export html to ms excel file in php
In this article,I will explain how to export html to excel(.xls) file. we are going to export an HTML table (or any html data) to a MS Excel document as it is displayed on the HTML page.
it is very easy to export HTML data to excel in PHP. Lets see Below code
<!–?php
if(isset($_POST[‘excel’]) && $_POST[‘excel’])
{
# Download Excel (.xls) File…
header(‘Content-Type: application/force-download’);
header(‘Content-disposition: attachment; filename=ExportHtmlToExcel.xls’);
header(“Pragma: “);
header(“Cache-Control: “);
echo $_POST[‘excel’];
exit();
}
?>
<html>
<head>
<script>
function getHtmlData()
{
$(“#excel”).val(‘<table border=”1″>’+$(“#info”).clone().html()+'</table>’);
return true;
}
</script>
</head>
<title>Export HTML to Excel in PHP</title>
// <![CDATA[
src=’http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js’>
// ]]>
</head>
<body>
<form method=”post” onSubmit=”javascript:return getHtmlData()”>
<table border=”1″ id=”info”>
<tr>
<th>First Name : </th>
</tr>
<tr>
Test First Name
<td>Test Last Name</td>
</tr>
</table>
<input type=”hidden” id=”excel” name=”excel” value=””>
<br><br>
<input type=”submit” value=”Export HTML to Excel”>
</form>
</body>
</html>
PHP Image and Audio Upload Function
Function in PHP to upload an image and audio to the MYSQL database and move the uploaded file:
//fileUpload(“location of file”,”table”,”file_name_in_table”,”condition1″,”condition2″,”file type”)
function fileUpload($location,$table,$name,$condition1,$condition2,$T) { //image upload if($T == “I”) : $new_name = time(). “-”. $_FILES["image"]["name"] ; $target = $location. $new_name ; if ((($_FILES["image"]["type"] == “image/gif”) ||
($_FILES["image"]["type"] == “image/png”) ||
($_FILES["image"]["type"] == “image/jpeg”) ||
($_FILES["image"]["type"] == “image/pjpeg”))) { $err = 0; } else { $err = 2; $_SESSION['errorMessage'] = “Invalid file format!!”; } if (file_exists($target)) { $err = 1; $_SESSION['errorMessage'] =
“Filename already exists!!”; } if($err!= 1 && $err!=2) { move_uploaded_file($_FILES["image"]["tmp_name"], $target); mysql_query(“UPDATE $table SET $name = ‘$new_name’ WHERE
$condition1=’$condition2′ “) or die(‘Upload error’.mysql_error()); $_SESSION['addMessage'] = “Action succesfully!!”; } endif; //audio upload if($T== “A”) : $new_name = time(). “-”. $_FILES["audio"]["name"] ; $target = $location. $new_name ; if ((($_FILES["audio"]["type"] == “image/gif”) ||
($_FILES["audio"]["type"] == “image/png”) ||
($_FILES["audio"]["type"] == “image/jpeg”) ||
($_FILES["audio"]["type"] == “image/pjpeg”))) { $err = 0; } else { $err = 2; $_SESSION['errorMessage'] = “Invalid file format!!”; } if (file_exists($target)) { $err = 1;
$_SESSION['errorMessage'] = “Filename already exists!!”; } if($err!= 1 && $err!=2) { move_uploaded_file($_FILES["audio"]["tmp_name"], $target); mysql_query(“UPDATE $table SET $name = ‘$new_name’
WHERE $condition1=’$condition2′ “) or die(‘Upload error’.mysql_error()); } endif; }
Upload Cover Photo to Facebook via PHP
Here is a tutorial to upload a Cover Photo on Facebook via PHP. We will need Facebook Application ID and Secret, and Facebook files from Github.com then upload to your web space only the src folder. Now create a file called upload.php and upload it to your web space. Open upload.php with notepad and add this code:
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require 'src/facebook.php'; $facebook = new Facebook(array( 'appId' => "xxxxxxxxxxxxxxxxxxx", //Facebook App ID 'secret' => "xxxxxxxxxxxxxxxxxxx", // Facebook App Secret "cookie" => true, 'fileUpload' => true )); $user_id = $facebook->getUser(); if($user_id == 0 || $user_id == "") { $login_url = $facebook->getLoginUrl(array( 'redirect_uri' => 'https://selvabalaji.wordpress.com/upload.php?cover='.$_GET['cover'].'', // Replace with your site url 'scope' => "publish_stream,user_photos")); echo "<script type='text/javascript'>top.location.href = '$login_url';</script>"; exit(); } //get user album $albums = $facebook->api("/me/albums"); $album_id = ""; foreach($albums["data"] as $item){ if($item["type"] == "cover_photo"){ $album_id = $item["id"]; break; } } //set timeline cover atributes $full_image_path = realpath($_GET['cover']); $args = array('message' => 'Uploaded from hhttps://selvabalaji.wordpress.com/'); $args['image'] = '@' . $full_image_path; //upload cover photo to Facebook $data = $facebook->api("/me/photos", 'post', $args); $picture = $facebook->api('/'.$data['id']); $fb_image_link = 'http://www.facebook.com/profile.php?preview_cover='.$data['id'].''; //redirect to uploaded facebook cover and change it echo "<script type='text/javascript'>top.location.href = '$fb_image_link';</script>"; ?>
Now that just type in the URL of your site followed by the name of the image file and you’re done!
Example : http://yoursitename.com/upload.php?cover=selvabalaji.gif
This article teaches you how to create pagination like twitter using jquery, PHP and MySQL. The content can be loaded at the end of old content when we scroll the page. Your can create your own pagination after completing this article. It is very easy to implement, you can just copy and paste the code. Please follow the steps given below to create your won pagination style.
1. Create table in MySQL using following query statement
CREATE TABLE IF NOT EXISTS `job` ( `job_id` INT(11) NOT NULL AUTO_INCREMENT, `job_name` INT(11) NOT NULL, PRIMARY KEY (`job_id`) ) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
2. Create database connection file ie connection.php
$DB_Username = "root"; $DB_Password = ""; $DB_DATABASE = "database_name"; $DB_HOST = "localhost"; $Connect = @mysql_connect($DB_HOST, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL: " . mysql_error() . " " . mysql_errno()); //select database $Db = @mysql_select_db($DB_DATABASE, $Connect) or die("Couldn't select database: " . mysql_error(). " " . mysql_errno());
3. Create index.php where you can write following codes
<?php
/*
Author: selvaBalaji
Email:selvabalaji@gmail.com
Date: oct 26 2012
*/
include(“connection.php”);
if(isset($_GET[‘lastID’]) && is_numeric($_GET[‘lastID’]))
$lastID =intval($_GET[‘lastID’]);
if(!isset($_GET[‘lastID’]))
{
?>
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js”>
</script>
<style>
#loader {
border:1px solid #ccc;
padding:10px;
margin:10px 0 0 0;
text-align:center;
}
.contentpane{}
.rowHolder{
border:1px solid #ccc;
padding:10px;
margin:10px 0 0 0;
}
</style>
<script type=”text/javascript”>
$(document).ready(function(){
function lastRecord()
{
$(‘div#loader’).html(‘<img src=”loader.gif” alt=”Loading…”>’);
$.post(“index.php?lastID=”+$(“.contentpane table tr:last”).attr(“id”),
function(data){
if (data != “”) {
$(“.contentpane table tr:last”).after(data);
}
$(‘div#loader’).empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() – $(window).height()){
lastRecord();
}
});});
</script>
</head>
<body>
<h1>Pagination </h1>
<p class=”hr” style=”padding:2px 0 2px 0;”></p>
<div class=”contentpane”>
<table width=”100%” border=”0″ cellpadding=”0″ cellspacing=”0″>
<?php
$sql=”SELECT * FROM job ORDER BY job_id DESC limit 30″;
$result = mysql_query($sql);
while($record = mysql_fetch_array($result))
{
$lastID = $record[‘job_id’];
?>
<tr id=”<?php echo $record[‘job_id’];?>”>
<td><div class=”rowHolder”><?php echo $record[‘job_name’];?></div></td>
</tr>
<?php
}
?>
</table>
</div>
<div id=”loader”></div>
</body>
</html>
<?php
}
else
{
$sql=”SELECT * FROM job WHERE job_id < $lastID
ORDER BY job_id DESC LIMIT 3″;
$result = mysql_query($sql);
while($record = mysql_fetch_array($result))
{
?>
<tr id=”<?php echo $record[‘job_id’];?>”>
<td><div class=”rowHolder”><?php echo $record[‘job_name’];?></div></td>
</tr>
<?php
}
}
?>
Login with Google Account OAuth
Sample database design
(
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) UNIQUE,
fullname VARCHAR(100),
firstname VARCHAR(50),
lastname VARCHAR(50),
google_id VARCHAR(50),
gender VARCHAR(10),
dob VARCHAR(15),
profile_image TEXT,
gpluslink TEXT
)
Verify your domain ownership with HTML file upload or including META tag.
Google will provide you OAuth consumer key and OAuth consumer secret key.
Create client ID OAuth Console here.
Create client ID.
Here the application OAuth client ID and client secret.
You can find this in srcfolder, here you have to configure application OAuth keys, Consumer keys and redirection callback URL.
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console Step 6 keys ‘oauth2_client_id’ => ‘App Client ID’, ‘oauth2_client_secret’ => ‘App Client Secret’,’oauth2_redirect_uri’ => ‘http://yoursite.com/gplus/index.php’,// OAuth1 Settings Step 3 keys.
‘oauth_consumer_key’ => ‘OAuth Consumer Key’,
‘oauth_consumer_secret’ => ‘OAuth Consumer Secret’,
google_login.php
Google plus login system. Just include the file in index.php
<?php require_once ‘src/apiClient.php’; require_once ‘src/contrib/apiOauth2Service.php’; session_start(); $client = new apiClient(); setApplicationName(“Google Account Login”); $oauth2 = new apiOauth2Service($client); if (isset($_GET[‘code’])) { $client->authenticate(); $_SESSION[‘token’] = $client->getAccessToken(); $redirect = ‘http://’ . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘PHP_SELF’]; header(‘Location: ‘ . filter_var($redirect, FILTER_SANITIZE_URL));}if (isset($_SESSION[‘token’])) {
$client->setAccessToken($_SESSION[‘token’]);
}if (isset($_REQUEST[‘logout’])) {
unset($_SESSION[‘token’]);
unset($_SESSION[‘google_data’]); //Google session data unset
$client->revokeToken();
}if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$_SESSION[‘google_data’]=$user; // Storing Google User Data in Session
header(“location: home.php”);
$_SESSION[‘token’] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}if(isset($personMarkup)):
print $personMarkup;
endifif(isset($authUrl))
{
echo “<a href=”$authUrl”>Google Account Login</a>”;
} else {
echo “Logout“;
}
?>
home.php
Contains PHP code inserting Google plus session details into users table.
<?php
session_start();
include(‘db.php’); //Database Connection.
if (!isset($_SESSION[‘google_data’])) {
// Redirection to application home page.
header(“location: index.php”);
}
else
{
//echo print_r($userdata);
$userdata=$_SESSION[‘google_data’];
$email =$userdata[’email’];
$googleid =$userdata[‘id’];
$fullName =$userdata[‘name’];
$firstName=$userdata[‘given_name’];
$lastName=$userdata[‘family_name’];
$gplusURL=$userdata[‘link’];
$avatar=$userdata[‘picture’];
$gender=$userdata[‘gender’];
$dob=$userdata[‘birthday’];
//Execture query
$sql=mysql_query(“insert into users(email,fullname,firstname,lastname,google_id,gender,dob,profile_image,gpluslink) values(‘$email’,’$fullName’,’$firstName’,’$lastName’,’$googleid’,’$gender’,’$dob’,’$avatar’,’$gplusURL’)”);
?>db.php
Database Configuration file.<?php
$mysql_hostname = “localhost”;
$mysql_user = “username”;
$mysql_password = “password”;
$mysql_database = “databasename”;
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die(“Could not connect database”);
mysql_select_db($mysql_database, $bd) or die(“Could not select database”);
?>
Related articles
- PHP OAuth API (phpclasses.org)
- basic_oauth 0.1.5 (pypi.python.org)
- How to store sensitive userdata in mysql using php (stackoverflow.com)
Recent Comments