Saturday, March 2, 2013

Get all links from url php

Get all links from url php
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$url = "http://4evertutorials.blogspot.com/";

$var = fread_url($url);
            
    preg_match_all ("/a[\s]+[^>]*?href[\s]?=[\s\"\']+".
                    "(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/", 
                    $var, &$matches);
        
    $matches = $matches[1];
    $list = array();

    foreach($matches as $var)
    {    
        print($var."


"); } // The fread_url function allows you to get a complete // page. If CURL is not installed replace the contents with // a fopen / fget loop function fread_url($url,$ref="") { if(function_exists("curl_init")){ $ch = curl_init(); $user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; ". "Windows NT 5.0)"; $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt( $ch, CURLOPT_HTTPGET, 1 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION , 1 ); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_REFERER, $ref ); curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); $html = curl_exec($ch); curl_close($ch); } else{ $hfile = fopen($url,"r"); if($hfile){ while(!feof($hfile)){ $html.=fgets($hfile,1024); } } } return $html; } ?>

Get facebook page likes php

It is simple php code that get the number of users who like a particular Facebook page
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$fb_URL = "http://www.facebook.com/forevertutorials"; # FB Page url
$myurl = "https://graph.facebook.com/".$fb_URL."?fields=likes";
$result = file_get_contents($myurl);
$response = json_decode($result, true);

if(count($response))
{


echo "FB Page URL: ". $fb_URL;
echo "
";
echo "FB Page ID: ". $response['id'];
echo "
";
echo "FB Page TOTAL LIKES: " .$response['likes'];
echo "
";


}



?>

Get all followers of specify user from Twitter by PHP

There are many ways for getting Twitter follower count but the simplest of them is by using a simple PHP method explained on this article.

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



$screenName = "4evertutorial"; #user name on twitter
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline.json?include_entities=false&include_rts=false&screen_name=$screenName&count=1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);


if(count($response))
{

echo $response[0]['user']['id'];
echo "
"; echo $response[0]['user']['name']; echo "
"; echo $response[0]['user']['screen_name']; echo "
"; echo $response[0]['user']['location']; echo "
"; echo $response[0]['user']['description']; echo "
"; echo $response[0]['user']['followers_count']; echo "
"; echo $response[0]['user']['friends_count']; echo "
"; echo $response[0]['user']['profile_background_image_url']; echo "
"; echo $response[0]['user']['profile_image_url']; } ?>

Saturday, February 2, 2013

How to extract text from DOCX or ODT files using PHP


Function to extract text from DOCX or ODT files using PHP
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


/*Name of the document file*/
$document = 'attractive_prices.docx';

/**Function to extract text*/
function extracttext($filename) {
//Check for extension
$ext = end(explode('.', $filename));

//if its docx file
if($ext == 'docx')
$dataFile = "word/document.xml";
//else it must be odt file
else
$dataFile = "content.xml"; 

//Create a new ZIP archive object
$zip = new ZipArchive;

// Open the archive file
if (true === $zip->open($filename)) {
// If successful, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// Index found! Now read it to a string
$text = $zip->getFromIndex($index);
// Load XML from a string
// Ignore errors and warnings
$xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Remove XML formatting tags and return the text
return strip_tags($xml->saveXML());
}
//Close the archive file
$zip->close();
}

// In case of failure return a message
return "File not found";
}

echo extracttext($document);

?>

PHP Ping Class

Create php file named with Ping.php copy following code. For cass usage see bottom of  this  post. Note This script run online with root user privilege no web users
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


// Name of Class Ping.php

/**
* Ping for PHP.
*
* This class pings a host.
*
* The ping() method pings a server using 'exec', 'socket', or 'fsockopen', and
* and returns FALSE if the server is unreachable within the given ttl/timeout,
* or the latency in milliseconds if the server is reachable.
*
* Example usage:
* @code
* $ping = new Ping('www.example.com');
* $latency = $ping->ping();
* @endcode
*
* @version 1.0-beta1
* @author Jeff Geerling.
*/

class Ping {

private $host;
private $ttl;
private $data = 'Ping';

/**
* Called when the Ping object is created.
*
* @param $host (string)
* The host to be pinged.
* @param $ttl (int)
* Time-to-live (TTL) (You may get a 'Time to live exceeded' error if this
* value is set too low. The TTL value indicates the scope or range in which
* a packet may be forwarded. By convention:
* - 0 = same host
* - 1 = same subnet
* - 32 = same site
* - 64 = same region
* - 128 = same continent
* - 255 = unrestricted
* The TTL is also used as a general 'timeout' value for fsockopen(), so if
* you are using that method, you might want to set a default of 5-10 sec to
* avoid blocking network connections.
*
* @return (empty)
*/
public function __construct($host, $ttl = 255) {
if (!isset($host)) {
throw new Exception("Error: Host name not supplied.");
}

$this->host = $host;
$this->ttl = $ttl;
}

/**
* Set the ttl (in hops).
*
* @param $ttl (int)
* TTL in hops.
*
* @return (empty)
*/
public function setTtl($ttl) {
$this->ttl = $ttl;
}

/**
* Set the host.
*
* @param $host (string)
* Host name or IP address.
*
* @return (empty)
*/
public function setHost($host) {
$this->host = $host;
}

/**
* Ping a host.
*
* @param $method (string)
* Method to use when pinging:
* - exec (default): Pings through the system ping command. Fast and
* robust, but a security risk if you pass through user-submitted data.
* - fsockopen: Pings a server on port 80.
* - socket: Creates a RAW network socket. Only usable in some
* environments, as creating a SOCK_RAW socket requires root privileges.
*
* @return (mixed)
* Latency as integer, in ms, if host is reachable or FALSE if host is down.
*/
public function ping($method = 'exec') {
$latency = false;

switch ($method) {
// The exec method uses the possibly insecure exec() function, which
// passes the input to the system. This is potentially VERY dangerous if
// you pass in any user-submitted data. Be SURE you sanitize your inputs!
case 'exec':
$ttl = escapeshellcmd($this->ttl);
$host = escapeshellcmd($this->host);
// -n = numeric output; -c = number of pings; -t = ttl.
$str = exec('ping -n -c 1 -t ' . $ttl . ' ' . $host, $output, $return);
// Second output line contains result of ping. Parse if not empty.
if (!empty($output[1])) {
$array = explode(' ', $output[1]);
// Remove 'time=' from string.
$latency = str_replace('time=', '', $array[6]);
// Convert latency to microseconds.
$latency = round($latency);
}
else {
$latency = false;
}
break;

// The fsockopen method simply tries to reach the host on port 80. This
// method is often the fastest, but not necessarily the most reliable.
// Even if a host doesn't respond, fsockopen may still make a connection.
case 'fsockopen':
$start = microtime(true);
$fp = fsockopen($this->host, 80, $errno, $errstr, $this->ttl);
if (!$fp) {
$latency = false;
}
else {
$latency = microtime(true) - $start;
$latency = round($latency * 1000);
}
break;

// The socket method uses raw network packet data to try sending an ICMP
// ping packet to a server, then measures the response time. Using this
// method requires the script to be run with root privileges, though, so
// this method only works reliably on Windows systems and on Linux servers
// where the script is not being run as a web user.
case 'socket':
// Create a package.
$type = "\x08";
$code = "\x00";
$checksum = "\x00\x00";
$identifier = "\x00\x00";
$seqNumber = "\x00\x00";
$package = $type . $code . $checksum . $identifier . $seqNumber . $this->data;

// Calculate the checksum.
$checksum = $this->calculateChecksum($package); // Calculate the checksum.

// Finalize the package.
$package = $type . $code . $checksum . $identifier . $seqNumber . $this->data;

// Create a socket, connect to server, then read the socket and calculate.
if ($socket = socket_create(AF_INET, SOCK_RAW, 1)) {
socket_connect($socket, $this->host, null);
$start = microtime(true);
// Send the package.
socket_send($socket, $package, strlen($package), 0);
if (socket_read($socket, 255) !== false) {
$latency = microtime(true) - $start;
$latency = round($latency * 1000);
}
else {
$latency = false;
}
// Close the socket.
socket_close($socket);
}
else {
$latency = false;
}
// Close the socket.
socket_close($socket);
break;
}

// Return the latency.
return $latency;
}

/**
* Calculate a checksum.
*
* @param $data (string)
* Data for which checksum will be calculated.
*
* @return (string)
* Binary string checksum of $data.
*/
private function calculateChecksum($data) {
if (strlen($data)%2) {
$data .= "\x00";
}

$bit = unpack('n*', $data);
$sum = array_sum($bit);

while ($sum >> 16) {
$sum = ($sum >> 16) + ($sum & 0xffff);
}

return pack('n*', ~$sum);
}
}

?>




Usage of class:




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

require_once('Ping.php');

$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}


?>

Wednesday, January 23, 2013

Simple method to encrypt and decrypt files in PHP

Simple way to encrypt and decrypt files in php

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



function CryptFile($InFileName,$OutFileName,$password){
//check the file if exists
if (file_exists($InFileName)){

//get file content as string
$InFile = file_get_contents($InFileName);

// get string length
$StrLen = strlen($InFile);

// get string char by char
for ($i = 0; $i < $StrLen ; $i++){
//current char
$chr = substr($InFile,$i,1);

//get password char by char
$modulus = $i % strlen($password);
$passwordchr = substr($password,$modulus, 1);

//encryption algorithm
$OutFile .= chr(ord($chr)+ord($passwordchr));
}

$OutFile = base64_encode($OutFile);

//write to a new file
if($newfile = fopen($OutFileName, "c")){
file_put_contents($OutFileName,$OutFile);
fclose($newfile);
return true;
}else{
return false;
}
}else{
return false;
}
}




function DecryptFile($InFileName,$OutFileName,$password){
//check the file if exists
if (file_exists($InFileName)){

//get file content as string
$InFile = file_get_contents($InFileName);
$InFile = base64_decode($InFile);
// get string length
$StrLen = strlen($InFile);

// get string char by char
for ($i = 0; $i < $StrLen ; $i++){
//current char
$chr = substr($InFile,$i,1);

//get password char by char
$modulus = $i % strlen($password);
$passwordchr = substr($password,$modulus, 1);

//encryption algorithm
$OutFile .= chr(ord($chr)-ord($passwordchr));
}

//write to a new file
if($newfile = fopen($OutFileName, "c")){
file_put_contents($OutFileName,$OutFile);
fclose($newfile);
return true;
}else{
return false;
}
}else{
return false;
}
}

//Example
$orginalfile = 'orginal.jpg';
$crypt = 'crypt.jpg';
$decrypt = 'decrypt.jpg';
$password = 'pass';

CryptFile($orginalfile,$crypt,$password);
DecryptFile($crypt,$decrypt,$password);

?>






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:)";}


?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top