Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

How to find cuntry by IP address



function getLocationInfoByIp($ip_addr)
{
    return $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip_addr));
}

$ap_address  =  $_SERVER['REMOTE_ADDR'];
$location_info = getLocationInfoByIp($ap_address);
echo '<pre>';
print_r($location_info);
echo '</pre>';

stdClass Object
(
    [geoplugin_request] => 103.4.146.186
    [geoplugin_status] => 200
    [geoplugin_credit] => Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.
    [geoplugin_city] => Dhaka
    [geoplugin_region] => Dhaka
    [geoplugin_areaCode] => 0
    [geoplugin_dmaCode] => 0
    [geoplugin_countryCode] => BD
    [geoplugin_countryName] => Bangladesh
    [geoplugin_continentCode] => AS
    [geoplugin_latitude] => 23.7231
    [geoplugin_longitude] => 90.4086
    [geoplugin_regionCode] => 81
    [geoplugin_regionName] => Dhaka
    [geoplugin_currencyCode] => BDT
    [geoplugin_currencySymbol] => Tk
    [geoplugin_currencySymbol_UTF8] => Tk
    [geoplugin_currencyConverter] => 79.4502
)

================================

function ip_details($ap_address)
{
    $json       = file_get_contents("http://ipinfo.io/{$ap_address}");
    $details    = json_decode($json);
    return $details;
}

$ap_address  =  $_SERVER['REMOTE_ADDR'];
$details    =   ip_details($ap_address);
echo '<pre>';
print_r($details);
echo '</pre>';

stdClass Object
(
    [ip] => 103.4.146.186
    [hostname] => No Hostname
    [city] => Dhaka
    [region] => Dhaka Division
    [country] => BD
    [loc] => 23.7231,90.4086
    [org] => AS9441 Next Online Ltd.
    [postal] => 1000
)

$ip = '141.168.138.15'; // Victoria/Melbourne
$ip = '49.197.229.133'; // Queensland/Brisbane
$ip = '114.141.196.226'; // New South Wales/Sydney
$ip = '58.108.79.123'; // Western Australia/Perth

PHP attach mail

 function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/html; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}

$my_file = "company-logo.png";
$my_path = '/var/www/html/bitmascotv3/wp-content/themes/webalive/images/'; // directory path
$my_name = "Iman Ali";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Test <b>Message</b>";
mail_attachment($my_file, $my_path, "iman@bitmascot.com", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);

Youtube Vimeo programming

<?php
 
  $url= 'http://vimeo.com/59026775';          
$url= 'https://youtu.be/wByp5d4IutM';
$url = 'https://www.youtube.com/watch?v=SbGFYjCbpRs';

$type = getTypeByURL($url);
$code = getCodeByURL($url);

$size ='';
if($type == 'youtube'){
    $size = 0;
}else{
    $size = 'large';
}

$thumbnail_url = getThumbnailByVideoURL($code, $type, $size);

function getTypeByURL($url){

    if(strstr($url, 'v=') || strpos($url, 'youtube.com') || strpos($url, 'youtu.be')){
        $type = 'youtube';
    }elseif(strpos($url, 'vimeo.com')){
        $type = 'vimeo';
    }
    return $type;
}

function getCodeByURL($url){

    if(strstr($url, 'v=')){
        $queryString = parse_url($url, PHP_URL_QUERY);
        parse_str($queryString, $params);
        $code = $params['v'];
    }else{
        $video_explode = explode('/', $url);
        $code = $video_explode[sizeof($video_explode)-1];
    }

    return $code;
}


function getThumbnailByVideoURL($code, $type = '', $size = ''){
    $thumbnail_url = '';
     if($type =='youtube'){
         $thumbnail_url = "https://i3.ytimg.com/vi/".$code."/".$size.".jpg";
     }elseif($type =='vimeo'){
         $thumbnail_info = unserialize(file_get_contents("https://vimeo.com/api/v2/video/$code.php"));
         if(!empty($thumbnail_info)){
             $thumbnail_url = $thumbnail_info[0]['thumbnail_'.$size];
         }
     }
    return $thumbnail_url;
}

    ?>
    <iframe width="750" height="400" src="https://www.youtube.com/embed/<?php echo $code; ?>" frameborder="0" allowfullscreen></iframe>

<iframe src="https://player.vimeo.com/video/189483103" width="640" height="1138" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
   
   
function showVideo(code){
jQuery('#video_frame').html('<iframe width="750" height="400" src="https://www.youtube.com/embed/'+code+'" frameborder="0" allowfullscreen></iframe>');
jQuery('.vimeo_video_wrapper').show();
jQuery('.close_video').show();
}
function closeVideo(){
jQuery('#video_frame').html('');
jQuery('.vimeo_video_wrapper').hide();
jQuery('.close_video').hide();
}

<div class="play_icon"><a href="javascript:" onclick="showVideo('<?php echo $video_code; ?>')">Play</a></div>
                        <img src="<?php echo $thumb; ?>" title="<?php echo $video->title; ?>" alt="<?php echo $video->title; ?>">

.vimeo_video_wrapper{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
z-index: 555;
display: none;
}
.vimeo_video_container{
left: 50%;
margin: -200px auto 0 -375px;
position: fixed;
top: 50%;
width: 750px;
z-index: 5000;
}
.vimeo_video_container .close_video{
position:absolute;
z-index:500;
right:-16px;
top:-16px;
}

Custom Next Previous / Next Prev

$career = $career_obj->getCareerById($id);
$careers = $career_obj->getCareers();
$career_ids = array();
if(!empty($careers)){
$count = 0;
foreach ($careers as $c){
$count++;
$career_ids[$count] = $c->ID;
}
}

$current_id = $career->ID;
$current_position = array_search($current_id, $career_ids);
$first_position = 1;
$last_position = sizeof($career_ids);

if($current_position==$first_position && $current_position==$last_position){
$next_position = $current_position;
$prev_position = $current_position;
}elseif($current_position==$first_position){
$next_position = $current_position + 1;
$prev_position = $last_position;
}elseif($current_position==$last_position){
$next_position = $first_position;
$prev_position = $current_position - 1;
}else{
$next_position = $current_position + 1;
$prev_position = $current_position - 1;
}

$next_item = $career_obj->getCareerById($career_ids[$next_position]);
$prev_item = $career_obj->getCareerById($career_ids[$prev_position]);

$next_link = home_url('/careers-details/'.$next_item->slug);
$prev_link = home_url('/careers-details/'.$prev_item->slug);

CSV Export

<?php

$data[] = array(
    'Name' => 'Iman',
    'Product Type' => 'Pulse, Energy Broking'    
);

$data[] = array(
    'Name' => 'Alvee',
    'Product Type' => 'Aa, Energy Broking'        
);

tocsv($data);

function tocsv($data, $filename='students.csv')
    {
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=".$filename);
        header("Pragma: no-cache");
        header("Expires: 0");

        $result = "";
        if (count($data) > 0) {
            $keys = array_keys($data[0]);
            $first = true;
            foreach ($keys as $key) {
                if (!$first) {
                    $result .= ",";
                }
                $key = str_replace("}", "|", $key);
                $key = str_replace("{", "|", $key);
                $key = str_replace(",", "|", $key);
                $key = trim($key);
                $result .= $key;
                $first = false;
            }
            foreach ($data as $row) {
                $result .= "\n";
                $first = true;
                foreach ($row as $col) {
                    if (!$first) {
                        $result .= ",";
                    }
                    $col = str_replace("}", "|", $col);
                    $col = str_replace("{", "|", $col);
                    $col = str_replace(",", "|", $col);
                    $col = trim($col);
                    $result .= "{$col}";
                    $first = false;
                }
            }
        }
        echo $result;
    }

File download

<?php 
function download($abspath)
    {

        $file = basename($abspath);

        if (!is_file($abspath)) {
            return false;
        }

        //get filesize and extension
        $size     = filesize($abspath);
        $ext     = strtolower(getExt($abspath));

        // required for IE, otherwise Content-disposition is ignored
        if(ini_get('zlib.output_compression')) {
            ini_set('zlib.output_compression', 'Off');
        }

        switch( $ext )
        {
            case "pdf":
                $ctype = "application/pdf";
                break;
            case "exe":
                $ctype="application/octet-stream";
                break;
            case "rar":
            case "zip":
                $ctype = "application/zip";
                break;
            case "txt":
                $ctype = "text/plain";
                break;
            case "doc":
                $ctype = "application/msword";
                break;
            case "xls":
                $ctype = "application/vnd.ms-excel";
                break;
            case "ppt":
                $ctype = "application/vnd.ms-powerpoint";
                break;
            case "gif":
                $ctype = "image/gif";
                break;
            case "png":
                $ctype = "image/png";
                break;
            case "jpeg":
            case "jpg":
                $ctype = "image/jpg";
                break;
            case "mp3":
                $ctype = "audio/mpeg";
                break;
            default:
                $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");
        //quotes to allow spaces in filenames
        header("Content-Disposition: attachment; filename=\"".$file."\";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".$size);
        ob_clean();
        flush();
        readfile($abspath);

        return true;
    }

function getExt($file) {
$ext = trim(substr($file,strrpos($file,".")+1,strlen($file)));
return $ext;
}

Read more

function readMore($content, $word_limit=50, $link = false){
    $content = strip_tags($content);
    $explode_content = explode(" ", $content);
    if(sizeof($explode_content)>$word_limit){
        $slice_content = array_slice($explode_content, 0, $word_limit);
        $content = implode(" ", $slice_content);
        if($link){
            $content .=' <span class="read-more"><a href="'.get_permalink().'">Read more</a></span>';
        }
    }
    return $content;
}

Mobile detection php

<?php
if(! empty($_SERVER['HTTP_USER_AGENT'])){
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    if( preg_match('@(iPad|iPod|iPhone|Android|BlackBerry|SymbianOS|SCH-M\d+|Opera Mini|Windows CE|Nokia|SonyEricsson|webOS|PalmOS)@', $useragent) ){
        header('Location: ./mobile/');
    }
}
?>

Including remove files in php

http://php.net/manual/en/features.remote-files.php

http://stackoverflow.com/questions/1158348/including-a-remote-file-in-php

To allow inclusion of remote files, the directive allow_url_include must be set to On in php.ini
But it is bad, in a security-oriented point of view ; and, so, it is generally disabled (I've never seen it enabled, actually)
It is not the same as allow_url_fopen, which deals with opening (and not including) remote files -- and this one is generally enabled, because it makes fetching of data through HTTP much easier (easier than using curl)

To use remote includes, the allow_url_fopen and allow_url_include option must be set in php.ini
Be aware that if the remote server is php-enabled, you'll get the output of that remote script, not the script itself. If you do want to fetch the source, you could add a symlink on the remote server, e.g. ln -s file.php file.php.source and then make your include reference file.php.source instead.

http://blog.kotowicz.net/2010/07/hardening-php-how-to-securely-include.html 

PHP include from another server

<?php
      echo implode(file("http://server.com/dir/file.html"));
?>

Zip unzip in php

 Zip a filter


<?php



class HZip
{
    /**
     * Add files and sub-directories in a folder to zip file.
     * @param string $folder
     * @param ZipArchive $zipFile
     * @param int $exclusiveLength Number of text to be exclusived from the file path.
     */
    private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
        $handle = opendir($folder);
        while (false !== $f = readdir($handle)) {
            if ($f != '.' && $f != '..') {
                $filePath = "$folder/$f";
                // Remove prefix from file path before add to zip.
                $localPath = substr($filePath, $exclusiveLength);
                if (is_file($filePath)) {
                    $zipFile->addFile($filePath, $localPath);
                } elseif (is_dir($filePath)) {
                    // Add sub-directory.
                    $zipFile->addEmptyDir($localPath);
                    self::folderToZip($filePath, $zipFile, $exclusiveLength);
                }
            }
        }
        closedir($handle);
    }

    /**
     * Zip a folder (include itself).
     * Usage:
     *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
     *
     * @param string $sourcePath Path of directory to be zip.
     * @param string $outZipPath Path of output zip file.
     */
    public static function zipDir($sourcePath, $outZipPath)
    {
        $pathInfo = pathInfo($sourcePath);
        $parentPath = $pathInfo['dirname'];
        $dirName = $pathInfo['basename'];

        $z = new ZipArchive();
        $z->open($outZipPath, ZIPARCHIVE::CREATE);
        //$z->addEmptyDir($dirName);
        //self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
        self::folderToZip($sourcePath, $z, strlen("$sourcePath/"));
        $z->close();
    }

    public static function zipToUnzip($zipFile, $destination)
    {
        $zip = new ZipArchive;
        $res = $zip->open($zipFile);
        if ($res === TRUE) {
            $zip->extractTo($destination);
            $zip->close();
        }
    }
}

?>

CURL

http://phpenthusiast.com/blog/five-php-curl-examples

Download a file using curl in php
<?php
set_time_limit(0);
//File to save the contents to
$fp = fopen ('files2.tar', 'w+');
$url = "http://localhost/files.tar";

//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);

//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);//get curl response
//done
curl_close($ch);
?>
============================
<?php
set_time_limit(0);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the    information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);
?>

====================================
Execute a HTTP POST Using PHP CURL
http://davidwalsh.name/curl-post 

<?php

//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
                        'lname' => urlencode($last_name),
                        'fname' => urlencode($first_name),
                        'title' => urlencode($title),
                        'company' => urlencode($institution),
                        'age' => urlencode($age),
                        'email' => urlencode($email),
                        'phone' => urlencode($phone)
                );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open 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($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);


?>

What are advantages and disadvantages of PHP / Limitation of PHP

Advantages of PHP
  • Open source: It is developed and maintained by a large group of PHP developers, this will helps in creating a support community, abundant extension library.
  • Speed: It is relative fast since it uses much system resource.
  • Easy to use: It uses C like syntax, so for those who are familiar with C, it’s very easy for them to pick up and it is very easy to create website scripts.
  • Stable: Since it is maintained by many developers, so when bugs are found, it can be quickly fixed.
  • Powerful library support: You can easily find functional modules you need such as PDF, Graph etc.
  • Built-in database connection modules: You can connect to database easily using PHP, since many websites are data/content driven, so we will use database frequently, this will largely reduce the development time of web apps.
  • Can be run on many platforms, including Windows, Linux and Mac, it’s easy for users to find hosting service providers.
Disadvantages of PHP
  • Security : Since it is open sourced, so all people can see the source code, if there are bugs in the source code, it can be used by people to explore the weakness of PHP
  • Not suitable for large applications: Hard to maintain since it is not very modular.
  • Weak type:  Implicit conversion may surprise unwary programmers and lead to unexpected bugs. For example, the strings “1000” and “1e3” compare equal because they are implicitly cast to floating point numbers.

How to enable error reporting in PHP

  error_reporting(E_ALL);
  ini_set("display_errors", 1);

OR


  error_reporting(E_ALL | E_STRICT);
  ini_set("display_errors", 1);

"hide" notifications/errors about deprecated functions
error_reporting((E_ALL | E_STRICT) ^ E_DEPRECATED);

Ajax contact form with recaptcha

Download recaptcha library from here
There are four step need to complete and they are:
Step 1: create index.php with this code
Step 2: create contact.js
Step 3: create captcha_validation.php
Step 4: create mail.php

Contact form with recaptcha

Download recaptch version 2 from https://github.com/google/ReCAPTCHA
Download recaptcha library from here

PHP functions

PHP functions content