Facebook Like URL Meta Data Fetch in PHP

URL fetch

In Facebook when we share a link, It fetches meta data of the link and show while sharing the link. This meta data includes a image from the link, meta description and title. If you are looking to create a similar kind of thing for your project, you can use this script.

Facebook Like URL Meta Data Fetch in PHP

Demo Download

HTML code:

<div class="box" align="left">
		<div class="head1">Enter Url</div>
		<input type="text" name="url" size="64" id="url" />&nbsp;&nbsp;
		<input type="button" name="attach" value="Attach" id="attach" />
		<div id="loader">
			<div id="load" style="display:none"><img src="load.gif" /></div>	
		</div>
	</div>
</div>

CSS Code

<style>
.images{width:100px; height:100px; float:left; margin-right:8px;}

.info{ width:360px; height:200px; float:left;}
#loader{ margin:30px 7px 7px 7px; padding-top:10px;}

.title{ font-size:11px; font-weight:bold; cursor:pointer; }

.url{ font-size:11px; padding:3px;}
.desc{ font-size:12px; margin-top:5px; cursor:pointer; }

.title:hover{ background-color:#FFFF99}

.desc:hover{ background-color:#FFFF99}

#prev{cursor:pointer;}
#next{cursor:pointer;}

body
{
width:600px;
margin:0 auto;
}
.totalimg{ font-size:10px; color:#333333;float:left; margin:5px;}
</style>

jQuery Code to call functions on click

<script type="text/javascript">
	$(document).ready(function(){	
		// delete event
		$('#attach').livequery("click", function(){

			if(!isValidURL($('#url').val()))
			{
				alert('Please enter a valid url.');
				return false;
			}
			else
			{
				$('#load').show();
				$.post("curl_fetch.php?url="+$('#url').val(), {
				}, function(response){
					$('#loader').html($(response).fadeIn('slow'));
					$('.images img').hide();
					$('#load').hide();
					$('img#1').fadeIn();
					$('#cur_image').val(1);
				});
			}
		});	
		// next image
		$('#next').livequery("click", function(){

			var firstimage = $('#cur_image').val();
			$('#cur_image').val(1);
			$('img#'+firstimage).hide();
			if(firstimage <= $('#total_images').val())
			{
				firstimage = parseInt(firstimage)+parseInt(1);
				$('#cur_image').val(firstimage);
				$('img#'+firstimage).show();
			}
		});	
		// prev image
		$('#prev').livequery("click", function(){

			var firstimage = $('#cur_image').val();

			$('img#'+firstimage).hide();
			if(firstimage>0)
			{
				firstimage = parseInt(firstimage)-parseInt(1);
				$('#cur_image').val(firstimage);
				$('img#'+firstimage).show();
			}

		});	
		// watermark input fields
		jQuery(function($){

		   $("#url").Watermark("http://");
		});
		jQuery(function($){

		    $("#url").Watermark("watermark","#369");

		});	
		function UseData(){
		   $.Watermark.HideAll();
		   $.Watermark.ShowAll();
		}
	});	

	function isValidURL(url){
		var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

		if(RegExp.test(url)){
			return true;
		}else{
			return false;
		}
	}
</script>

 curl_fetch.php

<?php
$url = trim($_REQUEST['url']);
$url = check_url($url);

function check_url($value)
{
	$value = trim($value);
	if (get_magic_quotes_gpc()) 
	{
		$value = stripslashes($value);
	}
	$value = strtr($value, array_flip(get_html_translation_table(HTML_ENTITIES)));
	$value = strip_tags($value);
	$value = htmlspecialchars($value);
	return $value;
}	

function file_get_contents_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $data = curl_exec($ch);
	$info = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

	//checking mime types
	if(strstr($info,'text/html')) {
		curl_close($ch);
    	return $data;
	} else {
		return false;
	}
}

//fetching url data via curl
$html = file_get_contents_curl($url);

if($html) {
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');

//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
}

// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $html, $img, PREG_PATTERN_ORDER);
$images_array = $img[1];
?>
<div class="images">
	<?php
	$k=1;
	for ($i=0;$i<=sizeof($images_array);$i++)
	{
		if($images_array[$i])
		{
			if(strstr($images_array[$i],'http')) {
				echo "<img src='".$images_array[$i]."' width='100' id='".$k."' >";
				$k++;
			} 
		}
	}
	?>
	<input type="hidden" name="total_images" id="total_images" value="<?php echo --$k?>" />
	</div>
	<div class="info">

		<label class="title">
			<?php  echo $title; ?>
		</label>
		<br clear="all" />
		<label class="url">
			<?php  echo substr($url ,0,35); ?>
		</label>
		<br clear="all" /><br clear="all" />
		<label class="desc">
			<?php  echo $description; ?>
		</label>
		<br clear="all" /><br clear="all" />

		<label style="float:left"><img src="prev.png" id="prev" alt="" /><img src="next.png" id="next" alt="" /></label>

		<label class="totalimg">
			Total <?php echo $k?> images
		</label>
		<br clear="all" />		
	</div>
<?php
} else {
echo "Please enter a valid url";
}
?>

 Demo Download

Advertisement

Tags:

Deepanker Verma is the founder of Techlomedia. He is a tech blogger, developer and gadget freak.


Similar Articles

1 Comments

  • Rajesh Chaukwale says:

    Wow… This script was something I was looking for. Thanks a lot Deepanker. I always wondered about the best way to fetch metadata from a page and this script solves my problem. Got something new to learn!
    Thanks for the script. 🙂

Leave a comment

Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.

2020 UseThisTip | Part of Techlomedia Internet Pvt Ltd Developed By Deepanker