How to Create a PHP Redirect?

Directions

Sometimes you want to hide an affiliate link, sometimes you may want to log each downloads of a file or just redirect the user to a site through your script. This is where PHP redirection comes handy.

The syntax is as follow:

header("Location: http://ephp.info");
die();

[ad name=”In Post”]
Just replace the URL with the page you want the user to be redirected to. The die() function is to make sure that the script ends execution if the redirection function failed for some reason.

Note: The word “Location” in the script must always start with a capital first letter. Otherwise, some older browsers might now follow the redirection.

If you want more info on PHP’s header function check out the W3School’s reference page.

Download Remote File Using CURL and PHP

Sometimes you need to download URL’s contents using the CURL library, included inside PHP (e.g if you want to use a web-based API, provided by service like TinyURL, Digg, Twitter). It’s actually very simple and faster to use than other methods of downloading remote file like the file(), file_get_contents() or fsockopen().

Also, CURL is very customizeable. You can POST data to the downloaded URL, simulate user-agent (browser) or other headers. The simplest version of a PHP function to retrieve file’s contents using PHP’s CURL is below:

function getfile($url)
{
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	$downloaded = curl_exec($ch);
	curl_close($ch);
	return $downloaded;
        // More great PHP snippets at http://ePHP.info
}

After you include the function in your file, you can simply call it like that:

$contents = getfile("http://ephp.info/feed")

And the $content variable will now have this blog’s RSS feed.

PHP Script to Show Visitor’s IP Address

Old Globe

Sometimes you want to get the visitor’s IP address (e.g to show it to him or for logging purposes). This simple snippet does the job:

$ip = $_SERVER['REMOTE_ADDR'];

Also, if you have REGISTER_GLOBALS turned on on your server, you can use the shorter version:

$ip = @$REMOTE_ADDR;

Then you can easily use the variable called $ip for your needs.
[ad name=”In Post”]

Top Online IDEs to Test Your PHP Code

Sometimes you don’t have an Apache server on your PC and you don’t want to go through the hassle of uploading your PHP script to your web hosting space just to test if your tweaks inside the code work. Sometimes you just need to paste the code inside the IDE (Integrated Development Environment) and see the result, including potential errors and suggestions to fix them. Also, the ability to work with languages other than PHP is a plus.

1. CodeRun Studio

Full featured programming IDE. Supports a C#/.NET, PHP, Javascript, HTML and CSS. You can work with projects and multiple files simultaniuously. You can also upload your existing project and edit it online. You are also given a link to share your projects online.
[ad name=”In Post (LU)”]
2. Codepad

Plain and simple. Supports about 13 programming languages including C/C++, Perl, Ruby and more. After pasting a code the user is given an unique URL that can be shared with other people, so they can see the result too. You can make the code private if you are concerned about privacy. No registration required.

3. IDEOne.com

The functionality is close to Codepad. Supports more than 40 programming languages. There is an optional registration if you want to manage your submitted scripts.

Convert Text to Barcode Image

Thanks to a skilled PHP programmer, the internet has a ready made PHP script that takes a text string and returns an image representation in barcode format.

Here’s the complete script:

=1 to enable


        NOTE: You must have GD-1.8 or higher compiled into PHP
        in order to use PNG and JPEG. GIF images only work with
        GD-1.5 and lower. (http://www.boutell.com)


        ANOTHER NOTE: If you actually intend to print the barcodes 
        and scan them with a scanner, I highly recommend choosing 
        JPEG with a quality of 100. Most browsers can't seem to print 
        a PNG without mangling it beyond recognition. 


        USAGE EXAMPLES FOR ANY PLAIN OLD HTML DOCUMENT:
        -----------------------------------------------


        


        
                
        
*/
/*=============================================================================*/


//-----------------------------------------------------------------------------
// Startup code
//-----------------------------------------------------------------------------


if(isset($_GET["text"])) $text=$_GET["text"];
if(isset($_GET["format"])) $format=$_GET["format"];
if(isset($_GET["quality"])) $quality=$_GET["quality"];
if(isset($_GET["width"])) $width=$_GET["width"];
if(isset($_GET["height"])) $height=$_GET["height"];
if(isset($_GET["type"])) $type=$_GET["type"];
if(isset($_GET["barcode"])) $barcode=$_GET["barcode"];




if (!isset ($text)) $text = 1;
if (!isset ($type)) $type = 1;
if (empty ($quality)) $quality = 100;
if (empty ($width)) $width = 160;
if (empty ($height)) $height = 80;
if (!empty ($format)) $format = strtoupper ($format);
        else $format="PNG";


switch ($type)
{
        default:
                $type = 1;
        case 1:
                Barcode39 ($barcode, $width, $height, $quality, $format, $text);
                break;          
}


//-----------------------------------------------------------------------------
// Generate a Code 3 of 9 barcode
//-----------------------------------------------------------------------------
function Barcode39 ($barcode, $width, $height, $quality, $format, $text)
{
        switch ($format)
        {
                default:
                        $format = "JPEG";
                case "JPEG": 
                        header ("Content-type: image/jpeg");
                        break;
                case "PNG":
                        header ("Content-type: image/png");
                        break;
                case "GIF":
                        header ("Content-type: image/gif");
                        break;
        }


        $im = ImageCreate ($width, $height)
    or die ("Cannot Initialize new GD image stream");
        $White = ImageColorAllocate ($im, 255, 255, 255);
        $Black = ImageColorAllocate ($im, 0, 0, 0);
        //ImageColorTransparent ($im, $White);
        ImageInterLace ($im, 1);



        $NarrowRatio = 20;
        $WideRatio = 55;
        $QuietRatio = 35;


        $nChars = (strlen($barcode)+2) * ((6 * $NarrowRatio) + (3 * $WideRatio) + ($QuietRatio));
        $Pixels = $width / $nChars;
        $NarrowBar = (int)(20 * $Pixels);
        $WideBar = (int)(55 * $Pixels);
        $QuietBar = (int)(35 * $Pixels);


        $ActualWidth = (($NarrowBar * 6) + ($WideBar*3) + $QuietBar) * (strlen ($barcode)+2);
        
        if (($NarrowBar == 0) || ($NarrowBar == $WideBar) || ($NarrowBar == $QuietBar) || ($WideBar == 0) || ($WideBar == $QuietBar) || ($QuietBar == 0))
        {
                ImageString ($im, 1, 0, 0, "Image is too small!", $Black);
                OutputImage ($im, $format, $quality);
                exit;
        }
        
        $CurrentBarX = (int)(($width - $ActualWidth) / 2);
        $Color = $White;
        $BarcodeFull = "*".strtoupper ($barcode)."*";
        settype ($BarcodeFull, "string");
        
        $FontNum = 3;
        $FontHeight = ImageFontHeight ($FontNum);
        $FontWidth = ImageFontWidth ($FontNum);
        if ($text != 0)
        {
                $CenterLoc = (int)(($width-1) / 2) - (int)(($FontWidth * strlen($BarcodeFull)) / 2);
                ImageString ($im, $FontNum, $CenterLoc, $height-$FontHeight, "$BarcodeFull", $Black);
        }
        else
        {
            $FontHeight=-2;
        }


        for ($i=0; $i<strlen($BarcodeFull); $i++)
        {
                $StripeCode = Code39 ($BarcodeFull[$i]);


                for ($n=0; $n 

How to kill PHP (on purpose)

1. Stack overflow (e.g calling a function inside itself).

function a()
{ a(); }

a();

First you define a function called a() and the function’s sole purpose is to call itself again, causing an infinite loop. Then you just call the function.

2. Excessive Memory Allocation Using str_repeat

str_repeat("a", 10000000000);

The above code will cause PHP to use too much memory (which will cause the process to close), if the correct memory or script runtime limits are not properly configured.

3. Kill the Apache Process with PHP Script

shell_exec("killall -11 httpd");

This simple code will kill (end) all running Apache processes, except the Daemon (which runs as Root). All other Apache processes run under the same user, which means that one of them with the harmful script, mentioned above can easily kill the rest. The best way to ensure Apache’s protection in this case is to disable execution commands such as exec() or shell_exec() using the disable_functions() directive.