JavaScript function that sends user to another site - javascript

I'm trying to make a simple JS function that takes a few of my sites and send the user to a random site once the script activates. I'm using it in two locations one of them is in the navigation php which I include on all sites, and the other is on a hottest.php site.
const rng = new Array();
rng[0] = "http://localhost/joker.php";
rng[1] = "http://localhost/loophero.php";
rng[2] = "http://localhost/godofwar.php";
rng[3] = "http://localhost/friends.php";
function randomlink(){
window.location=randomlinks[Math.floor(Math.random()*randomlinks.length)]
}
I've tried adding onload to the body of a site to test however it does not send to another site once clicked. Don't know it means much but I'm testing my php site on mamp local server.
I use the randomlink in 2 situations on for testing peropuses but neither of them work those are
<li class="nav-item">
<a class="nav-link" href="hottest.php" onclick="randomlink();"><i class="fas fa-fire"></i></a>
</li>
and
<head>
<title>DIGIME</title>
<?php require $meta;?>
<?php require $css;?>
<?php require $bootstrapCss; ?>
<?php require $script; ?>
</head>
<body onload="randomlink();">
<?php require $navigation ?>
The solutions I've found online seem to work for others however they do nothing for me, could this be related to my sites being .php? (Note that other js functions I have work on the sites).

Easy, you are using randomLinks in your function, and its undefined.
You have 2 ways to fix your code
Method 1: Add a parameter to your function
const rng = new Array();
rng[0] = "http://localhost/joker.php";
rng[1] = "http://localhost/loophero.php";
rng[2] = "http://localhost/godofwar.php";
rng[3] = "http://localhost/friends.php";
function randomlink(randomlinks){
window.location.href = randomlinks[Math.floor(Math.random()*randomlinks.length)];
}
And then you can call your function using rng as a parameter: randomlink(rng)
Method 2: Define the links inside the function:
function randomlink(){
const rng = new Array();
rng[0] = "http://localhost/joker.php";
rng[1] = "http://localhost/loophero.php";
rng[2] = "http://localhost/godofwar.php";
rng[3] = "http://localhost/friends.php";
window.location.href = rng[Math.floor(Math.random()*rng.length)];
}
And then you can call your function without using any parameter: randomlink()

Related

How to shorten url when sharing a webpage from my website on social media?

How to shorten url when sharing a webpage from my website on social media?
I hope it can be done with javascript and apis, I've checked the bitly api, but don't know how to get starting.
Thanks.
I have 2 useful resources for you:
This one for google url shortener: http://www.i-visionblog.com/2014/07/google-url-shortener-api-javascript.html
And this one for bit.ly: https://bdhacker.wordpress.com/2010/03/30/dynamically-use-bitly-in-your-site-easiest-way/
First, you need an account on http://bit.ly. To create one, go to the
site and register.
Once you’ve registered, login and go to your Account page. There, you
will find your API key.
Put this in your HTML HEAD:
<script type="text/javascript" charset="utf-8" src="http://bit . ly/javascript-api.js?version=latest&login=******&apiKey=*****************"></script>
(remove spaces in bit.ly url. stackoverflow doesn't allow to post answers with that url)
Put this before </body>:
<script>
// Bit.ly API
BitlyCB.shortenResponse = function(data) {
var sss = '';
var first_result;
// Results are keyed by longUrl, so we need to grab the first one.
for (var r in data.results) {
first_result = data.results[r]; break;
}
sss = first_result["shortUrl"].toString();
document.getElementById("qlink").value = sss;
}
BitlyClient.shorten(window.location, 'BitlyCB.shortenResponse');
</script>
And this, somewhere in your page:
<h3>Link to this page</h3><br>
Use this link to tell others about this page! <input onclick = "this.select()" type = 'text' id = "qlink" style = "width:100%;">

Save data by MySQL after click a link to an external web

I want to put a clicks counter on banners on my page so advertisers get an idea of how many visitors arrive via my website.
I've seen that could be done by directing the link to an intermediate page that access MySQL (to save the data in a record BD) using PHP, and then redirected to the advertiser's website, but I wonder if there otherwise somewhat more "elegant" to do so.
Could anyone tell me if it is possible?
I've found an similar example, but this one donwload a file and count the visit (I only want to go to another web)
EXAMPLE HTML
<span style="font-family: Verdana, Arial, Helvetica, sans-serif;"><a href='files/my_file.zip' id='25' onClick='dc(this.id)' target='_blank'>Download this file</a> </span>
EXAMPLE Javascript
function dc(id){$.post("process.php",{file_id:id})}
EXAMPLE Process.php
$file_id = $_POST['file_id'];
mysql_query("UPDATE file SET downloads = downloads + 1 WHERE id = " .$file_id);
I tried to adapt this example to my code, like this:
HTML
echo '<br><a onClick="sumar(this.id);" href="http://'.$result['WEB'].'" id="'.$result['ID_PAG'].'" target="_blank">'.$result['WEB'].'</a><br />';
Javascript (In head section)
function sumar(id){($.post("suma.php",{pag:id})}
Suma.php
$pag=$_POST['pag'];
$mysqli->query("UPDATE lapag SET visitas=visitas+1 WHERE id_pag=".$pag);
Thank You!
Are you sure you have the apostrophs right? I c/p html part into eclipse and it did not particularly like it.
echo "<br><a onClick='sumar(this.id)'";
echo "href='http://".$result['WEB'] . "'";
echo "id=". $result['ID_PAG'] . 'target="_blank">';
echo $result['WEB']. "</a><br />";
I have broken it up into several echoes in order to make it clearer and easier to handle.
HTML
<?php echo $result['WEB']; ?>
Sumar.php
$pag=$_GET['ID_PAG'];
$mysqli->query("UPDATE lapag SET visitas=visitas+1 WHERE id_pag=".$pag);
header("Location: http://".$_GET['WEB']); // redirect
exit();
Think best practice should look like this:
<a href="http://random.org" onclick='called(event, this, "clicked")'>Visit site</a>
function called(event, link, id){
event.preventDefault();
event.stopImmediatePropagation();
var theUrl = "counter.php";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange=function(){
if (this.readyState != 4) //4 means call is finished - we just want to switch side after the counter-call finished
return;
window.location.href = link.href.value;
};
xmlHttp.open("GET", theUrl, true);
xmlHttp.send("id="+id);
return false;
}
Example: http://jsbin.com/porotobuna/1/edit?html,js,output
In the counter.php just get the get variable "id" (which represents the clicked link) and handle the counter (I recommend some kind of database)

Php & code injection

The website for a client of mine continues to be "hacked" (I didn't do the website).The hacked pages contain a js script that loads an image and audio from youtube (Lol). Every page was modified and every page has a "news banner" .I'm pretty sure the problem is this part
<?php
$ul = new NewsList;
$ul->Load(3);
if($ul->Current() == null){ ?>
<?php }
else{
for(; $ul->Current() != null; $ul->Next()){
$new = $ul->Current();
the complete implementation of this NewsList : http://pastebin.com/WuWjcJ4p
I'm not a php programmer so I don't get where the problem is....I'm not asking that someone going to explain every line, maybe only an advice , thank you
Sounds like an SQL injection.
I believe the loadById() method is injectable (depending on how you call it).
Here is a way to strengthen it :
function LoadById($id){
$this->news = array();
$this->current = 0;
$this->total = 0;
$ndb = new NewsDB('news');
$result = $ndb->_query("SELECT * FROM ".$ndb->table." WHERE id = " . intval($id));
$new = mysql_fetch_assoc($result);
$n = new News($new['id'], $new['titolo'], $new['data'], $new['contenuto'], $new['img']);
array_push($this->news, $n);
unset($n);
$this->total = 1;
}
Someone might have stolen the passwords from administration using this security flaw and edited the articles from the back-office.
So I suggest you change this code, then change the passwords, delete all php sessions, and finally edit your articles to remove this "news banner".
Note that it might as well be a stored XSS.
Do you have a system which allows to comment the news?

How to scrape page links from dynamic web page using PHP?

I'd like to scrape the actual the dynamically created URLs in this web page's menu using PHP:
http://groceries.iceland.co.uk/
I have previously used something like this:
<?php
$baseurls = array("http://groceries.iceland.co.uk/");
foreach ($baseurls as $source)
{
$html = file_get_contents($source);
$start = strpos($html,'<nav id="mainNavigation"');
$end = strpos($html,'</nav>',$start);
$mainarea = substr($html,$start,$end-$start);
$dom = new DOMDocument();
#$dom->loadHTML($mainarea);
// grab all the urls on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++)
{
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
}
}
?>
but it's not doing the job for this particular page. For example, my code returns a url such as:
groceries.iceland.co.uk//frozen-chips-and-potato-products
but I want it to give me:
groceries.iceland.co.uk//frozen/chips-and-potato-products/c/FRZCAP?q=:relevance&view=list
The browser adds "/c/FRZCAP?q=:relevance&view=list" to the end and this is what I want.
Hope you can help
Thanks
Edit: Just to confirm, I had at look at the website you're trying to scrape with JavaScript turned off and it appears that the Mainnav urls are generated using JavaScript, so you will be unable to scrape the page without using a headless browser.
Per #Sam and #halfer's comments, if you need to scrape a site that has dynamic URLs generated by JavaScript then you will need to use a scraper that supports JavaScript.
If you want to do the bulk of your development in PHP, then I recommend not trying to use a headless browser via PHP and instead relying on a service that can scrape a JavaScript rendered page and return the contents for you.
The best one that I've found, and one that we use in our projects, is https://phantomjscloud.com/

Get webpage and read throug it using javascript

Hi i have a quick question, say that you would like to connect to a website and search it for what links it contains, how do you do this with javascript?
I would like to do something like this
Var everythingAdiffrentPageContains = //Go to some link ex www.msn.se and store it in this variable
var pageLinks = []; var anchors = everythingAdiffrentPageContains.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
We can assume here that we have acces rights to the site so this is not of a concern.
In other words I would like to go to some site and store all that sites Hyperlinks in an array, how would you do this in javascript?
Thanks
EDIT since pointed out Im not trying to connect to another domain. Im trying to connect to another apache webserver inside my lan that hosts a website that I would like to scan for links.
Unfornuatley I do not have PHP on my webserver :/ But a simple javascript would do it
for example go to X:/folder/example.html
Read it, and store the links
Unfortunately - You can't do this. "We can assume here that we have acces rights to the site"...that's a false assumption from a JavaScript point of view, if the page is on another domain. You simply can't access content on another domain (not HTML content anyway) via JavaScript. It's prevented by the same-origin policy, in place for several security reasons.
I suggest you to use a JS framework that helps you to retrieve elements and do stuff with DOM easily.
For example using mootools you could achieve this writing some code like this:
var req = new Request.HTML({
url:'./retrieve.php?url=YOURURL', //create a server script to "retrieve" the html of another domain page
onSuccess: function(tree,DOMelements) {
var links = [];
DOMelements.getElements('a').each(function(element){
links.push(element.get('href'));
});
}
});
req.send();
The retrieve.php page should be written for example in this way:
<?php
$url = $_GET['url'];
header('Content-type: application/xml');
echo file_get_contents($url);
?>

Categories

Resources