Monday, 29 June 2015

Yii 2 - Unable to find 'console\controllers\RbacController, RBAC yii rbac/init

I have installed the very latest version of Yii 2.0.4, and while using the Advanced Template with RBAC i got the below issue while running the command yii rbac/init



Exception 'yii\base\UnknownClassException' with message 
'Unable to find 'console\controllers\RbacController' 
in file: /var/www/yii/console/controllers/RbacController.php. Namespace missing?'


To overcome this simply edit the "namespace console\commands;" as   "namespace console\controllers;" in RbacController.php

RbacController - will be inside the console/controllers folder.

Once we set all correctly run yii rbac/init then we will get the values automatically in our migrated tables auth_item and auth_item_child




Wednesday, 4 March 2015

Wordpress Year Pagination.

We have used Page No pagination in WordPress like

[15] [14] [13] ... [1]

Likewise we can create the Year pagination for our archive post. OK use the below code to simply past in your archive list area under the pagination part.


<?php
$current_year= date('Y'); // this will the current year
$archive_year = get_the_time('Y'); // this will get the year of the archive list
$starting_year= "2006"; // this will be our starting year
?>

<ul class="SOME CLASS">
<?php if($archive_year < $current_year ) { ?>
<li><a href="<?php echo get_year_link( $archive_year+1 ); ?>"><i class="SOME CLASS"></i></a></li>
<?php } ?>
<?php if($archive_year == $current_year ) { ?>
<li><a href="<?php echo get_year_link( $archive_year ); ?>"><i class="SOME CLASS"></i></a></li>
<?php } ?>
<li class="SOME CLASS FOR DIVIDER"></li>
<?php

for($i=date('Y'); $i>2005; $i--) {
$diff= $i-$archive_year;
if($diff>2&&$diff<4)
{
echo '<li><a href='.get_year_link( $current_year ).'>'.$current_year.'</a></li>';
echo '<li><a class="SOME CLASS">…</a></li>';
}

if($diff>-3&&$diff<3)
{
if ($i == $archive_year) {
echo '<li class="active"><a href='.get_year_link( $i ).'>'.$archive_year.'</a></li>';
}
else {
echo '<li><a href='.get_year_link( $i ).'>'.$i.'</a></li>';
}
}

if($diff>-4&&$diff<-2)
{
echo '<li><a class="SOME CLASS">…</a></li>';
echo '<li><a href='.get_year_link( $starting_year ).'>'.$starting_year.'</a></li>';
}
}
?>
<li class="SOME CLASS FOR DIVIDER"></li>
<?php if($archive_year <= $current_year && $archive_year > '2006') { ?>
<li><a href="<?php echo get_year_link( $archive_year-1 ); ?>"><i class="SOME CLASS"></i></a></li>
<?php } ?>
<?php if($archive_year == $current_year && $archive_year == '2006') { ?>
<li><a href="<?php echo get_year_link( $archive_year); ?>"><i class="SOME CLASS"></i></a></li>
<?php } ?>
<?php if($archive_year != $current_year && $archive_year == '2006') { ?>
<li><a href="<?php echo get_year_link( $archive_year); ?>"><i class="SOME CLASS"></i></a></li>
<?php } ?>
</ul>


So the above will output like below


Thursday, 5 February 2015

Simple Mobile number subscription plugin Wordpress, Wordpress Mobile number subscription plugin

Simple Mobile number subscription plugin

== Description ==

This plugin will be handy for your users to add their numbers in your site, and you can use this plugin for your whatsapp subscription list

A few notes about the sections above:

*   Shortcode for widget
*   Admin can able to add, edit, delete the mobile number
*   "Tested up to" is the highest version that you've *successfully used to test the plugin*. Note that it might work on
higher versions... this is just the highest one you've verified.

== Installation ==

1. Upload `whatsapp-subscription` to the `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress



This is the shortcode that we need to use [ADD-SUBSCRIPTION-WHATSAPP]



Use this Wordpress Simple plugin: https://wordpress.org/plugins/whatsapp-subscription/




Tuesday, 3 February 2015

Avoid Custom Codes in WordPress Core files



WordPress is the best blogger CMS open source, as well as hack-able one. So we need to keep updating everything regularly.

Themes
Plugins
WordPress version



WordPress version update comes with Manual update as well as One click update from the dashboard. But if you made any custom codes inside wp-admin/ or wp-includes folders, then it will be replaced and we will lose our files, functions etc.

So Always don't edit any core files of WordPress


as well as don't update any raw files inside wp-content/themes or wp-cotent/plugins, if you edit any WordPress themes then it will be big head ache as well as we need to be stay in the old version if we need our site in the same format, if you did any edits in the theme files and updating the version then we will entirely loose the site design, functions etc.

So always create a Child theme and put your edited files there


If we are following this formats, then by a single click we can update our versions, and our site will be get secured.



Sunday, 1 February 2015

Whatsapp for sharing your Posts, Whatsapp PHP API for Wordpress, Whatsapp for Wordpress

We can see many sharing services like Addthis, Sharethis have already integrated the Whatsapp sharing services in their stream.


But it wont work in the Desktop version, as Whatsapp will work in latest Iphone and Chrome version. May be in the future days they will set the API for web sharing, but for now there is no such options in Whatsapp as well as in other Social Sharing Sites.

Ok, but we can do the sharing. Please refer this https://github.com/venomous0x/WhatsAPI, they are having the API to send the Whatsapp message from a mobile to other mobile.

Ok, here is the steps to set your API:


  • First we need to register our Mobile number with WART (https://github.com/shirioko/WhatsAPI/wiki/WhatsApp-Registration-Flow), check this site.


  • Once you register you will get a SMS code confirmation


  • We need to set the Code confirmation again in the same registration form and once set we will get the below 


  • Username
  • Password
  • Identity
         and this is what we need for the API



Please set the credentials inside the exampleFunctional.php file, and set the [$target] target mobile number to which you want to send your blog titles/ URLs.

The target numbers will get the Whatsapp Message from our WART registered Mobile number.


This Github URL is providing all the variables set for Whatsapp API from venomous0x
https://github.com/shirioko/WhatsAPI/wiki/WhatsApi-events

--------------------------------------------------------------------------------------------------------------------

We can use this API and integrate with our Blogger or Wordpress sites, we can set some AUTO system and send the messages to the Subscribed mobile numbers once we post a new articles in our site.


YES WHATSAPP IS WORKING.


--------------------------------------------------------------------------------------------------------------------

Why Whatsapp is not working in my ADDTHIS share code?

That is because it will be get worked inside the mobile device only with latest OS and CHROME versions. Also while referred to different forums, it is detailed that it will get worked in the latest Iphone devices.

If we run the Addthis - Whatsapp share inside the desktop version we will get the below link and it wont get worked

http://whatsapp//send?text=***************************************




Happy coding...













Tuesday, 9 December 2014

Play with CSS - CSS BOX SHADOW

CSS comes with a good box pattern called "Box Shadow" of your tag. For more details on Box shadow tutorials refer here  http://css-tricks.com/snippets/css/css-box-shadow/


We can set the floating of our tags (DIV, P etc) by setting the Box shadow style.


The box-shadow property sets one or more drop-shadows to the tags.

Sometime you need this http://www.w3schools.com/cssref/playit.asp?filename=playcss_box-shadow&preval=50px%2050px%205px%20black

Through this box shadow pattern i did some CSS image styling, please refer my below screenshot


.myclass{
box-shadow: 1em 0 0 0 red,
0 1em 0 0 red,
-1em 0 0 0 red,
0 -1em 0 0 red,
-1em -2em 0 0 red,
1em -2em 0 0 red,
-1em 2em 0 0 red,
1em 2em 0 0 red,
2em 1em 0 0 red,
2em -1em 0 0 red,
-2em 1em 0 0 red,
-2em -1em 0 0 red,
3em 0 0 0 red,
-3em 0 0 0 red,
0 3em 0 0 red,
0 -3em 0 0 red;
background: black;
width: 1em;
height: 1em;
overflow: hidden;
margin: 50px 0 70px 65px;
}

At some point we can avoid using the image and we can reduce the load time of the site. I didt diked any online tutorials, but this is what i got while working practically


1em 0 0 0 red  (Creates a box to the right of your tag (for me it is a div tag)



so what if 2em 0 0 0 red (Creates a box to the right of your tag with space like below (for me it is a div tag)



Friday, 7 November 2014

Why my wordpress site is slow and how to avoid it

I have been working in a WordPress project for a while and it is having too many data and comments from users. May be some 4000 posts and 30000 comments, day by day the site became shaky and it took lot of time to get loaded.

But i used the clean WordPress formats and codes, so i don't need to bother about any custom code issues. 

Note: PLEASE DO NOT CUSTOM CODE anything in the WordPress default file or write any unwanted SQL queries. Unwanted files and SQL queries will took time for the site to get loaded.

But there is something that makes the site to get loaded very slow. Actually i am just loading 10 posts in the home page and every other pages of the site is loading only 10 posts per page.

Mine is a WINDOWS / MYSQL server and it is easy for me to check any TEMP and CACHE values. While looked into my windows temp folder it loading with many 100+ PHP-CGI.exe files created for every minute, so i used a good cache plugin to cache the files and reduced the EXE file generation.

Note by default the Cache files will be get deleted on some time period (2 HRS, 4 HRS) and mine is 2 hrs.

But this does not actually reduced my page load problem and some time i got MYSQL server is overloaded something, and again i checked my TEMP folder and it showed it is stored some SESSION values for 1KB, the reason is i am using plugins (SI Captcha, Ninja Forms and YII poll) 

Inside these plugins there are code lines to generate Session values and we know all the session values will be get stored in our server, for every second the TEMP session files are getting generating. For a second i got some 5 files got generated, so i deleted these plugins and i got the site came in normal. So the problem is too many session files and php exe files.

Note: While creating any WordPress project DON'T CREATE TOO MANY SESSION values, as all will get stored in your server. And while using any plugin please check whether this is creating any session values.

My Wordpress site is very big so i did all, if you are not having that much traffic then no problem.

 



Saturday, 19 April 2014

Multiple polygons on google map with hover show, hide

Here you can find the multiple ploygons on the google map and we can show and hide the ploygons as per the title mouse over, i didt find much time to shorten this jquery code. Meantime i am not ok with the line 


idx=jQuery(this).attr('id');
for(var i=0,l=countries.length;i
if(idx==i){countries[i].setMap(map);}
else{countries[i].setMap(null);}
}


I cant able to directly assign my idx value like this countries[idx].setMap(map);, if i put like then it is showing as countriex[idx] is not a function, if anyone know the solution please let me know




Put your google map script URL
Put your Jquery ajax URL
Set your div tags with ID values


function initialize() {
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);   
var mapOptions = {     zoom: 2,     center: myLatLng,     mapTypeId: google.maps.MapTypeId.TERRAIN   };  
map = new google.maps.Map(document.getElementById("map_canvas"),       mapOptions);
var countries = new Array();

countries[0] = new google.maps.Polygon({
paths: [
new google.maps.LatLng(59.677361, -2.469846),     
new google.maps.LatLng(59.299717,   -6.314917),     
new google.maps.LatLng(57.877247,   -9.314917),     
new google.maps.LatLng(54.428078,  -11.638861),     
new google.maps.LatLng(51.784554,  -11.702241),    
new google.maps.LatLng(50.185848,  -10.054354),     
new google.maps.LatLng(49.405380,   -7.012100),     
new google.maps.LatLng(49.090675,   -3.272664),     
new google.maps.LatLng(48.775970,   -1.709283),     
new google.maps.LatLng(49.757851,   -2.089565),     
new google.maps.LatLng(50.714554,    1.037195),     
new google.maps.LatLng(51.482437,    2.304801),     
new google.maps.LatLng(53.433609,    3.276632),     
new google.maps.LatLng(55.863132,    3.445646)],
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});

countries[1] = new google.maps.Polygon({   
paths: [   
new google.maps.LatLng(25.774252, -80.190262),     
new google.maps.LatLng(18.466465, -66.118292),     
new google.maps.LatLng(32.321384, -64.757370),     
new google.maps.LatLng(25.774252, -80.190262)],
strokeColor: "#FF0000",   
strokeOpacity: 0.8,   
strokeWeight: 2,   
fillColor: "#FF0000",   
fillOpacity: 0.3
});


countries[2] = new google.maps.Polygon({   
paths: [   
new google.maps.LatLng(12.774252, -80.190262),     
new google.maps.LatLng(33.466465, -66.118292),     
new google.maps.LatLng(44.321384, -64.757370),     
new google.maps.LatLng(33.774252, -80.190262)],
strokeColor: "#FF0000",   
strokeOpacity: 0.8,   
strokeWeight: 2,   
fillColor: "#FF0000",   
fillOpacity: 0.3
});

countries[3] = new google.maps.Polygon({   
paths: [   
new google.maps.LatLng(33.774252, -44.190262),     
new google.maps.LatLng(55.466465, -54.118292),     
new google.maps.LatLng(75.321384, -64.757370),     
new google.maps.LatLng(53.774252, -80.190262)],
strokeColor: "#FF0000",   
strokeOpacity: 0.8,   
strokeWeight: 2,   
fillColor: "#FF0000",   
fillOpacity: 0.3
});

jQuery('#submenu_links li a').mousemove(function(){
idx=jQuery(this).attr('id');
for(var i=0,l=countries.length;i
if(idx==i){countries[i].setMap(map);}
else{countries[i].setMap(null);}
}
});

jQuery('#submenu_links li a').mouseout(function(){
var id=jQuery(this).attr('id');
for(var i=0,l=countries.length;i
countries[i].setMap(null);
}
});
 
 }
google.maps.event.addDomListener(window, 'load', initialize);


Thursday, 6 March 2014

How to show the Active/ Inactive dropdown status in YII C detail View

Its simple to set the active, inactive in the C detail View dropdown list, just assign the status value as like the below format


 array(             
            'label'=>'Status',
            'type'=>'raw',
            'value'=>($model->status == 1) ? "Active" : "Inactive",
        ),

CActiveDataProvider Yii - Is simple and neat



CActiveDataProvider Yii - Is simple and neat, where we can enter our condition, pagination etc

I actually started coding with custom select query in YII, but while referred to "CActiveDataProvider" with conditions and pagination there is no need for to call the  sql query second time with condition or pagination

Here i will explain what i had previously and how the YII default CActiveDataProvider is working


My custom code in my controller function:
===========================================

public function actionList()

{
$criteria = new CDbCriteria();

$criteria->addCondition('user_id='.Yii::app()->user->id.'');
$count = Blog::model()->count($criteria);
$pages = new CPagination($count);

 
$pages->pageSize = 5;
$pages->applyLimit($criteria);
$models = Blog::model()->findAll($criteria);
$this->render('list', array('models' => $models, 'pages' => $pages));
}


While following the above code, i need to call this $model inside a foreach and need to show the values. 



YII default CActiveDataProvider in my controller function:
===========================================

public function actionList()
{
$criteria=new CDbCriteria;
$criteria->order='id DESC';  
$dataProvider=new CActiveDataProvider('Blog',array('criteria'=>$criteria,'pagination' => array('pageSize'=>Yii::app()->params['PaginationPerPage']),));
$this->render('list',array('dataProvider'=>$dataProvider,));
}

This is what Yii gave in default, its simple. And while following this code we can simply use the default view format from YII like below 


$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'_view',)); 
?>




Tuesday, 11 February 2014

How to set the country, state relationship in Yii




My Country table:
================
id
name


My state table:
===============
id
country_id
name



Here i need to refer the country from state using the country_id relationship

So first i need to generate a Relationship in my State Model like below


public function relations()
{

return array(
'country'=>array(self::BELONGS_TO, 'Country', 'country_id'),
);

}

Country here is the country model
country_id is the reference key in state table to refer the country table


Ok so in CGrid view use the below format

'country.name',


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

And if we need filtering for countries in state admin?

Just use the compare setup like below

public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.

$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name);
$criteria->with = array('country');
$criteria->compare('country.id',$this->country_id, true);

return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}


And in your Cgridview area have it like below


array(
'name'=>'country_id',
'header'=>'Country',
'value'=>'$data->country->name',
'filter'=>CHtml::listData(Country::model()->findall(),'id','name' ),
),

Wednesday, 5 February 2014

How to set the active and inactive status for 1,0 values in YII CGridView

In Yii normal CGridView will have the below structure


'columns'=>array(
'id',
'title',
'sstatus',

So to set the 0 as Inactive and 1 as Active 

we need to edit the 'status' as

array(
'header'=>'status', //for to set the title for the table column, we can remove this if we need to show the default value
'name'=>'sstatus' // where sstatus is my database column name
'value'=>'($data->sstatus==1)? "Active" : "Inactive"'
),


Once set we can see 0 as inactive and 1 as active. 


But how about filtering? 
The filtering in Yii will work when we input 1 and not as active, so just replace this filter area with dropdown list in the same area where we updated our above code, just add filter array like below



array(
'header'=>'status', //for to set the title for the table column, we can remove this if we need to show the default value
'name'=>'sstatus' // where sstatus is my database column name
'value'=>'($data->sstatus==1)? "Active" : "Inactive"',

'filter'=>CHtml::dropDownList('Slider[sstatus]', 'sstatus',  
                array(
                    ''=>'All',
                    '1'=>'Active',
                    '0'=>'Inactive',
                )
            ),
        ),

),



in the above Slider is my model name and sstatus is my database table column... thats it.......


But i faced some problems like auto select and select all is not working, so we can set the filter directly like the below code


  array(
           'name' => 'sstatus',
           'filter' => array(0 => 'In Active', 1 => 'Active'),
'value' => '($data->sstatus == 1) ? "Active" : "Inactive"',
       ),

Tuesday, 20 August 2013

PHP Translator, replacement for google translator api?.


I struggled to get the language translator for my php project and found Google API is not WORKING FOR ME, I dont know it works for others. While surfed i got google closed its Free Translator API, and microsoft is providing its API with limited character free subscription.

The code providing by them comes in SOAP, HTTP and Javascript and yes it supported my PHP. Even they are providing exact PHP class files that helped me a lot. You can register your Keys with them, use this link for to Sign up for the Microsoft Translator API "https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb". They have listed all the subscription plans ranges from free to $6000/ month.

I think this link will also helpful http://www.microsofttranslator.com/dev/. After creating your Keys register with Datamarket and your translator will work good. I have used HTTP >> Translate Method "http://msdn.microsoft.com/en-us/library/ff512421.aspx" and there you can see the PHP class files, and it is very handy......


Happy coding

Monday, 19 August 2013

How to get the meta title, description and keywords using PHP



function getUrlData($url)
{
    $result = false;
   
    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;
       
        preg_match('/<***title***>([^***>]*)<***\/title***>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }
       
        preg_match_all('/<***[\s]*meta[\s]*name="?' . '([^***>"]*)"?[\s]*' . 'content="?([^***>"]*)"?[\s]*[\/]?[\s]****>/si', $contents, $match);
       
        if (isset($match) && is_array($match) && count($match) == 3)
        {
            $originals = $match[0];
            $names = $match[1];
            $values = $match[2];
           
            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();
               
                for ($i=0, $limiti=count($names); $i <*** $limiti; $i++)
                {
                    $metaTags[$names[$i]] = array (
                        'html' => htmlentities($originals[$i]),
                        'value' => $values[$i]
                    );
                }
            }
        }
       
        $result = array (
            'title' => $title,
            'metaTags' => $metaTags
        );
    }
   
    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;
   
    $contents = @file_get_contents($url);
   
    // Check if we need to go somewhere else
   
    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<***[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^***>"]*)"?' . '[\s]*[\/]?[\s]****>/si', $contents, $match);
       
        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection <*** $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }
           
            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }
   
    return $contents;
}
?>


<***?php
$result = getUrlData('http://elwatannews.com/');

echo '<***pre***>'; print_r($result); echo '<***/pre***>';


Note: Remove ***s

Friday, 16 August 2013

How to Resize or Scale your image using CSS

There are many best ways to scale the images for your site. We can use the php resize codes or Jquery resize scripts and others, and one of the best way is to scale the images through CSS. For a demo please check the below code



<*****style type="text/css">
.center-cropped  {
    width: 310px;
    height: 168px;
    background-position: 50% 11%;
    background-size: cover;
 }

<*****div class="center-cropped" style="background-image: url('http://elbadil.com/sites/default/files/styles/428xauto_node_image_2/public/13/08/32/0_73.jpg?itok%3Dk9uRSMGi');">
<******/div>


Note: remove ******


In the above code background-size acts as the center point, I just need a whole cover section, but we can use contain or auto or anything as per your needs.

Check the background-position too. I made as 50: 11 Percentage ratio. You can set the height and width and by this there wont be any stretch in the image. But the whole concept will make the load time bit high when compared to resizing :)




Code to make other site image to get stored in your wordpress database as well as making other site images to your wordpress post featured image


$upload_dir = wp_upload_dir();
$image_data = file_get_contents("Image URL for other site");
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path']))
$file = $upload_dir['path'] . '/' . $filename;
else
$file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id , $attach_id );


wp_update_attachment_metadata will make the image to get stored in your database

set_post_thumbnail will make the image to get featured for the post

$post_id - will be ID of your post, for example if you just want to make your post id 5 to get featured image then just replace the variable  $post_id with 5





substr in php is not removing characters?


I had a similar problem before and rectified using mb_substr, for demo please check the below code

$then_truncate_the_value=mb_substr($remove_html_first , 0, 123);

How to scrap the titles of a Wordpress site using CURL php?


$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL, 'Your URL');
curl_setopt($curl1, CURLOPT_HEADER, false); 
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl1, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl1, CURLOPT_ENCODING,"");
curl_setopt($curl1, CURLOPT_USERAGENT, "spider");
curl_setopt($curl1, CURLOPT_AUTOREFERER,true);
$result1 = curl_exec($curl1); curl_close($curl1); 


## get the title
preg_match_all('your h1 tag with calss', $result1, $matches1, PREG_OFFSET_CAPTURE);
preg_match('/your anchor tag/', $matches1[0][0][0], $set1);
$my_title=$set1[2];



1) Initialize the CURL
2) Enter the URL
3) Check whether the wordpress site comes with the h1 tag and with the same class i declared here, else use the correct one
4) I dont want the link tag so i removed the <--a---> tag, and finally we will have the result

How to get images for a URL through php?

We can use many concepts for this eithe we can use DOM or CURL or anything. Lets see a simple example on how to use DOM concept





$doc = new DOMDocument();
$doc->loadHTML('Your URL');
$imageTags = $doc->getElementsByTagName('img');

foreach($imageTags as $tag) {
$img_src= $tag->getAttribute('src');
}





By this we can get all the image tag in the particular URL, you can write separate scripts for Image types too.

Friday, 12 July 2013

Search lists from Youtube, Dailymotion, Google and Metacafe using PHP

Youtube:  For youtube you need to down the files from google-api-php-client and please use this below demo file


$htmlBody = <<

 

    Search Term:
 
 

    Max Results:
 
 

END;

if ($_GET['q'] && $_GET['maxResults']) {
  // Call set_include_path() as needed to point to your client library.
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_YouTubeService.php';

  /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
  Google APIs Console
  Please ensure that you have enabled the YouTube Data API for your project. */
  $DEVELOPER_KEY = 'put your api key here';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  $youtube = new Google_YoutubeService($client);

  try {
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';
    $playlists = '';


//print_r($searchResponse['items']);



for($x=0;$x
echo $searchResponse['items'][$x]['id'] ['videoId'] ;


}

/*
    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('

  • %s (%s)
  • ', $searchResult['snippet']['title'],
                $searchResult['id']['videoId']);
              break;
            case 'youtube#channel':
              $channels .= sprintf('
  • %s (%s)
  • ', $searchResult['snippet']['title'],
                $searchResult['id']['channelId']);
              break;
            case 'youtube#playlist':
              $playlists .= sprintf('
  • %s (%s)
  • ', $searchResult['snippet']['title'],
                $searchResult['id']['playlistId']);
              break;
          }
        }

        $htmlBody .= <<   

    Videos

       
      $videos


       

    Channels


       
      $channels

       

    Playlists


       
      $playlists

    END;*/
      } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf('A service error occurred: %s
    ',
          htmlspecialchars($e->getMessage()));
      } catch (Google_Exception $e) {
        $htmlBody .= sprintf('An client error occurred: %s
    ',
          htmlspecialchars($e->getMessage()));
      }
    }
    ?>



     
        YouTube Search
     

     
       
     



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

    Google Image Search:



    $url = "https://ajax.googleapis.com/ajax/services/search/images?" .
           "v=1.0&q=barack%20obama&userip=INSERT-USER-IP";

    // sendRequest
    // note how referer is set manually
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, "http://localhost/#######/google.php");
    $body = curl_exec($ch);
    curl_close($ch);

    // now, process the JSON string
    $json = json_decode($body);

    /*$results = array();
    foreach ($json['responseData']['results'] as $result) {
      $results[] = array(
        'url' => $result['url'],
        'title' => $result['title'],
        'content'=>$result['content']
      );
    }
    */
    echo '
    ';
    
    var_dump($json->responseData->results);
    echo '
    ';


    for($x=0;$xresponseData->results);$x++){

    echo "Result ".($x+1)."";
    echo "
    Image: ";
    echo $json->responseData->results[$x]->url;
    echo "


    echo $json->responseData->results[$x]->url;
    echo "
    URL: ";
    echo $json->responseData->results[$x]->url;
    echo "
    VisibleURL: ";
    echo $json->responseData->results[$x]->visibleUrl;
    echo "
    Title: ";
    echo $json->responseData->results[$x]->title;
    echo "
    Content: ";
    echo $json->responseData->results[$x]->content;
    echo "

    ";

    }

    // now have some fun with the results...

    /*echo '

    ';
    var_dump($json);
    echo '
    ';
    */


    //$decodedJSON = json_encode($json);

    // Put everyting to the screen with var_dump;
    //var_dump($decodedJSON);

    // With print_r ( useful for arrays );
    //print_r($decodedJSON);

    /*foreach ( $json->responseData->results as $results1 )
    {
           echo $results1;
    }*/

    //print_r($json->responseData->results);

    /*$properties = get_object_vars($json);
    print_r($properties);*/

    //print_r($json);

    ?>


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

    Metacafe:



    if(isset($_POST['search']))
    {
        $video=$_POST['video'];
        //echo $video;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'http://www.metacafe.com/topics/'.$video);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
        $result = curl_exec($curl); curl_close($curl);
        //echo $result;
       
        //$value=preg_match_all('/<section class=\"CCol">(.*?)<\/section>/s',$result,PREG_PATTERN_ORDER);
        preg_match('/
    (.*?)<\/section>/s', $result, $matches, PREG_OFFSET_CAPTURE);
        print_r($matches);
    }
    ?>
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

    ">
    http://www.w3.org/1999/xhtml">


    Search Video - Metcafe




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

    Daily Motion:


    $url="https://api.dailymotion.com/videos?search=facebook&fields=id,title,channel,thumbnail_medium_url";
    // sendRequest
    // note how referer is set manually
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, "http://localhost/jothirajan/demos/dailymotion-sdk-php-master/test.php");

    $body = curl_exec($ch);
    curl_close($ch);

    // now, process the JSON string
    $json = json_decode($body);

    /*echo '
    ';
    var_dump($json);
    echo '
    ';

    */
    for($x=0;$xlist);$x++){


    echo "Result ".($x+1)."";
    echo "
    id: ";
    echo $json->list[$x]->id;
    echo "
    Img: ";
    echo "
    ";

    echo "
    channel: ";
    echo $json->list[$x]->channel;
    echo "
    title: ";
    echo $json->list[$x]->title;

    echo "

    ";

    }

    ?>