Post message to another server through fopen and fsockopen in php

PHP tutorial for, Post message to another server through fopen and fsockopen in php. When this comes to sending data to server to server we need to post the data using web services.
Many people want to use the curl php method but there are serious issues with that.

Post message to another server through fopen and fsockopen in php

 

Post message to another server through fopen and fsockopen in php
Post message to another server through fopen and fsockopen in php

So I recommended to use fopen function to post the message to server to server.

You can use the following code for post the message to another server using fopen and fsockopen

    function post($host, $post_url,$port,$data) {
        $errno = 0;
        $errstr = '';

        $path = str_replace($host,'',$post_url); // IP of minor instance

        $header_variables = "POST / HTTP/1.1\r\n";
        $header_variables .= "Host: $host\r\n";
        $header_variables .= "Connection: Close\r\n";
        $header_variables .= "Content-Type: application/xml\r\n";
        $header_variables .= "Content-Length: " . strlen($data) . "\r\n\r\n";

        // establish the connection and send the request
        $fp = fsockopen($host, $port, &$errno, &$errstr, 15);
        if ($fp) {
            stream_set_timeout($fp, 15);
            fputs($fp, $header_variables);
            fputs ($fp, $data); //data written
            fputs ($fp, "\r\n"); //request posted

            $response = stream_get_contents($fp);
            $info = stream_get_meta_data($fp);
            if (!$info['timed_out'] && $fp) {
                //get response and everything is ok
            } else {
                trigger_error('Timed out for '.$post_url);
                exit();
            }

            fclose($fp); //close the file

        } else {
            trigger_error('Failed to open socket connection. ');
            exit();
        }
    }



using CURL function post message also possible for that you can use following code

<!--?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' =--> 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

Twitter follower count using PHP in WordPress

you can easily show twitter follower count in your wordpress site. In this tutorial we used twitter xml api for fetching Twitter follower count using PHP. You can place the twitter count in header section or footer section or sidebar section of wordpress.

Twitter follower count using PHP in WordPress

 

Twitter follower count using PHP in WordPress
Twitter follower count using PHP in WordPress

Using following code you can print the twitter followers count.


<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
$twitter_api = file_get_contents('http://twitter.com/users/show/USERNAME.xml');
$text_output = '<followers_count>'; $end = '</followers_count>';
$page = $twitter_api;
$explode_content = explode($text_output,$page);
$page = $explode_content[1];
$explode_content = explode($end,$page);
$twitter_followers = $explode_content[0];
if($twitter_followers == '') { $twitter_followers = '0'; }
echo '<div><strong>'.$twitter_followers.' </strong> Followers</div>';

?>

You just need to replace the your name instead of USERNAME.

php convert unix timestamp to utc

If you want to convert the unix time formart in simple readable format.

php convert unix timestamp to utc

If you got Unix time from some where and you need to convert to simple format then use following code.

<?php
$unix_timestamp = 1280225046;
$date =   date("r",$unix_timestamp);

$readable_date = date("Y-m-d H:i:s", strtotime($date));
echo $readable_date;
?>

Following PHP date functions are useful:
date() is likely the most-used date function in PHP, it can generate the current date or a selected timestamp in a huge amount of probabilities. A table of all the string determiners is available here

mktime() has parameters, one for each setting for time: second, minute, hour, month, day & year. The 7th parameter is for day light savings however if this setting is left alone PHP will find out the DS hour itself. mktime() returns a timestamp for the parameters made.

strtotime() converts a string into a timestamp, if it can’t achieve this it’ll return -1 or false.

time() returns the current time to the closest second as a timestamp.

how to make simple guestbook with php

Here in this PHP tutorial, we will give you code sample for, how to make simple guestbook with php. we given code sample with database schema. we explained every step. Here’s an easy way to create guestbook with php.

how to make simple guestbook with php

First you have to create database for it. If your database has been created add this table to database.


 CREATE TABLE IF NOT EXISTS `posts` (

 `name` varchar(100) NOT NULL,

 `email` varchar(100) NOT NULL,

 `website` varchar(100) NOT NULL,

 `message` text NOT NULL,

 `ip` varchar(25) NOT NULL,

 `date` varchar(50) NOT NULL

 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Step 1: Creating A Form

First we have to create a form. to do this use the following PHP code:


<code><code>echo "php?act=add' method='post'>"</code></code>

."Name:
<input type='text' name='name' size='30' />
"

."Email:
<input type='text' name='email' size='30' />
"

."Website:
<input type='text' name='website' size='30' />
"

."Message:
<textarea cols='30' rows='8' name='message'>
"

."<input type='submit' value='Post' />"

."</form>";

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Step 2: Add Info To Database

Now we have to add info to database. Do this using by this PHP code:

if($_GET['act'] == "add") </code></code>

<code><code>{ // If act is "add" like this file.php?act=add display the content</code></code>

$sqlCon = mysql_connect("localhost", "root", "bananaman"); // Connect to database

if($sqlCon == true){ // If connection has been made then..

$sqlSel = mysql_select_db("guestbook", $sqlCon); // Select a database

if($sqlSel == true)

<code><code>{ // If database has been successfully selected gather info and post it</code></code>

$name = addslashes(htmlspecialchars($_REQUEST['name'])); // Takes "name" field from the form

$email = addslashes(htmlspecialchars($_REQUEST['email'])); // Takes "email" field from the form

$website = addslashes(htmlspecialchars($_REQUEST['website'])); // Takes "website" field from the form

$message = addslashes(htmlspecialchars($_REQUEST['message'])); // Takes "message" field from the form

$ip = $_SERVER['REMOTE_ADDR']; // This takes user's IP

$time = time(); // Get UNIX timestamp

// This will create a SQL query which inserts all that information into database

$sql = "INSERT INTO posts (name, email, website, message, ip)

<code><code>VALUES ('".$name."', '".$email."', '".$website."', </code></code>

<code><code>'".$message."', '".$ip."', '".$time."')";</code></code>

// This will process SQL query and performs inserting info to database

$query = mysql_query($sql);

if($query == true) { // If everything was correct ..

echo "Your post has been successfully posted!"; // Display a success message

}else { // But if there was something wrong ..

echo "There was something wrong."; // Display a fail message

// As you can see I have commented

// mysql_error() function. It is because

// if you want to see what went wrong with

// your SQL query. Displaying it is not very

// good idea because it's like a candy to

// hackers. So if you have fixed the problem

// make sure to add comment "//" in front of it

//echo mysql_error();

}

mysql_close($sqlCon); // Close connection to database

}else{

exit; // If database selection wasn't a success close script

}

}else{

exit; // If connecting to database wasn't a success close script

}

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Step 3: Displaying Posts

Now posting part is done, now we're going to display our posts.

Use this PHP code:


<code><code>$sqlCon = mysql_connect("localhost", "root", "bananaman"); // Connect to database</code></code>

if($sqlCon == true) { // If connecting was successful ..

$sqlSel = mysql_select_db("guestbook", $sqlCon); // select your database

if($sqlSel == true) { // If database selecting was successful then take info from it

// Select all records from database

$sql = "SELECT * FROM posts";

// Process your selection

$query = mysql_query($sql);

// This creates a table which contains all info

// of your posts

while($info = mysql_fetch_array($query)) {

echo "<table width='300' border='1'>"

."<tr>"

."<td>Posted by: <a href='".$info['website']."'>".$info['name']."</a> (<a href='mailto:".$info['email']."'>Email</a>)</td>"

."".date("H:i j F Y", $info['date']).""

."</tr>"

."<tr>"

."<td colspan='2'>".$info['message']."</td>"

."</tr>"

."</table>"

."
";

}

mysql_close($sqlCon); // Close database connection

}else { // If database selection wasn't successful ..

exit; // exit form the script

}

}else { // If connection to database wasn't success ..

exit; // exit from your script

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

And you are done with your script. It should look like this:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Thank you!

How to use memcached with php

Using this tutorial you will know, How to use memcached with php. We given code for using memcache with php. we shown you to configure memcache with php.

How to use memcached with php

 

How to use memcached with php
How to use memcached with php

If you try to install memcached with Linux server then use following commands

# yum install libevent
# yum install libmemcached libmemcached-devel
# yum install memcached

For Starting the memcached server
# memcached -d -m 512 -l 127.0.0.1 -p 11211 -u nobody

11211 port is default port for memcached server.

For using the memecached with php client you need to install following package

# pecl install memcache

After installing all packages restart the apache server.

# /etc/sbin/service httpd restart

<!--?php
/* OO API */
$memcache_obj = new Memcache;
$memcache_obj--->connect('memcache_host', 11211);
$memcache_obj->set('any_key', 'some value', MEMCACHE_COMPRESSED, 50);
echo $memcache_obj->get('any_key');
?>

Important Note: Memcached key has limitations of 250 charactors, So key value should be with in 250 charactors.

what is difference between die and exit in php

Many PHP developers are been asked this question in interview. But many times they are not sure about answer.

There is no difference between die() and exit() function. They both are same and worked same.
Again question is why php keep the both functions if they are same. Both functions are alias of each other function.

Due to API and keeping the backward compatibility both functions are kept.

what is difference between die and exit in php
what is difference between die and exit in php

Here is one more example:

is_int() and is_integer() are also same.

There are quite a few functions in PHP which you can call with more than one name. In some cases there is no preferred name among the multiple ones, is_int() and is_integer() are equally good for example. However there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.

Full list of Aliases function you will find on following URL:
http://php.net/manual/en/aliases.php

How to use sleep and usleep function in PHP

PHP tutorial, explained to use sleep and usleep function in PHP. Sleep is very common method in every language. How sleep function works we need to understand.

use sleep and usleep function in PHP

Sleep function delays the program execution for the given number of seconds.
Usleep delays program execution for the given number of micro seconds.

Following is the php example with sleep function

&lt;?php
echo date('h:i:s') . &quot;&lt;br /&gt;&quot;;

//stop execution for 30 seconds
sleep(30);

//start again
echo date('h:i:s');

?&amp;gt;

Following is the php example with usleep function

<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
echo date('h:i:s') . &quot;&lt;br /&gt;&quot;;

//stop execution for 30 seconds
usleep(30000000);

//start again
echo date('h:i:s');
?>
How to use sleep and usleep function in PHP
How to use sleep and usleep function in PHP

log php error in log file with trigger_error

in this article i given full information about log php error in log file with trigger_error. PHP given the method for log error using there method.

log php error in log file with trigger_error

log php error in log file with trigger_error
log php error in log file with trigger_error

In PHP language checking the logs and checking error is sometimes became difficult.
PHP is offer inbuild solution to log all errors to a log fiie.

First I will tell about creating the normal error log file.
Open your pho.ini file and modify the following line.

error_log = /var/log/php-error.log

Make sure display_errors set to Off (no errors to end users)

display_errors = Off

This is normal way to check the php error log.

But if you want to check where is script is dying or you want to debug.
Then use trigger_error() function. Personaly I love to use this function for logging the php errors.

Using this function you can specify the custom error messages as per your script requirement.

<?php
$test = ture;
if ($test == true) {
trigger_error("A custom error has been triggered");
}
?>

When you run this file and check the php error log file or you can check httpd/apache error log file.

you will got following error message.

Notice: A custom error has been triggered
in C:\webfolder\test.php on line 5

how detect ie7 or ie8 with php and every language

In daily development we face lot of cross browser issues and sometimes conditional css will never work as excepted. We can detect I7 and I8 browser using every language. Using PHP language I need to use the browser So I written following code.

How to detect ie7 or ie8 with php

We can detect ie7 or ie8 with php and every language. Using PHP language I need to use browser So I written code snippet which is useful for PHP developer.

In this article I will show how to detect IE browser and IE 7 and IE8 using php language.

Following function you can use for detecting the IE browsers.


function detect_ie($navigator_user_agent)
{
 if (stristr($navigator_user_agent, "MSIE"))
 {
 return true;
 } else return false;
}

detect_ie($_SERVER['HTTP_USER_AGENT']);

//detect IE7 browser

function detect_ie7($navigator_user_agent)
{
 if (stristr($navigator_user_agent, "msie 7"))
 {
 return true;
 } else return false;
}

detect_ie7($_SERVER['HTTP_USER_AGENT']);

function detect_ie8($navigator_user_agent)
 {
 if (stristr($navigator_user_agent, "msie 7"))
 {
 return true;
 } else return false;
 }

detect_ie8($_SERVER['HTTP_USER_AGENT']);

How to detect ie7 or ie8 with php
How to detect ie7 or ie8 with php

how to install php-pear on centos or redhat

centos is linux based operating system which is used for server purpose. in this article I given the detailed information about, install php-pear on centos or rehat os.

For this example I used the RHEL 5.3 edition. If server is new then use follwoing commands to keep server up to date.
When I tried to install php-pear lib in server I am not able to install all the pear libs. Then I Used following commands for installing the php-pear fully.

install php-pear on centos

# yum update
# up2date -u
# yum install lighttpd-fastcgi php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mapserver php-mbstring php-mcrypt php-mhash php-mssql php-shout php-snmp php-soap php-tidy php-pear php-devel httpd-devel mysql-server mysql-devel

The 2 RPMs which we need are:
epel-release and remi-release

# wget http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm
# rpm -Uvh epel-release-5-3.noarch.rpm

# wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
# rpm -Uvh remi-release-5.rpm

# yum install php-pear*

# /sbin/service httpd start
# /sbin/service mysqld start

# php -v

install php-pear on centos
install php-pear on centos