Showing posts with label php problem solutions. Show all posts
Showing posts with label php problem solutions. Show all posts

Monday 16 March 2015

How to send an email using Email Template in Zend Framework

How to send an email using Email Template in Zend Framework

Email functionalities in websites is very common and used in mostly in all web application. Whether it is registration process or Order detail, we need to send an email to your valuable client.

To send the email using Email Template follow the following steps
1. First collect all the data which you want to send in Email like first name, last name etc.
$emailTemplateData = array('fname'=>'Web Technology','lname'=>'Experts Notes');


2. Create a Folder with name emails, where you can put the email templates files.
Email template Location: application/views/scripts/emails


3. Create a template with name registration.phtml  for registration Email and add following contents.
First name:  echo $data['fname'];  
Last name:   echo $data['fname'];  
Folder Location: application/views/scripts/emails
Don't forget to add php scripts for php variable
Im just giving you an working code, you can add lot of variables as you need.


Add following code from where you want to send an email
$subject ='This is subject';
$view = new Zend_View();
$view->addScriptPath(APPLICATION_PATH . '/views/scripts/emails');
$view->data = $emailTemplateData; //$emailTemplateData must have the values which you are using in registration.phtml
$emailHtml = $view->render('registration.phtml');
$mail = new Zend_Mail();
$mail->setBodyHtml($emailHtml);
$mail->setSubject($subject);              
$mail->setFrom("support@example.com", "From domain.com");
$mail->send();


If you get an issue regarding this post, Please comment below. we will try to fix your problem.




Tuesday 10 March 2015

How do I get wordpress global variable and functions in custom file [SOLVED]

How do I get wordpress global variable and functions in custom file


Problem:
I have create a file i.e mytestfile.php in root folder of wordpress blog.
Full path of mytestfile.php is http://www.example.com/blog/mytestfile.php.
Now, I want to access all global variables, functions like $wp_query, query_posts.



Solution:
As you have created mytestfile.php in blog root folder.
Just add the following line in top. This will load wordpress blog and you can access global variables.
require( 'wp-load.php' );
global $wp_query;
Now, you can access $wp_query, query_posts.



Saturday 7 March 2015

How to convert php array into javascript array

How to convert php array into javascript array

Converting PHP Array into java-script  array can be done by using json_ecode functions in php.
See, Following how to convert PHP Array into JavaScript Array.
 $phpArray = array(
      'web','web technology','web technology experts', 'web technology experts notes'
      );
      
      echo '<script>';
        echo 'var javaScriptArray ='.json_encode($phpArray);
      echo '</script>'; 



Output:
 
var javaScriptArray =["web","web technology","web technology experts","web technology experts notes"]


Wednesday 25 February 2015

How to store array in Cookie and retrieve array from cookie

How to store array in Cookie and retrieve array from cookie

How to store array in Cookie
We need to json_encode the array then save the data with setcookie function.
$arrayData=array(
    'web technology experts',
    'web technology experts Notes',
    'web technology experts Notes  php technology'    
);
setcookie('cookieData', json_encode($arrayData));


How to Retrieve array in Cookie
As we have encoded the array above, So we need to json_decode the array before use.
$arrayData = json_decode($_COOKIE['cookieData']);


How to set time in cookies
$arrayData=array(
    'web technology experts',
    'web technology experts Notes',
    'web technology experts Notes  php technology'    
);
setcookie('cookieData', json_encode($arrayData), time()+3600);// set time for 1 hour [1 hour=3600 seconds]


 


Sunday 15 February 2015

Synchronous XMLHttpRequest on the main thread is deprecated

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

If you are getting above issue, It means in Ajax call ( May be using xmlHttpRequest, jQuery.js OR prototype.js etc), Somewhere you have set following:
async: false

Never use "async: false", Because it has been deprecated.

async must be true, whether you are using core ajax, jQuery ajax OR prototype ajax etc.



Monday 2 February 2015

Send Email from Gmail SMTP using Zend Framework

Send Email from Gmail SMTP using Zend Framework

In Website we need to send email on Registration, Forget , Order email to our Clients/Customer.
We want email should be deliver timely in inbox folder not in junk/spam folder.
For this we have to use SMTP Server.

GMAIL SMTP Server is free to use, if you have valid Gmail account.

Just the following code to send email from your Gmail Account.
/** Must fill Following detail * */
$yourGmailAccountUsername = 'youremail@gmail.com';
$yourGmailAccountPassword = '********';
$emailTo = 'arun.compute@gmail.com';
$emailToName = 'receiptsName';
/** Must fill Following detail * */

/** Optional Detail * */
$emailBody = 'This is body text';
$emailSubject = 'This is subject';
/** Optional Detail * */

try {
    $config = array('ssl' => 'tls',
        'auth' => 'login',
        'username' => $yourGmailAccountUsername,
        'password' => $yourGmailAccountPassword);

    $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);


    $mail = new Zend_Mail();

    $mail->setBodyHtml($emailBody);
    $mail->setFrom($yourGmailAccountUsername);
    $mail->addTo($emailTo, $emailToName);
    $mail->setSubject($emailSubject);
    if ($mail->send($transport)) {
        echo 'Sent successfully';
    } else {
        echo 'unable to send email';
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

If you get similar to following Error
Please log in via your web browser and then try again.
5.7.14 Please log in via your web browser and then try again. 5.7.14 Learn more at 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 fr13sm3613053pdb.81

If Yes,
whether you have "turned on 2-Step Verification" OR Google need Verification that you want to use your gmail as SMTP credential.
you can fix this in couple of minutes using below link:
https://support.google.com/mail/answer/78754

If any issue, please comment below in comment box:




Friday 30 January 2015

How to display HTML Correctly in Email?

How to display HTML Correctly in Email?

When we send a email to users from web application, many times we see HTML email is distorted in Gmail, Yahoo, Iphone and Ipad etc.

 If you want to removed such type of issue, then keep following points in mind while creating html template. 


  Use tables for layout
<table>
<!--- html code -->
<!--- html code -->
</table>



Set the width in each cell
<table border="0" cellpadding="10" cellspacing="0">
 <tbody>
<tr>
  <td width="50">Sr</td>
  <td width="100">Name</td>
  <td width="100">Email</td>
  <td width="100">Billing Date</td>
 </tr>
</tbody></table>



Use a container table for body background colors
<table border="0" cellpadding="10" cellspacing="0">
<tbody>
<tr>
<td bgcolor="#000000">Background Color </td>
</tr>
</tbody></table>



Avoid unnecessary whitespace and in table
<table border="0" cellpadding="10" cellspacing="0">
<tbody>
<tr>
<td></td>
</tr>
</tbody></table>



Use "nbsp;" for doubly space


Avoid shorthand, use as below
 font-weight: bold;
 font-size: 1em;
 line-height: 1.2em;
 font-family: georgia,serif;


Always use inline CSS
<div style="color: red;">
Inline CSS</div>



Set link color in following way
<a href="http://web-technology-experts-notes.in/" style="color: black;"><span style="color: magenta;">this is a link</span></a>



Images in HTML emails
a. Avoid spacer images
b. Always include the dimensions of your image
c. Avoid PNGs image
d. Always add alt text in image attribute


Never use floats attribute 


Check CSS support in email
https://www.campaignmonitor.com/css/






Wednesday 28 January 2015

How to change the author of a post in Wordpress

How to change the author of a post in Wordpre


There are number of methods to change the author of word-press post and are following.




Method 1: Change Author by manually edit the POST, Follow the simple steps. 
  • Login as Administrator.
  • Go to Posts.
  • Edit the post which's author you want to change.
  • Now you are on edit post.
  • Scroll down till you get "Author List" under "Author".
  • Now select the Author from dropdown/selectbox to whom you want to assign. 
  • See screenshot below

Wordpress how to change the author of a post by manually




Method 2: Change Author by MySQL edit the POST, Follow the simple steps
  • Login to your database.
  • Get the backup of wp_posts table, incase you want to revert back.
  • Get the post_author of author which post you want to assgin another user (Suppose post_author is 28).
  • Get the post_author of author to whom you want to assign.(Suppose post_author is 30).
  • Execute the Following MySQL Query.
  • update wp_posts set post_author="30" where post_author="28"
  • It will change the author of all post from one author (28) to another author (30)


How to clear Facebook image cache

How to clear Facebook image cache

Following are way to clear the facebook's image from cache.
Step 1, Update the Image URL with version in Meta Tags
<meta content="http://www.aboutcity.net/images/web-technology-experts-notes.jpg?v=12" property="og:image"/>

Step 2:
A) Go to https://developers.facebook.com/tools/debug/
B) Enter URL and Press "Debug" Submit button
C) Click On "Show existing scrape information", It will remove the caching
D) Check the updated image


Following is Screenshot which explain, how to clear the Image Cache?

Facebook Open Graph not clearing cache








Tuesday 27 January 2015

Google trends api php - How to get hot trends

Google trends api php - How to get hot trends


Google Trends is a public web facility of Google Inc., based on Google Search, that shows how often a particular search-term is entered relative to the total search-volume across various regions of the world, and in various languages. 
From: en.wikipedia.org/wiki/Google_Trends


Use following code to get the hot trends from google.
  
try {            
            $url='http://www.google.com/trends/hottrends/atom/hourly';                        
            $client = new Zend_Http_Client($url);
            $response = $client->request('GET');
            $jsonData = ($response->getBody());
            echo 'Google Trends';            
            preg_match_all('/(.*)<\/a>/', $jsonData, $trends);
            /** preg_match_all('/(.*)<\/a>/', $jsonData, $trends);**/
             foreach($trends[0] as $trend) {
                echo "{$trend}";
                }

        } catch (Exception $e) {
            echo 'Error' . $e->getMessage();
        }     

Thursday 22 January 2015

How can delete a user without deleting the post and comments in wordpress?

How can delete a user without deleting the post and comments in wordpress?

In this blog, I will expalin how to delete a user/Editor/Subscriber/Author/Administor without deleting the post and comments. When you start deleting the post application will be prompt that you want to assign the post to another user. To keep the user's post, this you have to assign the deleteing user post to another user.


Follow the following simple steps.
1. Login as Administrator (must be not login to whom you are going to delete).
2. Go to User Listing.
3. Click on check box in front of user to whom you want to delete. See below screenshot.
wordpress admin user listing



4. Click on delete icon. It will bring to you new page.
5. Now assign all post to another user/administrator. See below Screenshot.
wordpress admin user delete page

6. Click on "Confirm Deletion". User deleted successfully.

Now deleting the user, same user wouldn't be able to login to system. If he is currently login will logout automatically.





Wednesday 21 January 2015

How to use MySQLi parameterized statements?

How to use MySQLi parameterized statements?

Here I will provide code snippet for the followings
  • How to make Database Connection with PHP-MysQLI.
  • How to fetch the records from database using MysQLI parameterized/prepared statements.
  • How to insert the record in database using MysQLI parameterized/prepared statements.

Create New Table
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `email` varchar(255) NOT NULL,
  `type` char(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 
INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`, `type`) VALUES
(1, 'Micheal', 'Steve', 'micheal@georama.com', 'Guide'),
(2, 'Vt', 'B2B', 'vt@georama.com', 'Guide'),
(5, 'Jana', 'Peter', 'jana@gmail.com', 'Guide'),
(6, 'Ram', 'kumar', 'ramkumar@no-spam.ws', 'Guide');


How to make Database Connection with PHP-MysQLI.
$host = 'localhost';
$user = 'root';
$password = '';
$dbName = 'arun';
$mysqliObj = new mysqli($host, $user, $password, $dbName);
if ($mysqliObj->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqliObj->connect_errno . ") " . $mysqliObj->connect_error;
}



How to fetch the records from database using MysQLI parameterized/prepared statements.
$userType = "Guide";
$stmt = $mysqliObj->prepare("SELECT * FROM users WHERE type = ?");
$stmt->bind_param("i", $userType);
$stmt->execute();
$resObj = $stmt->get_result();
while ($row = $resObj->fetch_assoc()) {
    print_r($row['id']);echo "\n";
}


How to insert the record in database using MysQLI parameterized/prepared statements.
/** Insert into database with mysql * */
//the data
$id = null;
$firstname = "Web";
$lastname = "Technoogy";
$email = "arun.c@no-spam.ws ";
$type = "Guide";

$stmt = $mysqliObj->stmt_init();
if (!($stmt->prepare("INSERT INTO users(first_name, last_name, email,type) VALUES (?,?,?,?)"))) {
    echo "Prepare failed: (" . $mysqliObj->errno . ") " . $mysqliObj->error;
}
$stmt->bind_param("ssss", $firstname, $lastname, $email, $type);
$stmt->execute();
$stmt->close();


Tuesday 20 January 2015

Wordpress redirect https to http with htaccess [SOLVED]

Wordpress redirect https to http with htaccess [SOLVED]

You can redirect all website pages from https to http. It will be redirect only when you open the page with https. 

See Example Below
https://example.com Redirect to http://example.com
https://example.com/page1/ Redirect to http://example.com/page1/
https://example.com/page2/ Redirect to http://example.com/page2/


Open .htaccess in root folder
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Replace with Following code
RewriteEngine On

RewriteCond %{SERVER_PORT} ^443$ [OR]
RewriteCond %{HTTPS} on
RewriteRule  ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Monday 12 January 2015

PHP Technical Interview Questions and Answers for Fresher and Experienced

PHP Technical Interview Questions and Answers for Fresher and Experienced



Question: How to convert string to array in php?
$string="cakephp and zend";
$array =explode('and',$string);
print_r($array);


Question: How to convert array to string in php?
$array = array('cakephp','zend');
$string =implode(' and ',$array);
echo $string;


Question: How to connect mysqli with php using Object-Oriented Way?
$host = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($host, $username, $password);
//connect to server
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";


Question: How to connect mysqli with php using Procedural Way?
$host = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($host, $username, $password);
//connect to server
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";


Question: How to connect mysqli with php using PDO?
$host = "localhost";
$username = "root";
$password = "";
 $conn = new PDO("mysql:host=$host;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";


Question: Give Curl example using post method?
$postData = array(
   "site" => "web technology experts notes",
   "dailyuser" => "1000",
   "location" => "India"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output = curl_exec($ch);
curl_close($ch);
echo $output;




Question: How to destroy one session?
unset($_SESSION['object']);


Question: How to Destroys all data registered to a session?
session_destroy();


Question: How to delete a php file from server?
$file="full_path/filename.php"
unlink($file); //make sure you have enough permission to do delete the file.


Question: How to convert string to uppercase in php?
$string="cakephp and zend";
echo strtoupper($string);


Question: How to convert string to lowercase in php?
$string="CAKEPHP AND ZEND";
echo strtolower($string);


Question: How to convert first letter of string to uppercase in php?
$string="cakephp and zend";
echo ucwords($string);


Question: Difference between array_merge and array_combine in php?
array_merge example
$array1 = array('one','two');
$array2 = array(1,2);
$result = array_merge($array1,$array2);
print_r($result);

array_combine example
$array1 = array('one','two');
$array2 = array(1,2);
$result = array_combine($array1,$array2);
print_r($result);


Question: How to convert array to json in php?
$array = array('one','two');
echo json_encode($array); //use json_decode for decode 


Question: How to serialize an array in php?
$array = array('one','two');
echo serialize($array);//use unserialize for convert serialized string to array


Question: How to get ip address in php?
$_SERVER['REMOTE_ADDR']


Question: How to count the number of elements in an array?
$array = array('cakephp','zend');
sizeof($array);
count($array);


Question: How to call constructor of parent class?
parent::constructor()


Question: What is use of var_dump?
It is used to display the data-type and values of variable. For Example.
$name='WTEN';
var_dump($name);



Question: What is final class
It is class which can not be inherited.
Following are example of final class
final class baseclass{
        public function testmethod()  {
            echo  "base class method";
        }
}


Question: How can we define constants in PHP?
define('WTEN','Web Technology Experts Notes'); //How to define constants
echo WTEN;//How to use constants




Question: How to start displaying errors in PHP application ? Add following code in PHP.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

OR
Add following code in .htacess
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on