Wednesday, October 24, 2012

Retrieve Remote file size with cURL PHP

Here's the best way (that I've found) to get the size of a remote file. Note that HEAD requests don't get the actual body of the request, they just retrieve the headers. So making a HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a resource that is 1KB.

Note: This will only work if the remote host is supplying valid content header, namely Content-Length. You cannot otherwise get file size without actually downloading it first.
 
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$remoteFileURL = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFileURL);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
  echo 'cURL failed';
  exit;
}

$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
  $status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}

echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;

?>

 
Result:
HTTP Status: 302 Content-Length: 8808759
 

Saturday, October 20, 2012

Force file download in PHP

PHP allows you to change the HTTP headers of files, so that you can force a file to be downloaded that normally the browser would load in the same window. This is perfect for files like PDFs, document files, images, and video that you want your visitors to download rather than read online.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$output = file_get_contents('your_file_here.extension');
if(ini_get('zlib.output_compression'))
{
ini_set('zlib.output_compression', 'Off');
}
$ctype="application/force-download";
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"Your_File_Here.Extension\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($output));
echo $output;
exit();

?>

Friday, October 19, 2012

Block Multiple ip addresses in PHP

Sometimes you need to disallow a visitor to access your website. The most common reason for this is Spammers. Although there are several other solutions to block multiple IP addresses, but in this post we are going to focus on simple php script.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$blacklisted_ips = array("304.456.789.66", "626.789.123.85", "578.123.45.46");

if(in_array($_SERVER['REMOTE_ADDR'], $blacklisted_ips)) {
    header("Location: http://www.examples.com/block.php");
    exit();
}

?>

Thursday, October 18, 2012

Get URL in PHP

Below is a simple php function that return current page url
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function currentURL() {
    $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;
}

?>

Date and Time Format like Facebook in PHP

This simple PHP example will return a date and time format like facebook, generated from a mysql datetime field. Input Format: date('Y-m-d H:i:s')
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function getDateTime($datetime)
{
    $datetime=strtotime($datetime);
    $yesterday=strtotime(date('Y-m-d', mktime(0,0,0, date("m") , date("d") - 1, date("Y"))));
    $tomorrow=strtotime(date('Y-m-d', mktime(0,0,0, date("m") , date("d") + 1, date("Y"))));
    $time=strftime('%H:%M',$datetime);
    $date=strftime('%e %b %Y',$datetime);
 
    if($date==strftime('%e %b %Y',strtotime(date('Y-m-d'))))
    {
        $date="Today";
    }
    elseif($date==strftime('%e %b %Y',$yesterday))
    {
        $date="Yesterday";
    }
    elseif($datum==strftime('%e %b %Y',$tomorrow))
    {
        $date="Tomorrow";
    }
 
    return $date." at ".$time;
}



?>

Mysql Database Connection in PHP

This is a simple example of how you could create a database connection from PHP to MySQL. It is good to save the MySQL Database Connection in a seperate php file in a secure part of the website. Then the file can be referenced in any page that requires a connection to the database file or This will save you from having to retype the details on every page and makes code reusable.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//MySQL database hostname (i.e.: Localhost)
$db_host='';
 
//MySQL database name (i.e. database)
$db_name='';
 
//MySQL database username (i.e. user)
$db_user='';
 
//MySQL database password for the user above
$db_pass='';
 
//Initialize connection
$connection = mysql_connect($db_host, $db_user, $db_pass) or die ('Error');
mysql_select_db($db_name);


?>

Saturday, October 13, 2012

Validate Credit Card Number Using PHP

This piece of code will check if a creditcard number could possibly be valid, determined on the number ranges given. It will NOT actually validate the number with the creditcard company but it could function as a pre-check.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function validate_credit_card($number)
{
    $false = false;
    $card_type = "";
    $card_regexes = array(
       "/^4\d{12}(\d\d\d){0,1}$/" => "visa",
       "/^5[12345]\d{14}$/"       => "mastercard",
       "/^3[47]\d{13}$/"          => "amex",
       "/^6011\d{12}$/"           => "discover",
       "/^30[012345]\d{11}$/"     => "diners",
       "/^3[68]\d{12}$/"          => "diners",
    );
 
    foreach ($card_regexes as $regex => $type) {
        if (preg_match($regex, $number)) {
            $card_type = $type;
            break;
        }
    }
 
    if (!$card_type) {
        return $false;
    }
   
    //  mod 10 checksum algorithm
    $revcode = strrev($number);
    $checksum = 0; 
 
    for ($i = 0; $i < strlen($revcode); $i++) {
        $current_num = intval($revcode[$i]);
        if($i & 1) {  // Odd  position
           $current_num *= 2;
        }
            // Split digits and add
            $checksum += $current_num % 10; if
        ($current_num >  9) {
            $checksum += 1;
        }
    }
 
    if ($checksum % 10 == 0) {
        return $card_type;
    } else {
        return $false;
    }
}


?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top