Wednesday, November 28, 2012

Disable Browser Cache using PHP

This is a simple function which sends combination of headers that completely disable any browser caching.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
function disable_browser_cache() 
{
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
}
?>

Download files from Amazon

Amazon S3 (Simple Storage Service) is a commercial storage web service offered by Amazon Web Services. It is inexpensive, scalable, responsive, and highly reliable. It has no minimum fee, and no start-up cost.

This code uses standard PHP sockets to send REST (HTTP 1.1) queries to Amazon S3 server. It does not support 'keep-alive' connections, so each call to downloadREST() function opens new connection to 's3.amazonaws.com'.

You should set following variables:

    $aws_key — Your AWS Access Key ID
    $aws_secret — Your AWS Secret Access Key
    $aws_bucket — AWS bucket (directory) name. You must specify existing AWS bucket.
    $aws_object — AWS object (file) name. You must specify existing AWS object.


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$aws_key = '_YOUR_AWS_KEY_000000';
$aws_secret = '_your_aws_secret_00000000000000000000000';


$aws_bucket = '4evertutorials'; // AWS bucket 
$aws_object = '4evertutorials.png';         // AWS object name (file name)

if (strlen($aws_secret) != 40) die("$aws_secret should be exactly 40 bytes long");



$dt = gmdate('r'); // GMT based timestamp 

// preparing string to sign
$string2sign = "GET


{$dt}
/{$aws_bucket}/{$aws_object}";


// preparing HTTP query 
$query = "GET /{$aws_bucket}/{$aws_object} HTTP/1.1
Host: s3.amazonaws.com
Connection: close
Date: {$dt}
Authorization: AWS {$aws_key}:".amazon_hmac($string2sign)."\n\n";

echo "Downloading:  http://s3.amazonaws.com/{$aws_bucket}/{$aws_object}\n";
list($header, $resp) = downloadREST($fp, $query);
echo "\n\n";

if (strpos($header, '200 OK') === false) // checking for error
    die($header."\r\n\r\n".$resp); // response code is not 200 OK -- failure

$aws_object_fs = str_replace('/', '_', $aws_object);
// AWS object may contain slashes. We're replacing them with underscores 

@$fh = fopen($aws_object_fs, 'wb');
if ($fh == false) 
    die("Can't open file {$aws_object_fs} for writing. Fatal error!\n");
    
echo "Saving data to {$aws_object_fs}...\n";
fwrite($fh, $resp);
fclose($fh);


// Sending HTTP query, without keep-alive support
function downloadREST($fp, $q)
{
    // opening HTTP connection to Amazon S3
    // since there is no keep-alive we open new connection for each request 
    $fp = fsockopen("s3.amazonaws.com", 80, $errno, $errstr, 30);

    if (!$fp) die("$errstr ($errno)\n"); // connection failed, pity 
        
    fwrite($fp, $q); // sending queyr
    $r = ''; // buffer for result 
    $check_header = true; // header check flag
    $header_end = 0;
    while (!feof($fp)) {
        $r .= fgets($fp, 256); // reading response

        if ($check_header) // checking for header 
        {
            $header_end = strpos($r, "\r\n\r\n"); // this is HTTP header boundary
            if ($header_end !== false) 
                $check_header = false; // We've found it, no more checking 
        }
    }

    fclose($fp);
    
    $header_boundary = $header_end+4; // 4 is length of "\r\n\r\n"
    return array(substr($r, 0, $header_boundary), substr($r, $header_boundary));
    // returning HTTP response header and retrieved data 
}


// hmac-sha1 code START
// hmac-sha1 function:  assuming key is global $aws_secret 40 bytes long
// read more at http://en.wikipedia.org/wiki/HMAC
// warning: key($aws_secret) is padded to 64 bytes with 0x0 after first function call 
function amazon_hmac($stringToSign) 
{
    // helper function binsha1 for amazon_hmac (returns binary value of sha1 hash)
    if (!function_exists('binsha1'))
    { 
        if (version_compare(phpversion(), "5.0.0", ">=")) { 
            function binsha1($d) { return sha1($d, true); }
        } else { 
            function binsha1($d) { return pack('H*', sha1($d)); }
        }
    }

    global $aws_secret;

    if (strlen($aws_secret) == 40)
        $aws_secret = $aws_secret.str_repeat(chr(0), 24);

    $ipad = str_repeat(chr(0x36), 64);
    $opad = str_repeat(chr(0x5c), 64);

    $hmac = binsha1(($aws_secret^$opad).binsha1(($aws_secret^$ipad).$stringToSign));
    return base64_encode($hmac);
}
// hmac-sha1 code END 

?>




See Amazon S3 Developer Guide for REST protocol details.

Using this code makes sense for objects uploaded with 'private' or 'authenticated-read' Amazon S3 ACL. You may download objects with other ACLs(public-read, public-read-write) by simply downloading file from URL:

           http://s3.amazonaws.com/bucket_name/object_name

Where 'bucket_name' is AWS bucket name, and 'object_name' is AWS object name.

Thursday, November 15, 2012

Easy to use and reliable mail function php

How to send email with PHP. Although PHP has built in function mail() to send email, it's quite insecure and use nonobvious arguments. In below example function Send_mail can send mail when called with just four arguments: from, to, subject, text. To avoid email injection (using malformed parameters to send spam through mail()) removing of special characters is used.


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

$site_admin = 'admin@example.com';

function Send_mail($from, $to, $subject, $text, $headers="")
{
    if (strtolower(substr(PHP_OS, 0, 3)) === 'win')
        $mail_sep = "\r\n";
    else
        $mail_sep = "\n";

    function _rsc($s)
    {
        $s = str_replace("\n", '', $s);
        $s = str_replace("\r", '', $s);
        return $s;
    }

    $h = '';
    if (is_array($headers))
    {
        foreach($headers as $k=>$v)
            $h = _rsc($k).': '._rsc($v).$mail_sep;
        if ($h != '') {
            $h = substr($h, 0, strlen($h) - strlen($mail_sep));
            $h = $mail_sep.$h;
        }
    }

    $from = _rsc($from);
    $to = _rsc($to);
    $subject = _rsc($subject);
    mail($to, $subject, $text, 'From: '.$from.$h);
}





if (($_SERVER['REQUEST_METHOD'] == 'POST') &&
    isset($_POST['subject']) && isset($_POST['text']) &&
    isset($_POST['from1']) && isset($_POST['from2']))
    {
        $from = $_POST['from1'].' <'.$_POST['from2'].'>';
        

        Send_mail($from, $site_admin, $_POST['subject'], $_POST['text'],
        array('X-Mailer'=>'4evertutorials.blogspot.in  Online PHP Examples with Source Code'));
        $mail_send = true;
    }



<html><head>Send us mail - 4evertutorials.blogspot.in
</head><body>
<?php
if (isset($mail_send)) {
    echo '

Form has been successfully sent, thank you

'; } else { ?>
Your Name:
Your Email:
Subject:
Text:
<?php } ?> </body></html> ?>

Wednesday, November 14, 2012

Detect user's browser with PHP

You can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.

By php.net, get_browser attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

Note:

In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.

browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

Listing all information about the users browser
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$browser = get_browser(null, true);
print_r($browser);

output something similar to:
Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)
?>

Monday, November 5, 2012

Set limitation for download rate

This snippet allows you set a limitation for download rate of the file that visitors download from your site.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
/* set here a limit of downloading rate (e.g. 10.20 Kb/s) */
$download_rate = 10.20;

$download_file = 'download-file.zip'; 
$target_file = 'target-file.zip';

if(file_exists($download_file)){
/* headers */
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($download_file));
header('Content-Disposition: filename='.$target_file);

/* flush content */
flush();

/* open file */
$fh = @fopen($download_file, 'r');
while(!feof($fh)){
/* send only current part of the file to browser */
print fread($fh, round($download_rate * 1024));
/* flush the content to the browser */
flush();
/* sleep for 1 sec */
sleep(1);
}
/* close file */
@fclose($fh);
}else{
die('Fatal error: the '.$download_file.' file does not exist!');
}
?>

Generate passwords automatically php

Sometimes you need to generate passwords for customers automatically when a new account is created. This code allows you choose the desired length and strength for the password and it is very flexible.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
function GeneratePassword($length=8, $strength=0){
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if($strength >= 1) $consonants .= 'BDGHJLMNPQRSTVWXZ';
if($strength >= 2) $vowels .= 'AEUY';
if($strength >= 3) $consonants .= '12345';
if($strength >= 4) $consonants .= '67890';
if($strength >= 5) $vowels .= '@#$%';

$password = '';
$alt = time() % 2;
for($i = 0; $i < $length; $i++){
if($alt == 1){
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
}else{
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}
?>
 

© 2014 4everTutorials. All rights resevered.

Back To Top