PHP

Export To CSV File – PHP


CSV is a simple file format that is widely used by IT Professional, business, and all who are familar with computer. Those who use computer in day to day life, they know how to use CSV/Excel. Among its most common uses is to move tabular data between programs that naturally operate on a more efficient or complete proprietary format. This file is easily readable even in mobile with use of some basic apps.

In Web Technology fileld,  number of times we have the send Stats, Logs and detail to our client in Form of CSV files.  Event may times we got the Text in form of excel/CSV Fle.
Now, Export the PHP data into CSV is very simple. Just  you need to do few simple steps.
  1. Save into into PHP multidimensional array
  2. Set the header
  3. Now, render the rows and then render EOL (First Row)
  4. Now, render the rows and then render EOL (Second Row)
  5. Now, render the rows and then render EOL  (Third Row and so on)
 Here EOL is End of Line.

$lists = array(
    array(
        'Web', 'Technology', 'Experts', 'Notes',
    ),
    array(
        'Web1', 'Technology1', 'Experts1', 'Notes1',
    ),
    array(
        'Web2', 'Technology2', 'Experts2', 'Notes2'
    ),
    array(
        'Web3', 'Technology3', 'Experts3', 'Notes3',
    ),
    array(
        'Web4', 'Technology4', 'Experts4', 'Notes4',
    ),
    array(
        'Web5', 'Technology6', 'Experts5', 'Notes5',
    )
);

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv.csv");
header("Pragma: no-cache");
header("Expires: 0");

//header
echo  "Title1, Title2,Title3, Title4 \n";

foreach ($lists as $list) {
    echo implode(',', $list);
    echo PHP_EOL;
}
Advertisements

Redirection


In previous articular we have discus Migrate site from ASP to WordPress

After successfully migration your ASP site to WordPress it’s important to maintain redirection. Because If you have an old url ranking is good in Google and move to a new, permanent location, a 301 redirect can pass the search engine ranking score of the old ranking URL (not abruptly; it will take time) to the new URL. Hence the new URL will appear and start to rank in the search engine results, replacing the old URL.

Before discuss on this topic need to know about Permalink

Permalink means “Permanent Link”. It is a unique URL for each article on your blog. Even if you publish two posts with the same title, they get different permalinks.

A permalink is generated when you hit the publish button for a post or page. It remains the same after publishing, even if you make changes to the title. That is why it is called a permanent link!

On the Internet, a permalink represents a unique address for each of your blog posts and other stuff. So if a permalink breaks, your visitors will be lost.

Similarly on the Internet, if a permalink breaks, the visitors coming from search engines, social media, bookmarks, backlinks from others posts will be lost.

 

Maintaining Permalinks

Try to set your permalink to similar to your old site url.

 

As you know by now, when you move your site from (ASP) to WordPress, permalink structure gets altered. you can use some WordPress plugin for redirection.

But there are Few known limitations of redirecting permalinks are:

  • Facebook/Twitter count will reset for sure. New permalink will have all zeros.
  • Google pagerank for new permalink will be zero. New permalink may gain Google pagerank over the time but big risk.
  • Human visitors will notice delay in opening your posts on WordPress. Delay will be obvious if they are using slow Internet connection.

If you do not take any extra effort to use to maintain permalink and redirection then you will loose traffic, ranking and of-course Google AdSense revenue from your blog.

Google pagerank can be retained if you maintain permalink and redirection.

 

Improve Ajax Performance


Following are few steps to Improve Ajax Performance

  1. First try to Reduce the Number of Ajax Call
  2. If same call send again, abort the previous call
  3. If ajax call is executing, and user go for another link, then cancel the previous one.
  4. Use GET Method, As its Fast but less secure
  5. Reduce the Amount of data transmitted
    a. Only Required parameter in Ajax Request
    b. Only Required Response in Ajax Request
  6. Optimize your Server

How To Fix Headers Already Sent Error In PHP?


We are here to fix below error in PHP
Warning: Cannot modify header information – headers already sent by (output started at E:\wamp\www\testp\public_html\test.php:2) in E:\wamp\www\testp\public_html\test.php on line 4

Question: Why this Error comes? This error comes when sending header after the output.
OR
using “header” function after the output.

Question: Give an example when this error comes?

echo "arun";
header("Location: next.php");

Question: How to fix this error?
When you are using header function to send header, make sure you have not any output before. In another words, header function must be called first in any script(if applicable). you can not send header after the output. For Example: below will work 
header("Location: next.php");
echo "arun";
Question: Is there any another way to fix this error?
Yes, you need to set the output_buffering "on" (By default it is off)


Question: How to set output_buffering on in PHP?
ini_set('output_buffering','On');

Question: How to set output_buffering on in php.ini?
output_buffering = Off
replace with
output_buffering = On

Question: How to set output_buffering on in htaccess?
open you .htacces file and add following code.
  php_value output_buffering On

REST API


Representational state transfer (REST) is the software architectural style of the World Wide Web.It relies on a stateless, client-server, cacheable communications protocol — and in virtually all cases, the HTTP protocol is used.

REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls) and Web Services (SOAP, WSDL, et al.).

Despite being simple, REST is fully-featured; there’s basically nothing you can do in Web Services that can’t be done with a RESTful architecture. REST is not a “standard”. There will never be a W3C recommendataion for REST, for example. And while there are REST programming frameworks, working with REST is so simple that you can often “roll your own” with standard library features in languages like PHP, Perl, Java, or C#.
REST was defined by Roy Thomas Fielding in his 2000 PhD dissertation “Architectural Styles and the Design of Network-based Software Architectures”.
REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.

An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource, and the required fields. The browser doesn’t know in advance where to submit the information, and it doesn’t know in advance what information to submit. Both forms of information are entirely supplied by the server.

So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.resources being manipulated using a common set of verbs: HTTP methods are the commonly seen case – the venerable Create, Retrieve, Update, Delete becomes POST, GET, PUT, and DELETE

For example, Let’s imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetypeapplication/json+userdb (There might also be an application/xml+userdb andapplication/whatever+userdb – many media types may be supported). The client and the server has both been programmed to understand this format, but they don’t know anything about each other.

The REST API lets you interact with Parse from anything that can send an HTTP request. There are many things you can do with the REST API. For example:

  • A mobile website can access Parse data from JavaScript.
  • A webserver can show data from Parse on a website.
  • You can upload large amounts of data that will later be consumed in a mobile app.
  • You can download recent data to run your own custom analytics.
  • Applications written in any programming language can interact with data on Parse.
  • You can export all of your data if you no longer want to use Parse.

Cloud Computing (Salesforce) and Salesforce Integration with PHP


Cloud computing is Internet-based computing, whereby shared resources, software, and information are provided to computers and other devices on demand, like the electricity grid.

Cloud computing is the use of computing resources (hardware and software) that are delivered as a service over a network (typically the Internet).

As a metaphor for the Internet, “the cloud” is a familiar cliché, but when combined with “computing,” the meaning gets bigger and fuzzier.

Some analysts and vendors define cloud computing narrowly as an updated version of utility computing: Basically virtual servers available over the Internet.

Benefits of Cloud

  • Lower Costs – Cost savings that come with economy of scale
  • Scale as Needed – As your applications grow, you can add storage, RAM and CPU capacity as needed.
  • Cap-Ex Free Computing cash flow by eliminating the capital expense associated with building the server infrastructure
  • Deploy Projects Faster – Because servers can be brought up & destroyed in a matter of minutes.
  • Lower Maintenance Costs driven by 2 factors: Less hardware and outsourced, shared IT staff.
  • Resiliency and Redundancy –you can get automatic failover between hardware platforms and disaster recovery services
  • Guaranteed “up time“
  • Software upgrades are provided with no cost and avoids obsolescence
  • More available Capital to promote business growth

Cloud service models

cloud

Cloud Service Available

The Cloud fits into a broad categorization of service offerings split out into,

Infrastructure as a Service (e.g. Amazon EC2 and Rackspace),

Platform as a Service (e.g. App Engine)

Platform as a service (PaaS) is a category of cloud computing services that provides a computing platform and a solution stack as a service. The provider provides the networks, servers, storage, and other services that are required to host the consumer’s application

Software as a Service (e.g. Salesforce.com).

Software as a service (SaaS) is a software distribution model in which applications are hosted by a vendor or service provider and made available to customers over a network, typically the Internet.

cloud_services

The Fear of Cloud

  •   72% cited Security concernscloud_use_graph
  •    34% selected Integration issues
  •    14% cited TCO
  •     8% none of the above

 

Security of customer data has been the #1 priority of Saas companies today.

They maintain the highest security standards at three levels: Application Security, Facilities security & Network securitysalesforce

Salesforce

Salesforce.com is the Enterprise Cloud Computing Company.

  • Salesforce is originally a Customer Relationship Management (CRM) software.
  • CRM is originally software for managing customer interaction, such as scheduling tasks, emailing, texting, and many more tasks.
  • Salesforce grew into a cloud software solution and acquired several other companies for Paas and Saas.

Salesforce is also 3-tier, but many of the internals are handled through abstraction. There are:

1) Out-of-box interfaces, which include security, dashboards, workflow, and user interfaces. Coding is optional.

2) VisualForce is an editor for customization of User Interfaces if not out-of-box.

Visualforce is a framework that allows developers to build sophisticated, custom user interfaces that can be hosted natively on the Force.com platform. The Visualforce framework includes a tag-based markup language, similar to HTML, and a set of server-side “standard controllers” that make basic database operations, such as queries and saves, very simple to perform.

3) Apex, using the developer console, is for writing code to the Salesforce API, for example a SOAP or batch application for importing custom data.

Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java and acts like database stored procedures, Apex enables developers to add business logic.

Salesforce in Business

Salesforce in Business

Salesforce Offers

Sales Cloud 2Sales Cloud 2 :  

The world’s #1 sales application

Give reps, managers and execs everything they need to focus on what’s important: more selling and less administration.

  • Close more deals — faster
  • Gain real-time visibility into sales
  • Collaborate instantly and know what matters

 

Service Cloud 2Service Cloud 2 : 

The future of customer service

Provide faster, more responsive service across every channel — from the call center to the social Web.

With the Service Cloud 2, you can:

  • Keep agents productive
  • Reduce service costs
  • Satisfy every customer

 

ChatterChatter :  

The real-time Collaboration Cloud

Chatter is a brand-new way to collaborate with people at work. Where the status of important projects and deals are automatically pushed to you — so you’re always in the loop.

  • Share securely and collaborate instantly
  • Stay on top of what matters most
  • Gain insight and make smarter decisions

 

Force.comForce.com : 

The leading cloud platform for business apps

Give developers a platform to create rich, collaborative cloud apps fast—without buying hardware or installing software.

  • Build apps 5 times faster, at 1/2 the cost
  • Deploy apps easily to anyone, anywhere
  • Make apps instantly collaborative and mobile

Salesforce Integration with PHP

  • Web Services API
  • PHP Toolkit

We can easily access the salesforce objects, fields & data using below is the basic steps to Integration Between Salesforce and PHP.
STEP 1:
Salesforce providing support to PHP and delivered the PHP Toolkit. Using this toolkit we can connect with salesforce and perform all API operations supported like Insert, Update, Delete, Retrieve the data and much more.

STEP 2:
Salesforce PHP Toolkit Requires is,
PHP 5.x
SOAP Enabled
SSL Enabled
cURL Enabled
OpenSSL Enabled

STEP 3:
Download the latest PHP toolkit using below URL

PHP Toolkit: http://wiki.developerforce.com/page/Force.com_Toolkit_for_PHP
unzip the folder(soapclient Folder) and paste it in your PHP Htdocs Folder (Ex: PHP Project Folder Name is “PHP_SFDC”)

STEP 4:
The WSDL file can be downloaded from wihin your SALESFORCE Org. Once you login to Salesforce, go to Setup > App Setup > Develop > API and then you can generate a Partner WSDL or Enterprise WSDL file from there and and save it to your PHP Project Folder(www/Htdocs/PHP_SFDC/partner.wsdl)

STEP 5:
In PHP Project Folder (PHP_SFDC), Create a new File called getRecord.php file and save it to www/Htdocs/PHP_SFDC/getRecord.php path

add the following lines to getRecord.php file

Retriving the Salesforce Contact Record using PHP
<?php
ini_set("soap.wsdl_cache_enabled", "0");
// PHP Tool Kit class scripts to login to Salesforce Org
require_once ('../includes/soapclient/SforcePartnerClient.php');
require_once ('../includes/soapclient/SforceHeaderOptions.php');
// Salesforce Login information
$wsdl = 'partner.wsdl.xml';    // PARTNER WSDL FILE PATH
$userName = "salesforce username";
$password = "salesforce password"; // PASSWORD SHOULD BE COMBINATION OF "PASSWORD + SECURITY TOKEN", if it's a Developer ORG.
// Process of logging on and getting a salesforce.com session
$client = new SforcePartnerClient();
$client->createConnection($wsdl);
$loginResult = $client->login($userName, $password);
//Then perform to get your Contact records from Your Salesforce ORG
$query = "SELECT Id, FirstName, LastName, Phone from Contact";
$response = $loginResult->query($query);
foreach ($response->records as $record)
{
echo '<tr>
<td>'.$record->Id.'</td>
<td>'.$record->fields->FirstName.'</td>
<td>'.$record->fields->LastName.'</td>
<td>'.$record->fields->Phone.'</td>
</tr>';
}
?>

Secure your WordPress Plugin : CSRF protection


I fixed this vulnerability in my WordPress ‘WP Database Backup‘ plugins and would like to share the same knowledge to other developers.

Lest you think this security stuff isn’t important, a major vulnerability was recently found in the WordPress plugins, which is installed on many WordPress sites and which allowed hackers to manipulate the WordPress database using CSRF(Cross-Site Request Forgery).

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.

How to Prevent CSRF

We can stop CSRF attacks by using some handy functionality built into WordPress.

  1. A nonce is generated.
  2. That nonce is submitted with the form.
  3. On the back end, the nonce is checked for validity. If valid, the action continues. If invalid, everything halts – the request was probably forged (You verify the nonce before doing anything else).

The nonce field is used to validate that the contents of the form request came from the current site and not somewhere else. A nonce does not offer absolute protection, but should protect against most cases. It is very important to use nonce fields in forms.

Let’s Add a Nonce

1.First create nonce using wp_create_nonce  function and pass it along with your request.

<input name=”wpdbbackup_update_setting” type=”hidden” value=”<?php echo wp_create_nonce(‘wpdbbackup-update-setting’); ?>” />

2.Verify nonce using wp_verify_nonce function.

if (!isset($_POST[‘wpdbbackup_update_setting’]))
die(“<br><br>Invalid form data. form request came from the somewhere else not current site! “);
if (!wp_verify_nonce($_POST[‘wpdbbackup_update_setting’],’wpdbbackup-update-setting’))
die(“<br><br>Invalid form data. form request came from the somewhere else not current site! “);

Using nonces you can stop forgery, and foil hackers!

Cron job fail to include files


If you select php as the command language for your cron job, relative paths may not work. This is because some PHP scripts expect to be run from the directory where they are stored, and due to the nature of our Sites platform they will be run from another location. This means including or requiring files from a relative path may result in errors such as:

 PHP Warning: include(../dbconnection.php): failed to open stream: No such file or directory
Solution

To correct this problem, you could use the absolute path to reference any files in your script. An absolute include looks something like this:

include('/var/www/html/dbconnection.php');

Disable WordPress Admin Bar


 Disable WordPress Admin Bar for All Users Except Admin

if you want Disable WordPress Admin Bar for All Users Except Admin then Paste following code in your theme’s functions.php file

add_action('after_setup_theme', 'remove_admin_bar');
 function remove_admin_bar() { 
if (!current_user_can('administrator') && !is_admin()) 
{ show_admin_bar(false); } }

Disable Admin Bar for All Users

If you want to disable Admin Bar for all users, then past following code in your theme’s functions.php file

 show_admin_bar(false);

Disable Admin Bar for certain role

Use this if you want this only for a certain role

function remove_admin_bar() {
$user = wp_get_current_user();
if (in_array('subscriber', $user->roles)) {
show_admin_bar(false);
}
}

Backing up your WordPress database


Your database contains all your important information if the database is erased or corrupted you lose everything.

Sometimes accident can happen when we least expert it. If you can have made a careless mistake and your database is gone how can you restore your data in your database?

So Backup your database regularly.

The WordPress backup files contain sensitive data, such as the WordPress administrator credentials. Such files should be stored in a secure location where other users do not have access to. You can also compress the WordPress backups into a password protected zip file so in case someone manages to get a copy of your WordPress backup files, he or she would need a password to access the content.

WordPress Database backup

Backup your WordPress database from CPanel

  1. Login to your hosting provider CPanel and click on the Backup icon in the Files section.
  2. Once in the backup options page, click on the WordPress database name listed under the section ‘Download a MySQL Database backup’.
  3. Once you click on the WordPress database name, a compressed SQL script file is automatically downloaded to your computer.

Store the WordPress database file in a secure place and ideally it should be stored on a different media.

Backup WordPress database using MySQL command line

If you host your own web server and have access to it via SSH or other protocol, you can make a database backup using a MySQL standard tool called mysqldump. As the name implies, the mysqldump tool dumps a MySQL database into a text file which can later be used to restore the WordPress database.

In the below example, we are using the MySQL root user to connect to the MySQL server, selecting the wpdatabase database and exporting it to a text file called wpdb_backup.sql.

Mysqldump –u root –p wpdatabasebk > wpdb_backup.sql

Below is a breakdown of the switches and parameters used in the command:

-u is used to specify the username to connect to the MySQL server.

-p is used to specify a password. If no password is specified in the command line like in the above example, the MySQL server will prompt you to specify the password once you issue the command. For security reasons it is better not to specify the password via command line since it will be stored in the command line history.

Wpdatabasebk is the actual WordPress database name.

> This sign means export. It is used to specify where to export the MySQL server database dump.

Wpdb_backup.sql is the name of the file where the database dump will be stored. If the file does not exist it will be generated by the tool. Once the database is dumped into this file, download it to your computer and store it in a secure location, ideally on a separate media.

Backup WordPress database using phpMyAdmin

phpMyAdmin is a MySQL Server admin web based tool. This can be accessed directly via a specific URL or else from your hosting provider’s CPanel under the Databases section. To backup the WordPress database from the phpMyAdmin follow the below procedure:

  1. Once logged in to phpMyAdmin, depending on your installation you might notice that you have several databases. In that case, select the WordPress database by clicking on it.
  2. Once you select the WordPress database you are redirected to the database options page form where you can launch several database related tasks. As seen in the below screenshot, a list of tables in the database will also be populated. You might have more than 11 tables in your WordPress database, if you have WordPress plugins that store data in the WordPress database.WP-database-backup-phpmyadmin
  3. Click on the Export option (highlighted in the above screenshot) to export/backup the WordPress database to a file. From the Export section, select Custom export and ensure that the below options are selected as highlighted in the below screenshot:
    1. All tables are highlighted.
    2. The option “Add Drop….” from the Object Creation options is enabled. This can be useful in case you are restoring the WordPress database onto an existing one.

Back up your website Using WordPress plugins

There are some limitation in default WordPress installation is backup.The included backup system limits you to exporting posts, pages, comments, custom fields, categories and tags. What you don’t get are backups of directories, files and databases.

There are plenty of plugins available to improve the WordPress database backup solution.

WP Database Backup

If you are use WordPress so you can use backup plugins for take database backup.

If You want to schedule a backup of your WordPress site database but do not have enough permissions to access your host then Install “wp database backup” plug-in.

WP-Database-Backup :When plugin is installed and active. you can backup your blog database easily in single click. Some time you have create database backup on your server or localhost and if some one hack your site or you have made some mistake then how can you recover your database which include important information. So it is important to save your database safer place like FTP, on your Email or Dropbox.

for more information about how to backup database using WP-database-Backup plugin check this link : https://walkeprashant.wordpress.com/wp-database-backup/