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;
    }
}


?>

Friday, October 5, 2012

Switch between multiple CSS styles sheets with PHP

A lot of webmasters like this nice looking CSS websites with the possibility to switch between different CSS style sheets. This code snippet will help to create the switch. Just create you different style sheets and your universal coded html documents (these one have to work with all the style sheets) and at least use this code in all html documents (or with a PHP included file). Notice: the links at the bottom of this site; they are created with the same function. After a visitor changed the style, his choice is stored inside a session variable.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


session_start();
$all_css = array();


$all_css['yellow']['file'] = "home_yellow.css";
$all_css['blue']['file'] = "home_blue.css";
$all_css['modern']['file'] = "home_modern.css"; // default

$all_css['yellow']['label'] = "Yellow!";
$all_css['blue']['label'] = "Deep blue";
$all_css['modern']['label'] = "Final..."; // default

$default_value = "modern"; // set the default value here

if (isset($_GET['change_css']) && $_GET['change_css'] != "") {
$_SESSION['css'] = $_GET['change_css'];
} else {
$_SESSION['css'] = (!isset($_SESSION['css'])) ? $default_value : $_SESSION['css'];
}
switch ($_SESSION['css']) {
case "yellow":
$css_file = "home_yellow.css";
break;
case "blue":
$css_file = "home_blue.css";
break;
default:
$css_file = "home_modern.css";
}
function style_switcher() {
global $all_css;
$style_links = "Style switch: \n";
foreach ($all_css as $key => $val) {
if ($_SESSION['css'] != $key) {
$style_links .= "";
$style_links .= "".$val['label']."  \n";
} else {
$style_links .= "".$val['label']."  \n";
}
}
return $style_links;
}




?>




Usage:


<!-- EXAMPLE: place this inside your html header -->
<link href="/includes/<?php echo $css_file; ?>" rel="stylesheet" type="text/css">
<!-- place this code inside the body where you want to show the links -->
<?php echo style_switcher(); ?>




Custom Error Page with .htaccess PHP

Create your own custom error page

This custom error page shows some standard error information and reports the error to the webmaster by e-mail. The script works for dead links and will report expired hot links from other sites (the IP address). Just add bad URL's and IP addresses into a text file to get the errors only once.


Create a .htaccess file in your root and enter these most common error code definitions


ErrorDocument 400 /error.php?err=400
ErrorDocument 401 /error.php?err=401
ErrorDocument 403 /error.php?err=403
ErrorDocument 404 /error.php?err=404
ErrorDocument 500 /error.php?err=500




Save below code in file "error.php"

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


if (isset($_GET['err'])) {
$errorNum = $_GET['err'];
} else {
$errorNum = "undef. number";
}

$emailaddress = "your@mail.com";
/*
you have to create this file and enter there all URL's with bad links and
all IP addresses which are hot linking not existing files, example:
117.40.85.210
http://www.example.com/filename.htm
*/
$filename = "http://".$_SERVER['HTTP_HOST']."/blocked_referer.txt";

// if the http referer is not empty check the file for exsiting URL's
if (!empty($_SERVER['HTTP_REFERER'])) {
$bad_referer = file ($filename);
$bad_counter = 0;
foreach ($bad_referer as $val) {
if (substr($_SERVER['HTTP_REFERER'], 0, 20) == substr($val, 0, 20)) {
$bad_counter++;
}
}
if ($bad_counter > 0) {
header("Location: http://".$_SERVER['HTTP_HOST']);
die();
} else {
$errortime = (date("d M Y h:m:s"));
$message = $errorNum." Error Report\r\n\r\nA ".$errorNum." error was encountered by ".$_SERVER['REMOTE_ADDR'];
$message .= " on $errortime.\r\n\r\n";
$message .= "The URI which generated the error is: \nhttp://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."\r\n\r\n";
$message .= "The referring page was:\n".$_SERVER['HTTP_REFERER']."\r\n\r\n";
$message .= "The used client was:\n".$_SERVER['HTTP_USER_AGENT']."\r\n\r\n";
$headers = "From: ".$emailaddress."\nDate: ".$errortime." +0100\n";
$subject = "Error: ".$errorNum." from ".$_SERVER['HTTP_REFERER'];
mail($emailaddress, $subject, $message, $headers);
}
} else { // at last check if there are already some bad IP Addresses
$bad_referer = file ($filename);
$very_bad_counter = 0;
foreach ($bad_referer as $val) {
if (substr($_SERVER['REMOTE_ADDR'], 0, 10) == substr($val, 0, 10)) {
$very_bad_counter++;
}
}
if ($very_bad_counter > 0) {
header("Location: http://4evertutorials.blogspot.in/"); // or some other nice URL
die();
}
}
// place here the html code you want to show the visitor, like
echo "you do not have sufficient permissions to access this page...

";



?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top