Skip to content

Instantly share code, notes, and snippets.

@maxiorel
Created November 19, 2022 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxiorel/063c43f0e09a69b7bee109a8545e8478 to your computer and use it in GitHub Desktop.
Save maxiorel/063c43f0e09a69b7bee109a8545e8478 to your computer and use it in GitHub Desktop.
Notion backlinks checker
<?php
/*
* Notion Backlinks Checker in PHP
* PHP requirement: https://github.com/brd6/notion-sdk-php
* Notion requirement: database table with columns: Name, OK, URL, Target, My URL, My Target, Contact, Latest Check
* read more:
* [CZ]: https://www.maxiorel.cz/notion-php-backlink-kontrola
* [EN] https://www.maxiorel.com/notion-php-backlink-checker
* */
require "vendor/autoload.php";
use Brd6\NotionSdkPhp\Client;
use Brd6\NotionSdkPhp\ClientOptions;
use \Brd6\NotionSdkPhp\Resource\Database\DatabaseRequest;
// Slightly modified version of https://gist.github.com/nedevl/f6fb87ab53f3c765c8eb5e09b16817fe
function backlinkCheck($backlink, $url) {
$backlinkexists = false;
$backlinknofollow = false;
$content = file_get_contents($url);
$dom = new DomDocument();
libxml_use_internal_errors(true);
$dom -> loadHTML($content);
$anchors = $dom -> getElementsByTagName('a');
libxml_clear_errors();
foreach ($anchors as $anchor) {
$link = $anchor -> getAttribute("href");
//check if the link exists among links on the $url
if ($link == $backlink) {
$backlinkexists = true;
$anchorhtml = strtolower($anchor -> C14N());
if (strpos($anchorhtml, 'nofollow') !== false) {
$backlinknofollow = true;
}
break;
}
}
if ($backlinkexists && !$backlinknofollow) {
// backlink exists and it doesn't has a rel attribute with nofollow value
return TRUE;
} else if ($backlinkexists && $backlinknofollow) {
// backlink exists and it does has a rel attribute with nofollow value
return FALSE;
} else {
// backlink doesn't exists
return FALSE;
}
}
$options = (new ClientOptions())
->setAuth('YOUR_NOTION_INTEGRATION_TOKEN');
$notion = new Client($options);
$databaseRequest = new DatabaseRequest();
$myPage = $notion->databases()->query('YOUR_DATABASE_MACHINE_NAME', $databaseRequest);
$results = $myPage->getResults();
foreach ($results as $result){
$page = $notion->pages()->retrieve($result->getId());
$properties = $page->getProperties();
$url = $properties['URL']->getUrl();
echo 'Checking '.$url. "\n";
$target = $properties['Target']->getUrl();
$check = backlinkCheck( $target, $url);
$properties['OK']->setCheckbox($check);
$page->setProperties([
'OK' => $properties['OK'],
'Latest Check' => ['date' => ['start' => date('c'), 'end' => date('c')] ]
]);
$pageUpdated = $notion->pages()->update($page);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment