0

I was trying to find an online tool to generate a new link which randomly redirects to user defined array of links.

Please check out http://mathstatic.co.nz/auto to see what I am trying to do. Problem with that site is that it is wordpress and you can only enter 2 links. I want to do something similar but with user defined number of links.

Please take a look at the code I have for what I put together today: http://rpantaev.com/RedirectLinkTool/

After researching, it seems that I need to use PHP and perhaps a database like mysql to store users' data, but I am not familiar with PHP so any pointers will be greatly appreciated.

So far php is installed on my server and I added .htaccess so html can read php. I put together a webpage with html/css/js that takes in user defined number of links, checks for http://, stores in array and redirects to randomly chosen url (array is not persistent and no new url is generated).

How can I recreate what the first link does and incorporate that into my website?

Thank you!

1 Answers1

0

So the language you use will depend on what languages your server supports or whether you can install your own. If your looking to run a server on your computer to just test this out, you just need to install the language you want to use then find a way to run as server on your computer.

You can use any database (postgres, mongodb), to store your urls. If it's ok to use memory for this project then you can use a dictionary to store the random urls.

Here's a way to do this using Node.js. In this solution, I create a server on port 9898 and create an in memory database using a dictionary. When there are entries, the database will look like this:

{
   "uuid1": { id: "uuid1", urls: ["https://www.google.com", "https://youtube.com"] },
   "uuid2": { id: "uuid2", urls: ["https://www.google.com", "https://youtube.com"] }
}

uuid1 and uuid2 would be replaced with actual unique IDs.

In this solution, I'm expecting that the client will send a json object.

The solution depends on expressjs and body-parser packages. Here's actual code that I test on my computer.

const express = require('express')
const bodyParser = require('body-parser');
const app = express()

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

const port = 9898
const host = `http://localhost:${port}`

// you would replace this with an actual database
const db = {}

// to generate a uuid
// from: https://stackoverflow.com/a/2117523
function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function success(message) {
    return JSON.stringify({
        success: message
    })
}

function error(message) {
    return JSON.stringify({
        error: message
    })
}

// assuming body looks like this { urls: ['www.google.com', 'www.gmail.com'] }
app.post('/gen', (req, res) => {
    const gen = req.body
    // check if the json in the request has the list of urls
    if(!(gen && gen.urls && gen.urls.length > 0)) {
        // if not then log the body and return a json object with the error object
        console.log('body', req.body)
        return res.send(error('I cannot find the list of urls in json body.'))
    }
    // generate a uuid
    const id = uuidv4()
    // save the urls with the new id
    db[id] = {
        id: id,
        urls: gen.urls
    }
    // respond with the url that the user should use
    res.send(success(host + '/' + id))
})

app.get('/:id', (req, res) => {
    // get the id paramater from the request
    const id = req.params.id
    // check if that id was saved, if not send an error message
    if(!db[id]) 
        return res.send(error('that url does not exist'))
    // grab a random element from the list of urls
    const urls = db[id].urls
    const url = urls[Math.floor(Math.random() * urls.length)]
    // redirect the user to the random url
    res.redirect(url)
})

// start the server
app.listen(port, () => {
    console.log('listening on port: '+port);
})

/*

example request:
curl -X POST -H "Content-Type: application/json" -d '{"urls": ["https://www.google.com", "https://www.yahoo.com", "https://www.youtube.com"]}' localhost:9898/gen

after doing this you grab the url generated and paste into your browser.
for example when I ran this it generated: http://localhost:9898/aa582177-4ab5-4ede-99c5-a06b43976c12

*/

If you've never setup a nodejs project before this page can get you up to speed: https://docs.npmjs.com/getting-started/installing-node After install nodejs and npm. create a folder for the project. In your command line, go to this directory. To setup the project and install the two packages, write:

npm init -y
npm install express body-parser

After doing that create a file named index.js in that folder. Then paste the code in. Then to run the server use this command:

node index.js

If your on MacOS or Linux, or have a way to use curl on Windows you can use this example request:

curl -X POST -H "Content-Type: application/json" -d '{"urls": ["https://www.google.com", "https://www.yahoo.com", "https://www.youtube.com"]}' localhost:9898/gen

Then that should return a url for you to use. For example for me it generated this:

http://localhost:9898/aa582177-4ab5-4ede-99c5-a06b43976c12

You would paste the url generated into your browser and it should reroute you to one of the urls in the list.