Friday, December 28, 2012

New year Count Down in PHP

Happy New Year 2013 simple Count Down script in php
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$day = 1;
$month = 1;
$year = 2013; //change for next year
$end = mktime(0,0,0,$month,$day,$year);
$today= mktime(date("G"),date("i"),
date("s"),date("m"),date("d"),date("Y"));
$days=($end-$today)/86400;
if ($days>0) {
$r1 = explode('.',$days);
$hours=24*($days-$r1[0]);
$r2 = explode('.',$hours);
$minutes=60*($hours-$r2[0]);
$r3 = explode('.',$minutes);
$seconds=60*($minutes-$r3[0]);
$r4 = explode('.',$seconds);
echo 'Days left: ' .$r1[0];
echo '
Time left: ' . $r2[0] . ':' . $r3[0] . ':' . $r4[0];
} else {
echo "Happy new year 2013:)";}


?>

Monday, December 24, 2012

Website page rank php

Get the page rank of any website supported by Alexa with this simple function.

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


function page_rank($page, $type = 'alexa'){
switch($type){
case 'alexa':
$url = 'http://alexa.com/siteinfo/';
$handle = fopen($url.$page, 'r');
break;
case 'google':
$url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:';
$handle = fopen($url.'http://'.$page, 'r');
break;
}
$content = stream_get_contents($handle);
fclose($handle);
$content = preg_replace("~(\n|\t|\s\s+)~",'', $content);
switch($type){
case 'alexa':
if(preg_match('~\<div class=\"data (down|up)\"\>\<img.+?\>(.+?)\<\/div\>~im',$content,$matches)){
return $matches[2];
}else{
return FALSE;
}
break;
case 'google':
$rank = explode(':',$content);
if($rank[2] != '')
return $rank[2];
else
return FALSE;
break;
default:
return FALSE;
break;
}
}
// Alexa Page Rank:
echo 'Alexa Rank: '.page_rank('4evertutorials.blogspot.in');
echo '
';
// Google Page Rank
echo 'Google Rank: '.page_rank('4evertutorials.blogspot.in', 'google');


?>

Thursday, December 6, 2012

Preventing SQL Injections and Cross-Site Scripting

To secure your site from SQL Injections and Cross-Site Scripting you must validate every user input field. And don't forget about url adress, you must verify $_GET data, too. There is a simple way to do this, without checking every user input.

You can do all with this function:
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
//$arr array to be checked, $html - bool to allow html tags ...
or not
function safe($arr, $html = false)
{
if(!empty($arr))
{
foreach ($arr as $key => $value)
{
//if is array, then check it too
if(is_array($arr[$key]))
{
$arr[$key] = safe($arr[$key]);
}
else
{
//if HTML tags allowed, only securing SQL injections
if($html)
{
$arr[$key] = mysql_real_escape_string($value);
}
//else stripping out HTML characters and
//converting new line to 
and then securing from SQL injections
else
{
$value = nl2br(htmlspecialchars($value));
$arr[$key] = mysql_real_escape_string($value);
}
}
}
}
return $arr;
}



?>



Just put something like this in the beginning of your page $_GET = safe($_GET);

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

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...

";



?>

Thursday, September 20, 2012

Make clickable text to links: PHP

With this function you can make clickable text to links.
Function:

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

function dolinks($text)
{

$text = html_entity_decode($text);
$text = " ".$text;
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'\\1', $text);
$text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'\\1', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
'\\1\\2', $text);
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
'\\1', $text);
return $text;
}

// Example Usage
echo dolinks("This is a test clickable link: http://4evertutorials.blogspot.in/ You can also try using an email address like username@example.com");

?>

Wednesday, September 19, 2012

RSS Reader Class in PHP

What is RSS?
RSS stands for Really Simple Syndication or Rich Site Summary. RSS is used by (among other things) news websites, weblogs and podcasting. RSS feeds provide web content, or summaries of web content, together with links to the full versions of the content. RSS delivers this information as an XML file called an RSS feed, webfeed, RSS stream, or RSS channel. In addition to facilitating syndication, RSS feeds allow a website's frequent readers to track updates on the site as soon as they become available using an aggregator. The aggregator provides a consolidated view of the content in a single browser display or desktop application. Such aggregators or applications are also referred to as RSS readers, feed readers, feed aggregators or news readers.

Universal RSS Reader Class:

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
class RSSReader {
var $xml = null;
var $pos = 0;
var $count = 0;

function __construct($feed_url) {
$this -> load_url($feed_url);
}

function load_url($feed_url) {
$this -> load_string(file_get_contents($feed_url));
}

function load_string($feed_string) {
$this -> xml = simplexml_load_string(str_replace('content:encoded', 'content_encoded', $feed_string));
$this -> pos = 0;
$this -> count = count($this -> xml -> channel -> item);
}

function get_title() {
return $this -> xml -> channel -> title;
}

function get_link() {
return $this -> xml -> channel -> link;
}

function get_pubdate() {
return $this -> xml -> channel -> pubdate;
}

function hasNext() {
return $this -> count > $this -> pos;
}

function next() {
$obj = $this -> xml -> channel -> item[$this -> pos++];
return array(
'title' => (string) $obj -> title,
'link' => (string) $obj -> link,
'description' => (string) $obj -> description,
'content' => (string) $obj -> content_encoded,
'pubDate' => strtotime($obj -> pubDate),
);
}
}?>
Usage:
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$rss = new RSSReader('http://news.google.com/?output=rss');
while ($rss -> hasNext())
print_r($rss -> next());
?>

Thursday, September 6, 2012

Send a magic packet over the Internet with PHP

PHP function to send a magic packet over the Internet
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
flush();
function WakeOnLan($addr, $mac,$socket_number) {

$addr_byte = explode(':', $mac);
$hw_addr = '';
for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
// send it to the broadcast address using UDP
// SQL_BROADCAST option isn't help!!
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($s == false) {
echo "Error creating socket!\n";
echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
return FALSE;
}
else {
// setting a broadcast option to socket:
$opt_ret = socket_set_option($s, 1, 6, TRUE);
if($opt_ret <0) {
echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
return FALSE;
}
if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
echo "Magic Packet sent successfully!";
socket_close($s);
return TRUE;
}
else {
echo "Magic packet failed!";
return FALSE;
}
}
}

// Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
$socket_number = "9";
// MAC Address of the listening computer's network device
$mac_addy = "00:01:02:03:04:05"; 
// IP address of the listening computer. Input the domain name if you are using a hostname (like when under Dynamic DNS/IP)
$ip_addy = gethostbyname("my.computer.com");
WakeOnLan($ip_addy, $mac_addy,$socket_number)
?>

Composition of Variables


Amazing trick by PHP
You can use composition of variables. I don’t how it can be useful, but the following code is valid:
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

${‘a’ . ‘b’} = ‘c’;
echo $ab; // it will output c

?>

Recursive Directory Delete Function

Recursive Directory Delete Function
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
define('PATH', '/www/public/images/');

function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file
");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file
");
}
}
closedir($mydir);
}
destroy(PATH);
echo 'all done.';

?>

Thursday, August 30, 2012

How to hide PHP Notice and Warning Messages

How to hide PHP Notice & Warning Messages ?
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting(E_ALL);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

How you would encrypt decrypt

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. Still, here is how you would encrypt/decrypt
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

//To Encrypt
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

//To Decrypt:
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

echo 'Encrypted:' . "\n";
var_dump($encrypted); // "ey7zu5zBqJB0rGtIn5UB1xG03efyCp+KSNR4/GAv14w="

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "

?>

Simple PHP Function to Detect Mobile Users

Simple PHP Function to Detect Mobile Users: iPhone, iPad, Blackberry & Android
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

if( !function_exists('mobile_user_agent_switch') ){
function mobile_user_agent_switch(){
$device = '';

if( stristr($_SERVER['HTTP_USER_AGENT'],'ipad') ) {
$device = "ipad";
} else if( stristr($_SERVER['HTTP_USER_AGENT'],'iphone') || strstr($_SERVER['HTTP_USER_AGENT'],'iphone') ) {
$device = "iphone";
} else if( stristr($_SERVER['HTTP_USER_AGENT'],'blackberry') ) {
$device = "blackberry";
} else if( stristr($_SERVER['HTTP_USER_AGENT'],'android') ) {
$device = "android";
}

if( $device ) {
return $device; 
} return false; {
return false;
}
}
}

?>

date_sun_info

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

array date_sun_info ( int $time , float $latitude , float $longitude )

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

$northernmost_city_latitude = 78.92; // Ny-Ã…lesund, Svalbard
$northernmost_city_longitude = 11.93;
$southernmost_city_latitude = -77.88; // McMurdo Research Station, Antarctica
$southernmost_city_longitude = 166.73;

print_r( date_sun_info( strtotime("2008-01-01") , $northernmost_city_latitude, $northernmost_city_longitude) );
print_r( date_sun_info( strtotime("2008-04-01") , $northernmost_city_latitude, $northernmost_city_longitude) );
print_r( date_sun_info( strtotime("2008-01-01") , $southernmost_city_latitude, $southernmost_city_longitude) );
print_r( date_sun_info( strtotime("2008-06-01") , $southernmost_city_latitude, $southernmost_city_longitude) );

?>

Increase PHP Script Execution Time Limit

Every once in a while I need to process a HUGE file. Though PHP probably isn't the most efficient way of processing the file, I'll usually use PHP because it makes coding the processing script much faster. To prevent the script from timing out, I need to increase the execution time of the specific processing script. Here's how I do it.


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

ini_set('max_execution_time', 300); //300 seconds = 5 minutes
set_time_limit(0);//no limit

?>

Monday, August 6, 2012

Create Dynamic Radio Group (HTML) with PHP

Creating radio elements in some content management systems can result into writing a lot of code. Just in case your radio group with multiple options is getting a value from a database and/or a form. There need to be a check for every posted value for every option. This function will do all this work for you, just create two arrays, one for the values and labels and for the related html code. It's up to the user if he uses 2 or more elements in one group. The function works with $_POST and $_GET data.

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

$values = array('google'=>'Google Search', 'link'=>'Link on some website', 'advert'=>'Advertisement', 'news'=>'News');
$html_elements = array('before'=>'', 'after'=>'
', 'label'=>'
');

function radioGroup($formelement, $values, $html, $def_value = '') {
    $radio_group = '
'."\n"; $radio_group .= (!empty($html['label'])) ? $html['label']."\n" : ''; if (isset($_REQUEST[$formelement])) { $curr_val = stripslashes($_REQUEST[$formelement]); } elseif (isset($def_value) && !isset($_REQUEST[$formelement])) { $curr_val = $def_value; } else { $curr_val = ""; } foreach ($values as $key => $val) { $radio_group .= $html['before']."\n"; $radio_group .= '' : ' />'; $radio_group .= ' '.$val."\n".$html['after']."\n"; } $radio_group .= '
'."\n"; return $radio_group; } // place this code between the form tags: // notice 'advert' could be a database value too echo radioGroup('test', $values, $html_elements, 'advert'); ?>

Saturday, July 28, 2012

Advanced PHP session start

If a session based web application is used by a visitor using Internet Explorer it's possible that this user get some trouble. This will happen if parts of the application are accessed for example via a shortcut on the desktop and the application opens then in a new Explorer window. At this moment a second session is started with a different ID, if the used web application has some session based authentication system the user has to login again. At the same time the user has to logout twice! In browsers like Mozilla Firefox new windows are treated the same way then tabs where the problem doesn't exists. This function will use a real cookie for the session ID and updates the expiration time with every script execution. The expiration is equal to the PHP directive "gc_maxlifetime" (default) or every custom value.

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

// $expire = the time in seconds until a session have to expire
function start_session($expire = 0) {
    if ($expire == 0) {
        $expire = ini_get("session.gc_maxlifetime");
    } else {
        ini_set("session.gc_maxlifetime", $expire);
    }
    if (empty($_COOKIE['PHPSESSID'])) {
        session_set_cookie_params($expire);
        session_start();
    } else {
        session_start();
        setcookie("PHPSESSID", session_id(), time() + $expire);
    }
}
// this example will start a session with an expire time given by the php configuration
start_session();
// start_session(600) will start a session which will expire after 10 minutes (60*10 seconds)
?>



Friday, July 27, 2012

Five Steps to Secure your PHP Website


Unfortunately there will always be some one out there on the world wide web who will attempt to break any thing they can find on the Internet so you owe it to your visitors/ members to ensure nothing malicious is being hidden on your site and there info isn't being stolen. In this article i will cover 5 important steps you need to take to make sure your web site's secure.

MySQL Injection

Every single piece of user inputted data should be treated as if it was an attack on your script. When running MySQL queries if you don't treat user inputted data before using it in the query a hacker could cause you a number of problems, for example.

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

$sql = mysql_query("SELECT FROM users WHERE username = '". $_POST["username"] ."' && password = '". $_POST["password"] ."');


?>

Lets say you were using this code to allow users to login, What if instead of a user entering a password they entered ' OR username = 'admin then the query would look like this.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$sql = mysql_query("SELECT FROM users WHERE username = '' && password = '' OR username = 'admin'");


?>

They would now be logged in as the admin and gain access to all your administrative tools. Using this method of exploitation hackers would also be able to delete records, force errors and all sorts. So to prevent this we use a php function called mysql_real_escape_string, so before using this user inputted data in our query we would simply do this.

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

$username = mysql_real_escape_string( $_POST["username"] );
$password = mysql_real_escape_string( $_POST["password"] );

$sql = mysql_query("SELECT FROM users WHERE username = '". $username ."' && password = '". $password .'");


?>

mysql_real_escape_string is a MySQL function which prepends backslashes to the following characters x00, n, r, , ', " and x1a.

CSRF Attacks

CSRF pronounced sea-surf is an abbreviation of "Cross Site Request Forgery". The basic principal behind CSRF attacks is instead of gaining access to a site's control's forcing actions on a user, for example.

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

echo '
';


?>

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

if( logged_in() == false ) {
 // User not logged in
 die();
}
// User logged in
$page_id = mysql_real_escape_string( $_GET["page_id"] );
$query = mysql_query("DELETE FROM pages WHERE page_id = '". $page_id ."'");


?>

Lets say this was part of your script and you as an admin used it to delete pages, Now obviously if a hacker were to visit this page they wouldn't be able to do any thing because we have a check at the very top to see if the user is logged in or not. But if you were logged in and then some one told you to visit a web page and on that page was an image like this.


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




?>

You would have just deleted what ever page had the id "20" to fix this issue its very simple all you need to do is use tokens so on pages.php you would generate a unique id and set it as a session and then you would check for that id on delete.php if they don't match then kill the script.


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

session_start();
$id = md5(uniqid(mt_rand(), true));
$_SESSION["token"] = $id;
echo '
';


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

if( logged_in() == false ) {
 // User not logged in
 die();
}
// User logged in
$page_id = mysql_real_escape_string( $_GET["page_id"] );
$token = mysql_real_escape_string( $_GET["token"] );
if( $_GET["token"] != $_SESSION["token"] ) {
 die();
}
$query = mysql_query("DELETE FROM pages WHERE page_id = '". $page_id ."'");


?>

Using this simple solution we can prevent CSRF attacks and prevent a number of security issues.


XSS Attacks

XSS (Cross site scripting) can cause web site's huge problems. The general idea of XSS is embedding code on your web site without you know which will cause your visitors to download something they don't want to. For example if you had a comment system on your web site and no checks were run on comments being posted any one could come along and make a comment like this.

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


What a wonderful news entry


?>

Now all you would see is "What a wonderful news entry" but that comment could be doing all sorts such as collecting cookie information off your visitors, downloading viruses onto their computers and so on. Luckily we have a simple fix for this, When you are about to save the comment in your database you should of course escape the comment text to prevent mysql injections but also you should use htmlspecialchars this will stop any bad code making it into your comments or other user posted data by changing characters such as < into their html codes e.g <.

Script functionality

This may be pretty obvious but i've seen a number of web site's that function poorly thus making there service less secure for their users. For example a user should not be able to attempt to login hundreds of times if they keep getting there password wrong, After about 5 attempts they should be frozen out for about 15 mins. If you are building a "forgot your password" facility into your script then by entering there username, email address and date of birth they should not be able to recover their password to another email address. You should also force people to enter a captcha when they are leaving a comment or post on your web site to make sure you don't have problems with bots and if they are posting any thing on your site they should have to wait at least 30 seconds between posts to stop people trying to crash your site by getting a bot to submit thousands of comments at once.

Error reporting

If there is an issue with your web site, The last person in the world you want knowing about it is a potential hacker because there is a chance that error could lead them to a way to exploit your script. So make sure that any script you put live you turn error reporting off.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

error_reporting(0);


?>

Now if your script throws any sort of error at you it will not be seen by your users.

I hope this tutorial has helped you understand some of the vital measures that must be taken to stop hackers ripping your web sites to pieces.
  



Friday, July 20, 2012

Find visitor's IP address in php script

Every php developer want to store IP address of visitor for tracking and other different purpose. Here is the function which i'm using in my script to store ip address in database.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
function visitorIPAdd()
{
/*
This returns the IP of the visitor calling the requested page
Checks to see if HTTP_X_FORWARDED_FOR has a value then the client is operating via a proxy
*/
       $visitorIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
       if($visitorIP == "")
      { 
         $visitorIP = $_SERVER['REMOTE_ADDR'];  
      }

      return $visitorIP;       // return the IP address
}
?>

Saturday, July 14, 2012

Remove HTML Tags from string in PHP

If your strings have any html code, you can easily remove using following code.

Using regular expression:

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

$string = preg_replace("/<.*?>/", "", $string_contain_html_code);


?>

Stop SQL Injection in MYSQL with PHP Script


Every PHP-MYSQL programmer need to know Anti-SQL Injection. Please take a look at very simple function which can save your database!!

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


function ClearInput($dirtyInput){
 
 if (get_magic_quotes_gpc()) {
 
 $clean = mysql_real_escape_string(stripslashes($dirtyInput));
 
 }else{
 
 $clean = mysql_real_escape_string($dirtyInput);
 
 }
 return $clean;
 
}

?>

Post XML data using CURL php


Recently I was working in a hotel booking engine and found a couple of methods to post XML to server; I thought this might be good to share with my friends who want to post xml via HTTP POST method.
There are several ways to Send XML requests via HTTP POST. I am going to show you post XML data using CURL 
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$xml_data =''.
    ''.
        '1234567890'.
        'lgsoftwares'.
        'mypassword'.
        'example.com'.
    ''.
    ''.
        ''.
        ''.
    ''.
''.
'JHM'.
        'OGGSHE'.
        '101009'.
        '101509'.
        '1'.
  ''.  
  '';
 
 
$URL = "https://www.yourwebserver.com/path/";
 
   $ch = curl_init($URL);
   curl_setopt($ch, CURLOPT_MUTE, 1);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
   curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $output = curl_exec($ch);
   curl_close($ch);
 
?>

Friday, July 13, 2012

Prevent XSS attacks with php

There are a number of ways hackers put to use for XSS attacks, PHP’s built-in functions do not respond to all sorts of XSS attacks. Hence, functions such as strip_tags, filter_var, mysql_real_escape_string, htmlentities, htmlspecialchars, etc do not protect us 100%. You need a better mechanism, here is what is solution:

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data);
$data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
 
// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
 
// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
 
// Only works in IE: 
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
 
// Remove namespaced elements (we do not need them)
$data = preg_replace('#]*+>#i', '', $data);
 
do
{
        // Remove really unwanted tags
        $old_data = $data;
        $data = preg_replace('#]*+>#i', '', $data);
}
while ($old_data !== $data);
 
// we are done...
return $data;
}

?>

Tuesday, July 10, 2012

Post or Submit Form Data with PHP CURL

Last Sunday, I was working with website form to collect data from third party website. If you have to just submit form its easy website does not restrict to use CURL in order to post data but my requirement was to post website from data and store that data in my database too. This is easy and simple and has a lot of ways to do.

Now I would like to show you PHP CURL way to post form data. You can use PHP Jquery and Ajax to make it more fancy. But I want to keep it simple.

Step 1 -
I am using one sales force form as example.
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

<form action="curl.php" method="POST">
<input type=hidden name="oid" value="70D400000009mU7">
<input type=hidden name="retURL" value="http://www.site.com/thankyou.html">
<label for="first_name">First Name</label><input  id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br>
<label for="last_name">Last Name</label><input  id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br>
<label for="street">Address</label><textarea name="street"></textarea><br>
<label for="city">City</label><input  id="city" maxlength="40" name="city" size="20" type="text" /><br>
<label for="zip">Zip</label><input  id="zip" maxlength="20" name="zip" size="20" type="text" /><br>
<label for="email">Email</label><input  id="email" maxlength="80" name="email" size="20" type="text" /><br>
<label for="phone">Phone</label><input  id="phone" maxlength="40" name="phone" size="20" type="text" /><br>
<input type="submit" name="submit">
</form>

Step 2  - 
This is standard PHP CURL script (curl.php) to post from you can use anywhere without any modification in from you can add more fields if you need.

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

//Initialize the $query_string variable for later use
$query_string = "";
 
//If there are POST variables
if ($_POST) {
 
//Initialize the $kv array for later use
$kv = array();
 
//For each POST variable as $name_of_input_field => $value_of_input_field
foreach ($_POST as $key => $value) {
 
//Set array element for each POST variable (ie. first_name=lakhsidhu)
$kv[] = stripslashes($key)."=".stripslashes($value);
 
}
 
//Create a query string with join function separted by &
$query_string = join("&", $kv);
}
//Check to see if cURL is installed ...
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
 
//The original form action URL from Step 2 :)
$url = 'https://www.site.com/path.php';
 
//Open cURL connection
$ch = curl_init();
 
//Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
 
//Set some settings that make it all work :)
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
 
//Execute SalesForce web to lead PHP cURL
$result = curl_exec($ch);
 
//close cURL connection
curl_close($ch);
if($result=='ok')
{
echo '<script>alert("Posted -- ")</script>';
}
// Here you can write mysql query to insert data in table.
 
$insert_tbl_index_page= "insert into tbl_form_data(first_name,last_name,street,city,zip,phone,email)values('$first_name','$last_name','$street','$city','$zip','$phone','$email')";

?>



Sunday, July 1, 2012

Connecting to ODBC using PHP



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


// connect to a DSN "database" with a user and password "4evertutorials"
$connect = odbc_connect("database", "4evertutorials", "4evertutorials");


// query the users table for name and surname
$query = "SELECT name, surname FROM users";



// perform the query
$result = odbc_exec($connect, $query);



// fetch the data from the database

while(odbc_fetch_row($result))
{
  $name = odbc_result($result, 1);
  $surname = odbc_result($result, 2);
  print("$name $surname\n");

}


// close the connection
odbc_close($connect);

?>

Get Unique Value from PHP Array

array_unique()

array_unique — Removes duplicate values from an array

Description:

Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

Example:

/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$_input = array("a" => "1", "2", "3" => "1", "2", "3");
$result = array_unique($_input);
print_r($result);


Result:

Array
(
  [a] => 1
  [0] => 2
  [2] => 3
)
?>
 

Wednesday, June 27, 2012

Create PHP Image Gallery with MySQL Blob Field

This is a simple example of photo-gallery script, which uses MySQL table (BLOB field) to store images. Trivial password-protection, uploading and deleting images are supported.

There are three main parts of the script:
  • main page generation --
    generates HTML code for the list of uploaded photos, forms for photo deletion and uploading
  • image uploading --
    processes POST request: checks password, uploads photo to database or deletes it
  • image showing --
    Fetches image information from MySQL database and sends image do browser. If PHP is installed as mod_php (for Apache), does If-Modified-Since HTTP header checking.

Create MySQL / SQL Table

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

CREATE TABLE `gallery` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) character SET utf8 NOT NULL,
  `ext` varchar(8) character SET utf8 NOT NULL,
  `image_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `data` mediumblob NOT NULL,
  PRIMARY KEY  (`id`) 
);



You can use any name for this table, just change $table variable at the begining of the image gallery code.
We use following functions in this example:


MySQL
  • mysql_connect - connects to MySQL server
  • mysql_select_db - select database
  • mysql_query - send query
  • mysql_fetch_row - get current row from result table
  • mysql_real_escape_string - escaping string to use it in MySQL query
  • mysql_num_fields - get number of rows
PHP
  • get_magic_quotes_gpc - checking if PHP add slashes before quotes in input parameters
  • stripslashes - remove odd slashes
  • trim - remove unnecessary spaces in the beginning and ending of string
  • getimagesize - return image information as an array. Third element of array -- image type.
  • file_get_contents - loads whole file into memory
  • php_sapi_name - returns the name of PHP Server API
  • apache_request_headers - gets some special header information from Apache
  • strtotime - convert textual representation of time to integer (number of seconds since 1970)
  • header - sends HTTP header to browser
Before using following example create sql-table (execute CREATE TABLE query above) and change variables ($db_host, $db_user, $db_pwd, $database, $table) to your MySQL / database settings.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/
$db_host = 'localhost';  
$db_user = 'username'; 
$db_pwd = 'password';

$database = 'test';
$table = 'gallery'; // use the same name as SQL table

$password = 'pass7';
// simple upload restriction,
// to disallow uploading to everyone


if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // cleaning title field
    $title = trim(sql_safe($_POST['title']));

    if ($title == '') // if title is not set
        $title = '(empty title)';// use (empty title) string

    if ($_POST['password'] != $password)  // cheking passwors
        $msg = 'Error: wrong upload password';
    else
    {
        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion


        if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $id = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE id=$id");
            $msg = 'Photo deleted';
        }
    }
}
elseif (isset($_GET['show']))
{
    $id = intval($_GET['show']);

    $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data
                             FROM {$table}
                            WHERE id=$id LIMIT 1");

    if (mysql_num_rows($result) == 0)
        die('no image');

    list($ext, $image_time, $data) = mysql_fetch_row($result);

    $send_304 = false;
    if (php_sapi_name() == 'apache') {
        // if our web server is apache
        // we get check HTTP
        // If-Modified-Since header
        // and do not send image
        // if there is a cached version

        $ar = apache_request_headers();
        if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
            ($ar['If-Modified-Since'] != '') && // not empty
            (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than
            $send_304 = true;                                     // image_time
    }


    if ($send_304)
    {
        // Sending 304 response to browser
        // "Browser, your cached version of image is OK
        // we're not sending anything new to you"
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

        exit(); // bye-bye
    }

    // outputing Last-Modified header
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT',
            true, 200);

    // Set expiration time +1 year
    // We do not have any photo re-uploading
    // so, browser may cache this photo for quite a long time
    header('Expires: '.gmdate('D, d M Y H:i:s',  $image_time + 86400*365).' GMT',
            true, 200);

    // outputing HTTP headers
    header('Content-Length: '.strlen($data));
    header("Content-type: image/{$ext}");

    // outputing image
    echo $data;
    exit();
}
?>
<html><head>
<title>Create PHP Image Gallery with MySQL Blob Field</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br>
<a href="<?=$PHP_SELF?>">reload page</a>
<!-- I've added reloading link, because
     refreshing POST queries is not good idea -->
</p>
<?php
}
?>
<h1>PHP-MySQL Image Gallery</h1>
<h2>Uploaded images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($id, $image_time, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' value='{$id}'>";
        echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – ";
        echo "<small>{$image_time}</small></li>";
    }

    echo '</ul>';

    echo '<label for="password">Password:</label><br>';
    echo '<input type="password" name="password" id="password"><br><br>';

    echo '<input type="submit" value="Delete selected">';
}
?>

</form>
<h2>Upload new image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title">Title:</label><br>
<input type="text" name="title" id="title" size="64"><br><br>

<label for="photo">Photo:</label><br>
<input type="file" name="photo" id="photo"><br><br>

<label for="password">Password:</label><br>
<input type="password" name="password" id="password"><br><br>

<input type="submit" value="upload">
</form>
</body>
</html>


Friday, June 22, 2012

How to Unzip Zip file in PHP


If you dont have access or cpanel access to your server and need to unzip an archive of zip file on your php server. You can use the script below to unzip files on your server using php:
$_ZIP_FILE = zip_open('file.zip');
while ($zip_entry = zip_read($_ZIP_FILE)) 
{
 $name = zip_entry_name($zip_entry);
 if (substr($name, -1) == '/') {
  mkdir($destination . $name);
 } else {
  $fh = fopen('zip/' . $name, 'w');
  if (zip_entry_open($_ZIP_FILE, $zip_entry, 'r')) {
   $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
   fwrite($fh, $buf);
   zip_entry_close($zip_entry);
  }
  fclose($fh);
 }
}
zip_close($_ZIP_FILE);

Above script will extract all the contents of the zip archive in the target directory, so no worries when you have no cpanel or shell access. We still have solution for your problem

Code Treasury

Ads

Contact Us

Name

Email *

Message *

Ads

Powered by Blogger.
 

© 2014 4everTutorials. All rights resevered.

Back To Top