How to add ads only at the first post?

It is very simple:

<?php if ($wp_query->current_post == 0) : ?>

<div style=”float:right”>

ads come here.

</div>
<?php endif; ?>

If you don’t want the ads show at homepage, using:

<?php if (!is_home()) ?>

Sending Email (Text/HTML/Attachments)

Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.

So, you want to send automated email messages from your PHP application. This can be in direct response to a user’s action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.

Sending a Simple Text Email
Sending HTML Email
Sending Email with Attachments
Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your php.ini file to point to your email server.

Sending a Simple Text Email

At first let’s consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. The mail() function returns True if the message is sent successfully and False otherwise. Have a look at the example:

<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test email’;
//define the message to be sent. Each line should be separated with \n
$message = “Hello World!\n\nThis is my first mail.”;
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com“;
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed”
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>
As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don’t receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.
Back to top

Sending HTML Email

The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off, they will still get a nice email, even if they don’t get all of the HTML markup. Have a look at the example:

<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test HTML email’;
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date(’r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com“;
//add boundary string and mime type specification
$headers .= “\r\nContent-Type: multipart/alternative; boundary=\”PHP-alt-”.$random_hash.”\”";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
–PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

–PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

–PHP-alt-<?php echo $random_hash; ?>–
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed”
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>
In the preceding example we add one additional header of Content-type:multipart/alternative and boundary string that marks the different areas of the email. Note that the content type of the message itself is sent as a mail header, while the content types of the individual parts of the message are embedded in the message itself. This way, mail clients can decide which part of the message they want to display.

Sending Email with Attachment

The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:

<?php
//define the receiver of the email
$to = ‘youraddress@example.com’;
//define the subject of the email
$subject = ‘Test email with attachment’;
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date(’r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = “From: webmaster@example.com\r\nReply-To: webmaster@example.com“;
//add boundary string and mime type specification
$headers .= “\r\nContent-Type: multipart/mixed; boundary=\”PHP-mixed-”.$random_hash.”\”";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents(’attachment.zip’)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
–PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary=”PHP-alt-<?php echo $random_hash; ?>”

–PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

–PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset=”iso-8859-1″
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

–PHP-alt-<?php echo $random_hash; ?>–

–PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name=”attachment.zip” 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
–PHP-mixed-<?php echo $random_hash; ?>–

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print “Mail sent”. Otherwise print “Mail failed”
echo $mail_sent ? “Mail sent” : “Mail failed”;
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

Blocking access to the login page after three unsuccessful login attempts

Sometimes you need to add an extra protection to password-protected website. This article explains how access to the login page can be restricted after three unsuccessful login attempts. This schema uses visitors IP address to store log attempts in the database and block access to login feature for 30 minutes after third unsuccessful attempt.

There are a number of reasons to restrict access. One reason is security. Quite often users try to guess login and password combination to get unauthorized access to the system. Another reason is extra load on server.

So let’s start. At first you need to create a new table in your database to store information about login attempts from a certain computer. SQL script creating such table in MySQL Server will be the following. For other databases it will slightly differ.

CREATE TABLE `LoginAttempts`
(
`IP` VARCHAR( 20 ) NOT NULL ,
`Attempts` INT NOT NULL ,
`LastLogin` DATETIME NOT NULL
)

It is assumed that you have already had an authorization page. Otherwise you can create it using PHP, SSI, and similar languages. There are no major difficulties in writing this program (script).

Authorization page should work with two tables: one table where information about registered users is stored and the other one where unsuccessful login attempts are listed.
Before verifying entered data, system has to check if the user exceeded attempts limit or not. If in the LoginAttempts table there are more than two records correspondent to one IP address, then error message will appear saying that access is blocked for a certain period of time. You can set time period at your discretion. Depending on your security policy it can vary from 1 minute to 24 hours or more. In the following example access will be blocked for 30 minutes.

 

<?php
function confirmIPAddress($value) {

  $q = “SELECT attempts, (CASE when lastlogin is not NULL and DATE_ADD(LastLogin, INTERVAL “.TIME_PERIOD.
  ” MINUTE)>NOW() then 1 else 0 end) as Denied FROM “.TBL_ATTEMPTS.” WHERE ip = ‘$value’”;

  $result = mysql_query($q, $this->connection);
  $data = mysql_fetch_array($result); 

  //Verify that at least one login attempt is in database

  if (!$data) {
    return 0;
  }
  if ($data[”attempts”] >= ATTEMPTS_NUMBER)
  {
    if($data[”Denied”] == 1)
    {
      return 1;
    }
    else
    { 
      $this->clearLoginAttempts($value);
      return 0; 
    }
  }
  return 0;
}

function addLoginAttempt($value) {

   //Increase number of attempts. Set last login attempt if required.

   $q = “SELECT * FROM “.TBL_ATTEMPTS.” WHERE ip = ‘$value’”;
   $result = mysql_query($q, $this->connection);
   $data = mysql_fetch_array($result);
  
   if($data)
   {
     $attempts = $data[”attempts”]+1;        

     if($attempts==3) {
       $q = “UPDATE “.TBL_ATTEMPTS.” SET attempts=”.$attempts.”, lastlogin=NOW() WHERE ip = ‘$value’”;
       $result = mysql_query($q, $this->connection);
     }
     else {
       $q = “UPDATE “.TBL_ATTEMPTS.” SET attempts=”.$attempts.” WHERE ip = ‘$value’”;
       $result = mysql_query($q, $this->connection);
     }
   }
   else {
     $q = “INSERT INTO “.TBL_ATTEMPTS.” (attempts,IP,lastlogin) values (1, ‘$value’, NOW())”;
     $result = mysql_query($q, $this->connection);
   }
}

function clearLoginAttempts($value) {
  $q = “UPDATE “.TBL_ATTEMPTS.” SET attempts = 0 WHERE ip = ‘$value’”;
  return mysql_query($q, $this->connection);
}
?>

How to Get the Current Page URL

Sometimes, you might want to get the current page URL that is shown in the browser URL window. For example if you want to let your visitors submit a blog post to Digg you need to get that same exact URL. There are plenty of other reasons as well. Here is how you can do that.

Add the following code to a page:

<?php
function curPageURL() {
 $pageURL = ‘http’;
 if ($_SERVER[”HTTPS”] == “on”) {$pageURL .= “s”;}
 $pageURL .= “://”;
 if ($_SERVER[”SERVER_PORT”] != “80″) {
  $pageURL .= $_SERVER[”SERVER_NAME”].”:”.$_SERVER[”SERVER_PORT”].$_SERVER[”REQUEST_URI”];
 } else {
  $pageURL .= $_SERVER[”SERVER_NAME”].$_SERVER[”REQUEST_URI”];
 }
 return $pageURL;
}
?>

You can now get the current page URL using the line:

<?php
  echo curPageURL();
?>

for example, if you want to check the current url is the same as other one or not, you can use it, if  they ar the same, show one thing, if not, show another, the code is as follows:

<?php
function curPageURL() {
 $pageURL = ‘http’;
 if ($_SERVER[”HTTPS”] == “on”) {$pageURL .= “s”;}
 $pageURL .= “://”;
 if ($_SERVER[”SERVER_PORT”] != “80″) {
  $pageURL .= $_SERVER[”SERVER_NAME”].”:”.$_SERVER[”SERVER_PORT”].$_SERVER[”REQUEST_URI”];
 } else {
  $pageURL .= $_SERVER[”SERVER_NAME”].$_SERVER[”REQUEST_URI”];
 }
 return $pageURL;
}
?>
<?php
  echo curPageURL();
$cururl=curPageURL();
?>
<br>

<?php if (’http://kingphp.com/’==$cururl)echo ‘Kingphp’;

else echo ‘Welcome to Kingphp’; ?>

How to usp php to ban ip

First build a database table:

CREATE TABLE `su_lockip` (
  `id` int(4) NOT NULL auto_increment,
  `lockip` varchar(1024) default NULL,
  PRIMARY KEY  (`id`)

Second, design a page so that you can add the ip you want to ban, every ip is devided by |,  I only write the mail part:
 

$UlockIp=$_POST[’z']?$_POST[’z']:”;
 if(empty($UlockIp)){
  exit(”<script>alert(’Sorry, the message your input is wrong!’);history.back();</script>”);
 }
 $sql=”update su_lockip set lockip=’$UlockIp’”;
 if(mysql_query($sql)){
  exit(”<script>alert(’Locked succesfully!’);history.back();</script>”);
 }else{
  exit(”<script>alert(’Sorry, the message your input is wrong!’);history.back();</script>”);
 } 

Last, check the ip is in the database or not, if in the database, then show killed.

function lock_user_ip(){
 $Usql =mysql_query(”select * from su_lockip”);
 $Urs =mysql_fetch_array($Usql);
 $UlockIp=$Urs[’lockip’];
 $ClockIp=$this->get_real_ip();
 $Iplist =explode(’|',$UlockIp);
 if(in_array($ClockIp,$Iplist)){
  exit(’sorry system lock your IP’);
 }
 }
 
 function get_real_ip(){
   $ip=false;
   if(!empty($_SERVER[”HTTP_CLIENT_IP”])){
    $ip = $_SERVER[”HTTP_CLIENT_IP”];
   }
   if (!empty($_SERVER[’HTTP_X_FORWARDED_FOR’])) {
    $ips = explode (”, “, $_SERVER[’HTTP_X_FORWARDED_FOR’]);
    if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
    for ($i = 0; $i < count($ips); $i++) {
     if (!eregi (”^(10|172\.16|192\.168)\.”, $ips[$i])) {
      $ip = $ips[$i];
      break;
     }
    }
   }
   return ($ip ? $ip : $_SERVER[’REMOTE_ADDR’]);
 } 

How to let tag cloud show the same size font and in list style?

It is very easy to tag cloud show the same size font and in list style, there are 2 ways to do this:

 1. Change sidebar.php in templates:

<li>

<h2>Tag Cloud</h2>

<?php wp_tag_cloud(’smallest=8&largest=8&number=45&orderby=name&format=list’); ?>  <!– wp_tag_cloud(’smallest=8&largest=8&number=45&orderby=name&format=list’)–>
</li>

another way is change code in widgets.php inside include document:

function wp_widget_tag_cloud($args) {
 extract($args);
 $options = get_option(’widget_tag_cloud’);
 $title = empty($options[’title’]) ? __(’Tags’) : apply_filters(’widget_title’, $options[’title’]);

 echo $before_widget;
 echo $before_title . $title . $after_title;
 wp_tag_cloud(”); //wp_tag_cloud(’smallest=8&largest=8&number=45&orderby=name&format=list’);
 echo $after_widget;
}

How to let the post show from lowest to highest?

If you want your posts show from lowest to highest, it is very simple, just add:
<!–p query_posts($query_string.’&order=ASC’);–>

for example, the following code will let all your post show from lowest to highest:

<!–p query_posts($query_string.’&order=ASC’);–>
<!–p if (have_posts()) : while (have_posts()) : the_post();–>

List 50 posts of wordpress.

If you want to list 50 posts, use the following code:

<ul>
 <?php
 global $post;
 $myposts = get_posts(’numberposts=-1′);
 foreach($myposts as $post) :
 ?>
    <li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li>
 <?php endforeach; ?>
 </ul>

if you want to list all the posts, use the following codes:

<ul>
 <?php
 global $post;
 $myposts = get_posts(’numberposts=5′);
 foreach($myposts as $post) :
 ?>
    <li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li>
 <?php endforeach; ?>
 </ul>

http://codex.wordpress.org/Template_Tags/get_posts

Wordpress Random posts

Display a list of 15 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:

 <ul><li><h2>A random selection of kingphp posts</h2>
    <ul>
 <?php
 $rand_posts = get_posts(’numberposts=15&orderby=rand’);
 foreach( $rand_posts as $post ) :
 ?>
    <li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li>
 <?php endforeach; ?>
    </ul>
 </li></ul>

 more: http://codex.wordpress.org/Template_Tags/get_posts#Random_posts

How to get root dirctory by php

<?php echo realpath(’./’)?>

very simple, right?