Feature
Post

Category
Code

Transfering Data with Other Servers Using cURL

In this day and age, there are many ways to transfer data between servers. One of the fastest, most popular, and easiest method is using the cURL library with the ability to work in many protocols, including HTTP, HTTPS, FTP, WebDAV, and more. In order to use this in PHP, you need to install the libcurl package. You must also enable libcurl once it is installed by uncommenting the line in your php.ini configuration file.

To verify that we have cURL installed and enabled, create a new file called phpinfo.php with the following code in it:

PHP:
  1. <?php
  2. ?>

Now go into your web browser and open up http://localhost/phpinfo.php or wherever you placed it. Once you are there, just do a search for the cURL module. If it isn't there, you must be using an older version of libcurl or not enabled it.

For your first script, we will be getting an RSS file from digg. In order to do this, we first need to initiate cURL, set some of our options (including URL), dispatch it, then close it.

PHP:
  1. <?php
  2. $url = 'http://digg.com/rss/index.xml';
  3. $ch = curl_init(); // Initialize the cURL handler
  4.  
  5. curl_setopt($ch, CURLOPT_URL, $url); // Set the URL
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return data, instead of displaying it
  7. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1) // Follow any redirects, just in case
  8.  
  9. $rss = curl_exec($ch); // Get the data
  10. curl_close($ch); // Close cURL handler
  11. ?>

In the above code, we use the PHP constant CURLOPT_RETURNTRANSFER, because if we don't the function curl_exec($ch) will automatically echo the data onto the page. We make sure to enable it so that the data instead goes into the $rss variable so that you may work with it. Another constant we used was CURLOPT_FOLLOWLOCATION, because if one day digg.com decides to change the location of this feed, and has put a redirect in place of it, cURL will transfer itself to this new URL.

Sure you can get data from a page, but you can also send as well! Lets say you want to search for videos on YouTube, you may do so as follows:

PHP:
  1. <?php
  2. $search = 'libcurl';
  3. $url = 'http://youtube.com/results';
  4. $ch = curl_init(); // Initialize the cURL handler
  5.  
  6. curl_setopt($ch, CURLOPT_URL, $url); // Set the URL
  7. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1) // Follow any redirects, just in case
  8. curl_setopt($ch, CURLOPT_POST, 1); // set POST method (to send our search)
  9. curl_setopt($ch, CURLOPT_POSTFIELDS, 'search_query=' . $search); // What we will be searching for
  10.  
  11. curl_exec($ch); // Display page
  12. curl_close($ch); // Close cURL handler
  13. ?>

If you have already tested the code out, you may have noticed that you see YouTube. This is because I have removed the CURLOPT_RETURNTRANSFER constant just for fun, but you can ofcourse just reinclude it and make sure that curl_exec($ch) is returning the data into a variable. CURLOPT_POST switches cURL's setting from getting, to sending, while CURLOPT_POSTFIELDS sets the data you want to send. In this case search_query=libcurl

If you go to web sites that have protected directories and your browser requires a username and password, you can also use cURL for that!

PHP:
  1. <?php
  2. $url = 'http://mysite.com/protected';
  3. $ch = curl_init(); // Initialize the cURL handler
  4.  
  5. curl_setopt($ch, CURLOPT_URL, $url); // Set the URL
  6. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1) // Follow any redirects, just in case
  7. curl_setopt($ch, CURLOPT_USERPWD, "username:password"); // Your username and password
  8.  
  9. curl_exec($ch); // Display page
  10. curl_close($ch); // Close cURL handler
  11. ?>

This is basically for something called HTTP Authentication where you need an authorized username and password to continue. The PHP cURL constant CURLOPT_USERPWD lets you define the username and password with a colon in between. Everything else is pretty much normal.

Of course you can also use HTTPS (HTTP Secure) and FTP connections and more. You can find more tutorials on PHP here on Devlounge and please comment with your thoughts on the article.

Feature
Post

Category
Code

Rotating Header Images in PHP

Most websites like to use rotating banners to add an extra appeal in their header. To make this work, all we need to do is get all the images from the specified directory, choose a random image, and present it to the browser. First, we need to create some sort of configuration for this:

<?php
$directory = './images/';
$accept = array('gif', 'png', 'jpg');
$deny = array('file1.jpg', 'file2.gif');
?>

Next, in order to scan through the directory, we would need to use scandir(). Using the filters above, we can also restrict the files that are in the directory using array_filter() since the output of scandir() is of type array. The built-in PHP function array_filter() requires an input array, and an optional callback function. A callback function is a function that PHP calls after a certain event. In this case, the event would trigger with every value in the array. We will use the callback option which requires one parameter that will contain the value of the key.

<?php
$files = scandir($directory);
$files = array_filter($files, 'filter_images');

function filter_images($image)
{
    global $accept, $deny;

    if (in_array($image, array_merge($deny, array('.', '..', '.htaccess', 'index.html'))))
    {
        // Remove, because we don't accept those files
        return false;
    }

    $ext = substr(strrchr($image, '.'), 1);

    if (!in_array($ext, $accept))
    {
        // Remove, because its not an accepted extension
        return false;
    }

    // This image passed the tests
    return true;
}
?>

Now we have an array of all of the images we can use for the banner rotator. Because we removed some of the values from the file list, we need to resort the array so that the keys are consecutively ordered from 0 using the function sort(). After this, we will need to generate a random number from the range of the keys using mt_rand(). The reason we are not going to use rand() because mt_rand() produces a "better" random number and is four times faster, according to php.net.

<?php
$files = array_values($files);
$rand = mt_rand(0, count($files)); // mt_rand(min, max);
$image = $directory . $files[$rand];
?>

We have selected our image and all that we have left is to output the image to the browser. We need to set the proper content type header and output the contents of the image using header() and readfile().

<?php
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $image);
finfo_close($finfo);

header('Content-type: ' . $mime);
readfile($image);
?>

At this point, a random image is displayed when viewing this file. All you have to do next is display it on your page using the HTML <img>tag or using CSS. I will go over both methods.

First, using the image tag, you can do the following:

 <img src="banner.php" alt="Banner" />

Next, with CSS, you can do this:

<style type="text\css">
#banner {
    background-image: url(banner.php);
}
</style>
 <div id="banner"></div>

If you want to get more advanced, you can always enhance the filters with REGEX using preg_match(). And, as I said before, for their header to add an extra appeal and other uses. You can wrap a link around the <img> so that whenever someone clicks your header, it redirects them to the homepage. This is a tool most websites use, depending on how it is constructed and looks. I hope you guys have fun with this script!

Download File

Feature
Post

Category
Code

Multiple Languages on any Page Dynamically

Have you ever thought of adding multiple languages to your website or have done so using methods such as creating separate directories for a completely new website with only that one language? The PHP language can make this easy for your site.

To begin, you will need atleast 4 files: index.php, index.html, lang.php, lang_english.php, and any other language file you want in the format of lang_[language].php.

This will work by creating variables within your html files. Such variable would look like {VARIABLE}. We would then replace them with the variables in the language files. An example of how a user would use this would be: Bob goes to your website and the default language is English. He then wants to change the language to Spanish, so he will click on a link in the menu bar. The page refreshes with the new language selection visible.

First we create an html file (index.html) in the default language:

<html>

    <head>

        <title>Language Test</title>

    </head>

    <body>

        <p>Hello World</p>

    </body>

</html>

Then we convert the text into variables and add the links to the different languages:

<html>

    <head>

        <title>{TITLE}</title>

    </head>

    <body>

        <div id=”menu”>

            <a href=”index.php?lang=english”>English</a>

            <a href=”index.php?lang=spanish”>Spanish</a>

        </div>

        <p>{INTRO}</p>

    </body>

</html>

Simple enough, right? Now for a language file. To make things easier, we will use an associative array of strings:

<?php

// lang_english.php

$lang = array(

    'TITLE' => 'Language Test',

    'INTRO' => 'Hello World',

);

?>
<?php

// lang_spanish.php

$lang = array(

    'TITLE' => 'Prueba de Lenguage',

    'INTRO' => 'Hola, Mundo',

);

?>

A note I have to make about variable naming: The variables do not have to be in all uppercase, though it is common practice. You have the freedom to name them anything you want and however way you want to.

The language converter will also act like a pseudo-template engine in which it loads the html, converts some data, then displays it. This is why we created the index.html file above. Now, to load, we can simply use file_get_contents to access the data within the html. We would also have to include a language file based on the user input and then convert using another function called strtr.

<?php

// lang.phpfunction get_lang($file)

{

    // The default lang

    $user_lang = 'english';

// Lets see if the user clicked on a language

    if (isset($_GET['lang']) && !empty($_GET['lang']))

    {

        $user_lang = $_GET['lang'];

    }

// Include a language file

    include 'lang_' . basename($user_lang) . '.php';

// Get the data from the HTML

    $html = file_get_contents($file);

// Create an empty array for the language variables

    $vars = array();

// Scroll through each variable

    foreach($lang as $key => $value)

    {

        // Turn 'THIS' to '{THIS}'

        $vars['{' . $key . '}'] = $value;

    }

// Finally convert the strings

    $html = strtr($html, $vars);

// Return the data

    return $html;

}

?>

The comments within the function should be enough. Now going on, we need to use this within index.php:

<?php

// index.php// Get the function

include 'lang.php';

// Convert and display

get_lang('index.html');

?>

This pretty much sums it up on how to create a page with multiple languages. All you need to do is add language files (lang_[language_name].php). You may also order the structure of your site by keeping the language files in its own folder like /languages/ and put the html files into a directory like /html/. You must also adjust the paths in the function and everywhere else to suit a new structure you put in. Also, so that the user wont have to click on the Spanish conversion link every time, you may also make it work via cookie, or via a database if the user has an account on your site.

Source Files