Scripts SEO

Le SEO demande parfois quelques connaissances et raccourcis en développement. Afin de ne pas avoir à chercher partout un bout de code, je vous donnes quelques scripts SEO qui me sont utiles assez souvent.

Les scripts SEO (parfois BlackHat) en php

scripts seo php

Detecter les bots Google et autres moteurs de recherche, par plage d’ip.

Idéal pour du cloaking quand on a listé quelques plages spécifiques des crawlers.

<?php
/**
 * Is_bot
 * traque la présence d'un bot par plage d'ip
 *
 * @param string $ip
 * @param array $array_bots
 * @return string|false
 */
 
function is_bot ($ip,$array_bots) {
    $ip = strval($ip);
    $reponse = false;
    foreach($array_bots as $bot=>$val) {
	foreach($array_bots[$bot] as $ip_bot) {
	    $reponse = strpos($ip,$ip_bot);
	    if ($reponse !== FALSE) return $bot;
	}
    }
    return $reponse;
}

// Utilisation
$bots = array(
    'google' => array('216.239.46','64.68.8','66.249.','64.233.173'),
    'yahoo' => array('66.196.','68.142.','202.165.','66.142.')
);
$test = is_bot('216.239.46.654',$bots); //renverra TRUE car 216.239.46 est présent dans l'ip. Utilisez $_SERVER['REMOTE_ADDR'] pour automatiser
if($test != FALSE) {
    //action affichage bot ou cloaking ;)
    $bot = $test;
    echo "bot présent<br/>";
    echo $bot;
} else {
    echo "pas de bot";
}
https://gist.github.com/titomus/3ec329b3578feb71c334754977ed0601

Récupérer les suggestions de Google pour faire du contenu ciblé.

Mais les suggestions changent au fil du temps… voici comment les récupérer (Chez Aymeric … Yapasdequoi)

Petit code PHP rapide pour récupérer les Google Suggest

function ggSuggest($word, $lang = 'fr', $spin = false){

    $word = urlencode(trim($word));
    $words = array();
    $apicall = ("https://www.google.com/complete/search?output=toolbar&q=$word");
    $result = utf8_encode(file_get_contents($apicall));
    $resp = simplexml_load_string($result);
    if ($resp){
        foreach ($resp as $t) {
            $words[] = $t->suggestion['data'];
        }
        return ($spin === true) ? '{' . implode('|', $words) . '}' : $words;

    }
    else{
        return false;
    }
}

//test
echo '<pre>';
var_dump(ggSuggest('referencement'));

echo '<hr/>';

echo (ggSuggest('seo', 'fr', true));
https://gist.github.com/titomus/134b46f41ffec6d734a218ab382a6b77

Récupérer le nombre de résultats Google (à adapter):

function get_search_num($keyword){
	$url = sprintf('http://www.google.fr/search?pws=0&hl=fr&q=%s', $keyword);

	$data = file_get_contents($url);
	$pattern = sprintf(
        '/%s(.*?)%s/',
        preg_quote('Environ'),
        preg_quote('résultats')
    );
    preg_match_all($pattern, utf8_encode($data), $matches);

    return trim($matches[1][0]);
}
// utilisation
echo get_search_num('seo');
https://gist.github.com/titomus/a219b0d7519c2f704a210b012e925716

Vérifier qu’un backlink est toujours sur une page

function is_alive_bl($url,$on){
		if (function_exists('curl_init')) {
	        $ch = curl_init();
	        $options = array(
	            CURLOPT_URL => $on,
	            CURLOPT_HEADER => false,
	            CURLOPT_RETURNTRANSFER => true,
	            //CURLOPT_FOLLOWLOCATION => true,
	            CURLOPT_MAXREDIRS => 3,
	            CURLOPT_TIMEOUT => 20,
	            CURLOPT_SSL_VERIFYHOST => false,
	            CURLOPT_SSL_VERIFYPEER => false,
	            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
	            CURLOPT_HTTPHEADER => array('Connection: close', 'Cache-Control: no-cache'),
	        );
	        curl_setopt_array($ch, $options);
	        $data = curl_exec($ch);


	    } // No cURL, try file_get_contents
	    else {
	        $data = @file_get_contents($on);
	    }
	    // Did we succeed?
	    if ($data === false || strlen($data) < 1) {
	        return false;
	    } else {	    
		    // Convert all code to lowercase
		    $html = strtolower($data);
		    
		    // Remove "https" and "www" for verification purposes
		    $site_url = str_replace(array('https://', 'http://www.'), array('http://', 'http://'), strtolower($url));
		    $site_url = @trim($site_url, '/');
		    
		    // Can we find the reciprocal link?
		    if (preg_match_all('/<a\s[^>]*href=([\"\']??)([^" >]*?)\\1([^>]*)>/siU', $html, $matches, PREG_SET_ORDER)) {
		    	//echo '<pre>';var_dump($matches);
		        foreach ($matches as $match) {
		            $match[2] = str_replace(array('https://', 'http://www.'), array('http://', 'http://'), $match[2]);
		            // on vire les repartoire et les param get
		            
		            $match[2] = @explode('?', $match[2], 2)[0];
		            $formatmatch = @trim($match[2],'/');
		            //echo $formatmatch.' == '.$site_url.chr(10);
		            if ( $formatmatch == $site_url) {
		                // All OK
		                return true;
		            }
		        }
		    }
		    // No reciprocal link found
		    return false;
	    }
}


// Utilisation
	$url = 'URL DE VOTRE SITE';
	$on = 'URL DE LA PAGE A VERIFIER';
	if (is_alive_bl($url,$on) != false){

		echo $url. ' Trouvé sur '.$on;

	}else{ 
		echo "Erreur de scrape";
	}
https://gist.github.com/titomus/9ae92a28bb4850187211ab894df551ca

Attirer le chalant avec des commentaires en dofollow … mais nofollow quand même.

Leurre idéal pour récupérer des commentaires sur son site. Peu de personnes pensent à regarder les en-têtes des pages web :

function fake_df(){
	header("X-Robots-Tag: nofollow", true);
}

// utilisation (ATTENTION: à utiliser avant affichage de la page sinon ERROR)
fake_df();
https://gist.github.com/titomus/3525d1557dd7ce1092bdd6f8a666ee90

Scraper les liens sur une page web

function scrape_links($url){
	$pageData = file_get_contents($url);
	if(preg_match_all(
		'/<a\s+href=["\']([^"\']+)["\']/i', 
		$pageData, 
		$links, 
		PREG_PATTERN_ORDER)){
    	return array_unique($links[1]);
	}else{ return false;}

}
https://gist.github.com/titomus/c65b1fa40550040a7e28e8335bc665b6

Récupérer la méta keyword d’une page

function get_site_kw($url){
	$meta = get_meta_tags($url);
	$keywords = $meta['keywords'];
	$keywords = @explode(',', $keywords );
	$keywords = array_map( 'trim', $keywords );
	$keywords = array_filter( $keywords );

	return $keywords;
}
// utilisation
get_site_kw('http://site.com')
https://gist.github.com/titomus/6d2202be0f4642af78aa3829d1ed4ee5

Fonction PHP pour spinner un texte ({hello|salut|coucou}):

function spin($txt){
        $pattern = '#\{([^{}]*)\}#msi';
        $test = preg_match_all($pattern, $txt, $out);
        if(!$test)
            return $txt;
 
        $a_trouver = array();
        $a_remplacer = array();
 
        foreach($out[0] as $id => $match)
            {
                $choisir = explode("|", $out[1][$id]);
                $a_trouver[] = $match;
                $a_remplacer[] = $choisir[rand(0, count($choisir)-1)];
            }
        $reponse = str_replace($a_trouver, $a_remplacer, $txt);
 
        return spin($reponse);
}
https://gist.github.com/titomus/36b87f77deeb93af94b038547bb88773

La même mais en JS

function spin(txt){

        var matches = txt.match(/{([^{}]*)}/g);
        if (!matches) return txt;
            for (i in matches) {
                spin = matches[i]+'';
                ori_spin = spin;
                spin = spin.replace("{", "").replace("}", "");
                spin_strs = spin.split('|');
                txt = txt.replace(ori_spin,spin_strs[Math.floor(Math.random() * spin_strs.length)]);
            }
        return spin(txt);
}
https://gist.github.com/titomus/6344bbfe277ad60a703cbf0bccecc9b3

Récupérer la racine du referer… on ne sait jamais, si on veut cloaker:

function racine_referer()
{
	if (!isset($_SERVER['HTTP_REFERER'])){
	  return false;
	}else{
	  $parser_url = parse_url(trim($_SERVER['HTTP_REFERER']));
	  return trim($parser_url[host] ? $parser_url[host] : array_shift(explode('/', $parser_url[path], 2)));
	}
}

//utilisation
echo racine_referer();
https://gist.github.com/titomus/ef1e6fcd4ead7b88c445f5673eae605f

Raccourcir ses liens.

Soit pour planquer un lien d’affiliation, soit pour traquer des clics et avoir des stats: Voir ici la très bonnes classe php disponible

Un crawler en PHP (avec multi process si souhaité)

Une fonction utile en Scraping pour récupérer des datas entre des mots.

le nombre de résultats renvoyé par Google par exemple: Environ 36 000 000 résultats

function getStringBetween($p_string, $p_from, $p_to, $p_multiple=false){
        //checking for valid main string  
        if (strlen($p_string) > 0) {
            //checking for multiple strings 
            if ($p_multiple) {
                // getting list of results by end delimiter
                $result_list = explode($p_to, $p_string);
                //looping through result list array 
                foreach ( $result_list AS $rlkey => $rlrow) {
                    // getting result start position
                    $result_start_pos   = strpos($rlrow, $p_from);
                    // calculating result length
                    $result_len         =  strlen($rlrow) - $result_start_pos;

                    // return only valid rows
                    if ($result_start_pos > 0) {
                        // cleanying result string + removing $p_from text from result
                        $result[] =   substr($rlrow, $result_start_pos + strlen($p_from), $result_len);                 
                    }// end if 
                } // end foreach 

            // if single string
            } else {
                // result start point + removing $p_from text from result
                $result_start_pos   = strpos($p_string, $p_from) + strlen($p_from);
                // lenght of result string
                $result_length      = strpos($p_string, $p_to, $result_start_pos);
                // cleaning result string
                $result             = substr($p_string, $result_start_pos+1, $result_length );
            } // end if else 
        // if empty main string
        } else {
            $result = false;
        } // end if else 

        return $result;
} // end func. get string between

//Pour une utilisation simple (renvoie deux):
$result = getStringBetweenDelimiters(" one two three ", 'one', 'three');
//Pour obtenir chaque ligne d'une table en tableau de résultats:
$result = getStringBetweenDelimiters($table, '<tr>', '</tr>', true);
https://gist.github.com/titomus/be81e6cb2528fe77115d11a9c0637572

Faire une url SEO avec un titre:

https://gist.github.com/titomus/56cda56b1fb30a7147ecafcb3c0704e9

Une redirection en php:

https://gist.github.com/titomus/7ab3b49e8ee713867199d50f220f373b

Pinguer avec Pingomatic

https://gist.github.com/titomus/28a096dcbd48925a023608d94764c1f4

Récupérer la provenance et le mot clé d’un visiteur qui vient des moteurs de recherche

https://gist.github.com/titomus/62ea5ae9a5cc50e8415f297491e5c13b

Les scripts SEO pour WordPress

Ces petits snippets SEO sont à intégrer dans le fichier functions.php de votre thème.

Un fil d’ariane simpliste:

https://gist.github.com/titomus/ca97bfa8464acb01608c2cbcc4a1f4ba

Il en manque ? N’hésitez à me passer l’info sur Twitter… je rajouterai :)

Article ajouté au panier
0 Produit - 0,00