Showing posts with label php. Show all posts

Tutorial Get Users IP Address

by in , 0

Accounts for proxies:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
     $ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
     $ip=$_SERVER['REMOTE_ADDR'];
}

Reference URL

Tutorial Get Suffix of Given Number/Date

by in , 0

function get_suffix($number) {

   $last_number = substr($number,-1); //fetch the last number

   if($last_number == "0" || $last_number == 0){ $last_number = 4; } // if last number is 0 than it assign value 4
      return date("S",mktime(0,0,0,1,$last_number,2009));
}

Returns suffix of any number:
1 = st
2 = nd
3 = rd
4 = th
50 = th

Example: This is the 23rd coolest snippet ever.

Return date of month with appropriate suffix

function day_of_month(  ) {
        $number = date( 'j' );
        if ( $number[( strlen( $number ) - 1 )] == 1 ) {
                $suffix = "st";
        } elseif ( $number[( strlen( $number ) - 1 )] == 2 ) {
                $suffix = "nd";
        } elseif ( $number[( strlen( $number ) - 1 )] == 3 ) {
                $suffix = "rd";
        } else {
                $suffix = "th";
        }
        return array( "number" => $number, "suffix" => $suffix );
}

Function PHP Get Image Information

by in , 0

/*
 * @param string $file Filepath
 * @param string $query Needed information (0 = width, 1 = height, 2 = mime-type)
 * @return string Fileinfo
 */

function getImageinfo($file, $query) {
       if (!realpath($file)) {
               $file = $_SERVER["DOCUMENT_ROOT"].$file;
       }
       $image = getimagesize($file);
       return $image[$query];
}

PHP Get Geo-IP Information

by in , 0

Requests a geo-IP-server to check, returns where an IP is located (host, state, country, town).

<?php
       $ip='94.219.40.96';
       print_r(geoCheckIP($ip));
       //Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )

       //Get an array with geoip-infodata
       function geoCheckIP($ip)
       {
               //check, if the provided ip is valid
               if(!filter_var($ip, FILTER_VALIDATE_IP))
               {
                       throw new InvalidArgumentException("IP is not valid");
               }

               //contact ip-server
               $response=@file_get_contents('http://www.netip.de/search?query='.$ip);
               if (empty($response))
               {
                       throw new InvalidArgumentException("Error contacting Geo-IP-Server");
               }

               //Array containing all regex-patterns necessary to extract ip-geoinfo from page
               $patterns=array();
               $patterns["domain"] = '#Domain: (.*?)&nbsp;#i';
               $patterns["country"] = '#Country: (.*?)&nbsp;#i';
               $patterns["state"] = '#State/Region: (.*?)<br#i';
               $patterns["town"] = '#City: (.*?)<br#i';

               //Array where results will be stored
               $ipInfo=array();

               //check response from ipserver for above patterns
               foreach ($patterns as $key => $pattern)
               {
                       //store the result in array
                       $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
               }

               return $ipInfo;
       }

?>

PHP function Get File Size

by in , 0

/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function getFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
                       }
               return round($fileSize, $digits)." ".$sizes[$total];
       }
       return false;
}

Tutorial Get File Last Updated Date

by in , 0

/*
 * @param string $file Filepath
 * @param string $format dateformat
 * @link http://www.php.net/manual/de/function.date.php
 * @link http://www.php.net/manual/de/function.filemtime.php
 * @return string|bool Date or Boolean
 */

function getFiledate($file, $format) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
               $fileDate = filemtime($filePath);
               if ($fileDate) {
                       $fileDate = date("$format",$fileDate);
                       return $fileDate;
               }
               return false;
       }
       return false;
}

PHP Get FeedBurner Subscriber Count with cURL

by in , 0

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=7qkrmib4r9rscbplq5qgadiiq4');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
$content = curl_exec($ch);
$subscribers = get_match('/circulation="(.*)"/isU',$content);
curl_close($ch);

The $subscribers variable will then be your subscriber count, for echoing out (or whatever). You'll need to replace the ID at the end of the second line with your feed's ID (find it). You'll also need to have the Awareness feature of FeedBurner enabled.

Tutorial Get Current Page URL

by in , 0

function getUrl() {
  $url  = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] :  'https://'.$_SERVER["SERVER_NAME"];
  $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
  $url .= $_SERVER["REQUEST_URI"];
  return $url;
}

Tutorial Get Current File Name

by in , 0

<?php
    $pageName = basename($_SERVER['PHP_SELF']);
?>

Potential use:

<body id="body_<?php echo $pageName; ?>">

Append ID to body to do different CSS styles on different pages.

Tutorial Get All-Time Number of MySQL Queries

by in , 0

<?php
       $handle=@mysql_connect("localhost","root","");

       if (!$handle)
       {
               die("No connection to database");
       }

       echo 'Total number of all-time mysql-queries: '.getTotalNumberOfMySQLQuerys();


       //Returns integer-value of the total number of alltime mysql-calls that have been made
       function getTotalNumberOfMySQLQuerys()
       {
               //global mysql-status containing the number of querys has been renamed in newer versions of mysql
               $mysqlVersion=getMysqlVersion();

               //contact helper-function to receive the mysql-version
               if ($mysqlVersion()>=50002)
               {
                       $sql="SHOW GLOBAL STATUS LIKE 'Questions'";
               }
               else
               {
                       $sql="SHOW STATUS LIKE 'Questions'";
               }

               $result=@mysql_query( $sql );
               $row=@mysql_fetch_array( $result );
               return $row['Value'];
       }

       //helper function is needed to detect the exact mysql-version
       function getMysqlVersion()
       {
               $sql = 'SELECT VERSION() AS versionsinfo';
               $result = @mysql_query('SELECT VERSION() AS versionsinfo');
               $version = @mysql_result( $result, 0, "versionsinfo" );
               $match = explode('.',$version);
               return sprintf('%d%02d%02d',$match[0],$match[1],intval($match[2]));
       }
?>

Because the name of the global mysql-status-variable containing the number of queries changed in later versions of mysql, a helper-function is needed to detect the exact version of mysql you're running.

Tutorial Generate Expiring Amazon S3 Link

by in , 0

You don't have to make files on Amazon S3 public (they aren't by default). But you can generate special keys to allow access to private files. These keys are passed through the URL and can be made to expire.

<?php 

  if(!function_exists('el_crypto_hmacSHA1')){
    /**
    * Calculate the HMAC SHA1 hash of a string.
    *
    * @param string $key The key to hash against
    * @param string $data The data to hash
    * @param int $blocksize Optional blocksize
    * @return string HMAC SHA1
    */
    function el_crypto_hmacSHA1($key, $data, $blocksize = 64) {
        if (strlen($key) > $blocksize) $key = pack('H*', sha1($key));
        $key = str_pad($key, $blocksize, chr(0x00));
        $ipad = str_repeat(chr(0x36), $blocksize);
        $opad = str_repeat(chr(0x5c), $blocksize);
        $hmac = pack( 'H*', sha1(
        ($key ^ $opad) . pack( 'H*', sha1(
          ($key ^ $ipad) . $data
        ))
      ));
        return base64_encode($hmac);
    }
  }

  if(!function_exists('el_s3_getTemporaryLink')){
    /**
    * Create temporary URLs to your protected Amazon S3 files.
    *
    * @param string $accessKey Your Amazon S3 access key
    * @param string $secretKey Your Amazon S3 secret key
    * @param string $bucket The bucket (bucket.s3.amazonaws.com)
    * @param string $path The target file path
    * @param int $expires In minutes
    * @return string Temporary Amazon S3 URL
    * @see http://awsdocs.s3.amazonaws.com/S3/20060301/s3-dg-20060301.pdf
    */
    
    function el_s3_getTemporaryLink($accessKey, $secretKey, $bucket, $path, $expires = 5) {
      // Calculate expiry time
      $expires = time() + intval(floatval($expires) * 60);
      // Fix the path; encode and sanitize
      $path = str_replace('%2F', '/', rawurlencode($path = ltrim($path, '/')));
      // Path for signature starts with the bucket
      $signpath = '/'. $bucket .'/'. $path;
      // S3 friendly string to sign
      $signsz = implode("\n", $pieces = array('GET', null, null, $expires, $signpath));
      // Calculate the hash
      $signature = el_crypto_hmacSHA1($secretKey, $signsz);
      // Glue the URL ...
      $url = sprintf('http://%s.s3.amazonaws.com/%s', $bucket, $path);
      // ... to the query string ...
      $qs = http_build_query($pieces = array(
        'AWSAccessKeyId' => $accessKey,
        'Expires' => $expires,
        'Signature' => $signature,
      ));
      // ... and return the URL!
      return $url.'?'.$qs;
    }
  }

?>

Usage

<?php echo el_s3_getTemporaryLink('your-access-key', 'your-secret-key', 'bucket-name', '/path/to/file.mov'); ?>

Reference URL

Tutorial Generate CSV from Array

by in , 0

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
       $handle = fopen('php://temp', 'r+');
       foreach ($data as $line) {
               fputcsv($handle, $line, $delimiter, $enclosure);
       }
       rewind($handle);
       while (!feof($handle)) {
               $contents .= fread($handle, 8192);
       }
       fclose($handle);
       return $contents;
}

Usage

$data = array(
       array(1, 2, 4),
       array('test string', 'test, literal, comma', 'test literal "quotes"'),
);

echo generateCsv($data);
// outputs:
// 1,2,4
// "test string","test, literal, comma","test literal""quote"""

Tutorial Force Leading Zero

by in , 0

<?php
  function forceLeadingZero($int) {
    return (int)sprintf('%02d',$int);
  }
?>

Forces leading zero to integers.

was | now

1 | 01
2 | 02
3 | 03

10 | 10
100 | 100
99 | 99

Reference URL

Tutorial Find URLs in Text, Make Links

by in , 0

<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);

} else {

       // if no urls in the text just return the text
       echo $text;

}
?>

The basic function of this is to find any URLs in the block of text and turn them into hyperlinks. It will only find URLs if they are properly formatted, meaning they have a http, https, ftp or ftps.

Check out the comments below for more solutions.

PHP Define Full Path to a File

by in , 0

<?php
  echo dirname(__FILE__);
?>
Save the file as fullpath.php Upload to the folder you'd like to know the full path to Go to http://www.yoursite/lots/of/folders/fullpath.php

You'd might be surprised what shows up. Sometimes you need more than just /lots/of/folders/ as your full path to a file (e.g. .htpasswd). This script will allow you to see that.

Tutorial Find Highest Numerically Named File

by in , 0

$latest = getNewest("/path/to/folder/*_bla.xml");

function getNewest($xmlfile){
   foreach (glob($xmlfile) as $filename) {
       $c = explode('_', basename($filename));
       $files[$c[0]] = $filename;
   }
   ksort($files, SORT_NUMERIC);
   $latest = array_pop($files);
   if (file_exists($latest)){
       return $latest;
   }
   return false;
}

In a folder are files named:
1_bla.xml
2_bla.xml
...
34_bla.xml

The function returns the file with the biggest numeric number:
$latest = "/path/to/folder/34_bla.xml";

Tutorial Find File Extension

by in , 0

Method 1

function findexts ($filename) {

       $filename = strtolower($filename) ;

       $exts = split("[/\\.]", $filename) ;

       $n = count($exts)-1;

       $exts = $exts[$n];

       return $exts;

}

Method 2

$filename = 'mypic.gif';
$ext = pathinfo($filename, PATHINFO_EXTENSION);

Method 3

function getFileextension($file) {
       return end(explode(".", $file));
}

Preg Match All Links on a Page PHP

by in , 0

Here's the basic principal behind spiders.

$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
       echo $url.'<br />';
}

Tutorial Extract Email Addresses

by in , 0

Just pass the string (e.g. the body part of an email) to the function, and it returns an array of Email Addresses contained in the String.

function extract_emails_from($string) {
         preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
         return $matches[0];
}

If you catch the return value of function in $emails, you can parse it using foreach:

foreach($emails as $email) {
    echo trim($email).'<br/>';
}

Tutorial Error Page to Handle All Errors

by in , 0

This is a way to make a single error page for all errors, which is easier to update and maintain.

1) Point all error pages at one location in your .htaccess file

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php
etc.

2) PHP for error.php page in root

$status = $_SERVER['REDIRECT_STATUS'];
$codes = array(
       403 => array('403 Forbidden', 'The server has refused to fulfill your request.'),
       404 => array('404 Not Found', 'The document/file requested was not found on this server.'),
       405 => array('405 Method Not Allowed', 'The method specified in the Request-Line is not allowed for the specified resource.'),
       408 => array('408 Request Timeout', 'Your browser failed to send a request in the time allowed by the server.'),
       500 => array('500 Internal Server Error', 'The request was unsuccessful due to an unexpected condition encountered by the server.'),
       502 => array('502 Bad Gateway', 'The server received an invalid response from the upstream server while trying to fulfill the request.'),
       504 => array('504 Gateway Timeout', 'The upstream server failed to send a request in the time allowed by the server.'),
);

$title = $codes[$status][0];
$message = $codes[$status][1];
if ($title == false || strlen($status) != 3) {
       $message = 'Please supply a valid status code.';
}
// Insert headers here
echo '<h1>'.$title.'</h1>
<p>'.$message.'</p>';
// Insert footer here