I got a script to check if a URL is present in a page. Here it is:
class LP_backlinkchecker
{
var $url;
var $content;
var $links;
var $linktocheck;
function __construct($url, $linktocheck)
{
$this->url = $url;
$this->linktocheck = $linktocheck;
}
function SetLinktocheck($link)
{
$this->linktocheck = $link;
}
function getContents()
{
$this->content = file_get_contents($this->url);
}
function lpFetchLinks()
{
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
preg_match_all("/$regexp/siU", $this->content, $matches);
$this->links = $matches;
return $matches;
}
function check()
{
foreach($this->links[2] as $key => $url)
{
if($url == $this->linktocheck)return TRUE;
}
return FALSE;
}
}
My problem is that the script only works for checking links on the same site. It does not work when the links to check is outside of the website. For example, the script works well to check the link
http://web.com/linktocheck present on the website http://web.com/
If think my $regexp is wrong, do you have some idea of the problem ?
Thanks for your help.
Not sure if I have misunderstood your issue but your code seems to work for me. I wrote you a little unit test that you can now have and expand upon, if you could write a test that does not work I might be able to help more.
class LP_backlinkcheckerTest extends PHPUnit_Framework_TestCase
{
public $l;
public function setUp()
{
$this->l = new LP_backlinkchecker('test.html', null);
}
public function tearDown()
{
}
public function testGetContents()
{
$this->l->getContents();
$this->assertNotEmpty($this->l->content);
}
public function testlpFetchLinks()
{
$this->l->getContents();
$matches = $this->l->lpFetchLinks();
$expected = array(
"http://google.com",
"http://www.bluesnews.com",
"http://www.bluesnews.com/somepage"
);
// 4 things captured by the regex
$this->assertEquals(4, count($matches));
$this->assertEquals($expected, $matches[2]);
}
}
and the HTML file I am using
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Google.com
BluesNews.com
somepage
</body>
</html>
Although it would be better to make your class so that I don't have to supply it a file but that's the way you designed it. I would also suggest perhaps using parse_url to breakdown the url into it's component parts. Your problem may be just that your expecting one string to be equal to the other and there may be a user input error at construct time which your not checking at all.
Related
My problem is, when the user logout. The login page is being called and the index page is showing but the url is saying
https://mysite/logout.php
instead of
https://mysite/index.php
which means my javascript files included in the index.php ain't being loaded, so you cant log in again without refreshing the page manually.
Link in home.php the page you reach after login
<p class="mc-top-margin-1-5">Logout</p>
I have the following logout page (logout.php)
<?php
session_start();
require_once 'php/class/class.user.php';
$user = new USER();
if(!$user->is_logged_in())
{
$user->redirect('index.php');
exit;
}
if($user->is_logged_in()!="")
{
$user->logout();
$user->redirect('index.php');
exit;
}
?>
my user functions as follow (class.user.php)
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
}
what am I missing?
Your function is_logged_in() returns a boolean, TRUE, but you are checking the return value with:
if($user->is_logged_in()!="")
That is, checking if it's an empty string.
Also, and more importantly, is_logged_in() doesn't return anything if the user is not logged in. That function should be something like:
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
else { return false; }
}
And the check should be something like:
if(!$user->is_logged_in())
so i ended up with a not very nice solution:
I changed the link in home.php
`<p class="mc-top-margin-1-5">Logout</p> `
To a button
<button id="btn-logout">Logout</button>
and added its functionality in a jquery function
$(function(){
$("#btn-logout").bind('click', function () {
window.location.href = "http://example.com/logout.php";
})
});
my logout.php ended up looking like
<?php
session_start();
unset($_SESSION['user_session']);
session_destroy();
?>
<html>
<head>
<script>
window.location.href = "https://example.com/index.php";
</script>
</head>
<body>
</body>
</html>
So going from refresh page in php using header. I ended up with js and jquery. Its not a nice solution above, but it works!
I am using this, for login with Facebook, but i am not getting user response here is the link
http://demos.idiotminds.com/link.php?link=https://www.box.com/s/108pspt0o0oj0fpr6ghf
I have tried this solution also for codeigniter
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
for log in with Facebook but i am not getting value from this $user = $facebook->getUser(); it returns 0 value even if i have logged into Facebook.
I have used so many codes for this but did not success, kindly help me out.
I am very frustrated
Download PHP SDK for Facebook
Now create the a folder in application\libarires "facebook"
Put the "SRC" folder of PHP SDK
Now create a file with FacebookApp.php in that folder and put this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config- >item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
Now in controller load this library
$this->load->library('facebook/FacebookApp)
in Method
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
put the fb_login_url in href of login button and now the login will done.
Hope it help you.
Rahul, I had a similar issue. You can find a pretty good solution here.
If you still cannot figure the solution, why don't you look into the JavaScript SDK. It is pretty straight forward and then use AJAX to act on the response that you get from Facebook.
I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){
I am a rookie PHP and MongoDB developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, connect() that is in an Awards.php file.
The source-code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onrequest();">Add</button>
</div>
</div>
awards.js
function onrequest() {
$("#divAddAward").load('example.php');
alert('Test');
$.post(
'example.php'
).success(function(resp) {
json = $.parseJSON(resp);
alert(json);
});
}
example.php
<?php
include 'Awards.php';
$class = new Awards();
$method = $class->connect();
echo json_encode($method);
Awards.php
<?php
require_once 'mongodb-library/libraries/Mongo_db.php';
include 'mongodb-library/libraries/Mongo_db.php';
class Awards extends Mongo_db
{
//put your code here
public function __construct()
{
parent::__construct();
}
public function connect()
{
$this->load();
//The following code is used for confirmation
$array = array(
$this->message => '1'
);
return $array;
}
public function create()
{
//Code to read
}
public function read()
{
//Code to read
}
public function update()
{
//Code to update
}
public function delete()
{
//Code to delete
}
}
The purpose of my project is to perform CRUD operations on my MongoDB database called, test. I am using the Codeigniter-MongoDB-Library to connect to this database. I have edited the mongodb.php library file accordingly to connect to my database. The config settings for this file are given as follows:
mongodb.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['default']['mongo_hostbase'] = 'localhost:27017';
$config['default']['mongo_database'] = 'test';
$config['default']['mongo_username'] = '';
$config['default']['mongo_password'] = '';
$config['default']['mongo_persist'] = TRUE;
$config['default']['mongo_persist_key'] = 'ci_persist';
$config['default']['mongo_replica_set'] = FALSE;
$config['default']['mongo_query_safety'] = 'safe';
$config['default']['mongo_suppress_connect_error'] = TRUE;
$config['default']['mongo_host_db_flag'] = FALSE;
The problem here is that the connect function is not getting executed; in other words, I am not able to connect to my database successfully. How do I know this? Because on the awards.html page I am getting an output which reads, No direct script access allowed, which is coming from the mongo_db.php file (mind you not the mongodb.php file I have mentioned above).
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.
pushState doesn't make a request, it just changes the url and stores a new history entry. Thinking about this concept, it's impossible to refresh or bookmark because the server will always do a request. A server-side solution is needed.
After several hours searching, I have found a solution, every single call must be redirect to index.php to let PHP handle the request.
rewrite ^/(.*)$ /index.php?page=$1 last
I don't know exactly how this file should be to let a website refresh or bookmark a page. Can somebody help me ? I made an example to help clarify.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>History API</title>
<script>
function ajax (url, callback) {
var conection = new XMLHttpRequest ();
conection.open ("GET", url, true);
conection.setRequestHeader ("X-Requested-With", "XMLHttpRequest");
conection.send (null);
conection.onreadystatechange = function () {
if (conection.readyState === 4) {
if (conection.status === 200) {
callback (conection.responseText);
}
else if (conection.status === 404) {
alert ("Page not found !");
}
else {
alert ("Error !");
}
}
}
}
window.addEventListener ("popstate", function (event) {
var state = event.state;
if (state) {
document.getElementById ("content").innerHTML = state["content"];
}
});
document.addEventListener ("DOMContentLoaded", function () {
var content = document.getElementById ("content");
var menu = document.getElementById ("menu");
menu.addEventListener ("click", function (event) {
var target = event.target;
if (target.nodeName === "A") {
ajax (target.href, function (result) {
history.pushState ({"content": result}, target.innerHTML, target.href);
content.innerHTML = result;
});
event.preventDefault ();
}
});
});
</script>
<style>
body {
width: 400px;
}
div {
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div id = "menu">
Page 1
Page 2
</div>
<div id = "content"></div>
</body>
</html>
index.php
<?php
isset ($_GET["page"]) or exit ("Error !");
$page = $_GET["page"];
// Ajax request
if (isset ($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower ($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest") {
if (file_exists ($page)) {
require_once ($page);
}
else {
header ("HTTP/1.1 404 Not Found");
}
}
else {
require_once ("index.html");
}
?>
page1.html
Hello, I'm the Page 1. It's nice to meet you.
page2.html
Hi brother. I'm page 2.
Clicking (ok)
Refresh (fails)
First of all you should really not use a GET parameter as input for a _require_once_. Really. Not. Use at least a simple whitelist of allowed names for pages and only include and output mapped files (or files with those whitelisted names).
Now to your history API problem. Pushing things obviously seems to work for you so all that is missing is probably a simple ondomready event that reads the current URL and loads the content via AJAX or from existing history entries. The same whitelist approach should be used there. Also try to not fall into the trap of DOMXSS by using unvalidated input (the URL) as input for your javascript and DOM operations.