JavaScript changes a href link url based on user's IP address - javascript

Hopefully someone can assist with this question.
I am looking for simple JavaScript code that will update the a href link url and display it on a static HTML page, based on IP address from which the access request came.
The good thing is – the IP will be static and fixed, it will be the same number, which I already have.
In other words, if I access the same page from different IP addresses, the page will display different link url based on that.
While I might be wrong, my understanding is this can be scripted using ‘if else’ logic – if a specific IP address is detected and matched, the JS rewrites the link address.
Here is my logic below. Sorry, I don’t know much of the JavaScript syntax and used the construct below as a hypothetical example (its probably a total wreck since I didn't use the right syntax and whatnot), but this should give the general idea:
**if (location.referrer.ip('123.45.67.89.00') > -1)**
**document.write.href = 'xxx.com';**
**else if (location.referrer.ip('123.98.76.54.00') > -1)**
**document.write.href = 'yyy.com';**
**else**
**document.write.href = 'zzz.com';**
It is my understanding that since I will be using a single IP address in the formula, the following code can be omitted:
**else if (location.referrer.ip('123.98.76.54.00') > -1)**
**document.write.href = 'yyy.com/';**
Leaving only something like this
**if (location.referrer.ip('123.45.67.89.00') > -1)**
**document.write.href = 'xxx.com';**
**else**
**document.write.href = 'zzz.com';**
Again, this might not be the correct approach altogether and a way more sophisticated solution will be needed, therefore I hope that some of you with coding expertise can provide some assistance. Just to be clear - the script should NOT redirect the page but only update the url behind the link displayed on it instead.
I know there are several technologies already out there that can offer the solution, but my task is to get this running on the client side in the browser; I am not allowed to use server side technologies like Dot.NET, ASP, JSP, or anything other than JavaScript and static html.
Can someone please advice if this can be done this way? Basically, I just need to know if the approach I described above would work and if yes, what is the syntax for 'if' and 'else' lines.
Greatly appreciate any help, Thank YOU!
JK

I went looking for an answer to the same question just today and couldn't find anything. After a bit of tinkering I figured out a solution and registered on this site just to share it.
In my particular situation I was building my website to provide different href's based on the IP, but more specifically whether it was a local IP (192.168.x.x) or an external IP. Objective was to circumvent the NAT loopback problem (external IP address not accessible when connected to the same IP locally)
first off, we're going to use php so rename the file from extension .html to .php, then add this anywhere in your code and just replace the IP with whatever IP you're searching for
<?php
$ipaddress = getenv('REMOTE_ADDR');
if (fnmatch("192.168.*", $ipaddress)) {
echo 'This button is for local IP';
$link = 'http://192.168.2.40:8080';
} else {
echo 'This button is for external IP';
$link = 'http://www.myddns.com:8080';
}
?>
One weird thing I noticed about this is that I couldn't have the link be an image inside the above php tags, so I worked around that by including this after:
<img src="image/pic.png" onmouseover="this.src='image/picMouseOver.png'" onmouseout="this.src='image/pic.png'" border="0" alt="Link">
Note that this code works fine when loaded to a proper web server, but when just double clicking and testing directly in chrome it won't work. Just be aware of that (i.e. you will have to put it on your webserver or install php for windows to test it)
That answers your question... but on a related note I wanted to share something else.
So I have multiple domains that link to the same site, but wanted links to point to the same domain you came in on originally. So for that reason I was stuck using relative links and not the full URL (i.e. so if you found the website from www.website1.com, buttons wouldn't send you to www.website2.com\link.html)
I wanted to figure out how to make a relative link to a different port but learned it couldn't be done without hardcoding the domain. So I combined what I just did above with the instructions here:
Relative URL to a different port number in a hyperlink?
and wrote this method to change the URL just after the page loads, so hovering over the link or doing "Copy Link Location" will get the updated URL with the port number:
<html>
<head>
<script>
function setHref1() {
document.getElementById('modify-me').href = window.location.protocol + "//" + window.location.hostname + ":32400/web/index.html";
}
</script>
<?php
$ipaddress = getenv('REMOTE_ADDR');
if (fnmatch("192.168.*", $ipaddress)) {
// echo 'This button is for local IP';
$link = 'http://192.168.2.40:8080';
$id = '';
} else {
// echo 'This button is for external IP';
$link = 'http://www.myddns.com:8080';
$id = 'modify-me';
}
?>
</head>
<body onload="setHref1()">
</body>
</html>
edit:
You might also find this code to display visitors IP addresses interesting:
<html>
<head>
<title>What is my IP address?</title>
</head>
<body>
<?php
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pipaddress = getenv('HTTP_X_FORWARDED_FOR');
$ipaddress = getenv('REMOTE_ADDR');
echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ;
} else {
$ipaddress = getenv('REMOTE_ADDR');
echo "Your IP address is : $ipaddress";
}
?>
</body>
</html>
source: http://www.cyberciti.biz/faq/how-to-determine-retrieve-visitors-ip-address-use-php-code-programming/

Related

PHP: How to use Javascript inside PHP code

I would like to run one of JS scripts while redirecting to another webpage .. Script to change a variable in Index.php like below code:
if ($flag == 1) {
// echo "<h1> Welcome to Website Home Page </h1>";
if(header("Location: ../../index2.php")) {
echo "<script type='text/javascript'> document.getElementById(body).style.color = 'red'; </script>";
};
} else {
// echo "<h1>Try Again!!!</h1>";
echo "<div class='alert alert-danger' role='alert'>
Your are not a Registered User <i class='fas fa-exclamation-triangle'></i> <br> Please Use below registrarion form.</div>";
}
N.B:
Still Junior learning PHP.
An HTTP redirect tells the browser that it should get the data it asked for from a different URL.
The body of a redirect response should be a message telling the user that they need to request a different URL. It is used in clients which either don't have HTTP redirect support or which have it disabled. Today such clients are practically non-existent.
If you want to run JS on the page being redirected to then you need to embed that JS in that page.
The header function not is for check URL, this function for send HTTP header.
For check url path using REQUEST_URI in superglobal variable $_SERVER.
REQUEST_URI - the URI which was given in order to access this page; for instance, '/index.html'.
More: https://www.php.net/manual/en/reserved.variables.php
Run the following code for research:
echo '<pre>';
var_dump($_SERVER)
About your JS code:
You forgot to enclose the body in quotation marks
I think it will help you.
Add a slash before all single quote ' -- > \'
But above code dose not look ok...
You should add an event Listener, onclick, on something(when you check the URL) and then include your js in a function.

How to store $_SESSION variables in Javascript for XMLHttpRequest purposes?

I asked this question a while ago and I deleted that question because I though I found the appropriate method to solve my issue.
I'm making a website which works with lots of XMLHttpRequest. I need to send the user_id of the logged in client to a php file located elsewhere which will send sql statements to the database, and return the information according to the logged in client. I do not have any knowledge of security. I only have little knowledge of sql and php. So I want to make my website secure, so I need some advice on security and the appropriate way to send user_id via to the php file.
Or does it even matter if the user_id is being shown on the client side. And also I'm storing the unique user_id of the client in the $_SESSION only, nothing else.
I have made my login/sign-up system entirely using this source = https://www.youtube.com/watch?v=xb8aad4MRx8&t=674s
index.php:
<?php
session_start();
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<?php
if (isset($_SESSION['user_id'])) {
echo ('<button>CLICK TO GET INFO IN CONSOLE</button>');
} else {
header ("Location: login.php");
exit();
}
?>
<script>
var user_id = <?php echo($_SESSION['user_id']);?>;
document.querySelector("button").onclick = function() {
var xhr = new XMLHttpRequest();
var url = "http://URL_OF_A_PHP_FILE_LOCATED_IN_A_DIFFERENT_LOCATION";
xhr.open("GET", url + "?user_id=" + user_id + "&var_1=val_1&var_2=val_2&var_3=val_3");
xhr.onload = function() {
console.log(JSON.parse(xhr.responseText));
}
xhr.send(null);
}
</script>
</body>
</html>
You don't have to use javascript to share information between PHP files (even if on separate servers).
$_SESSION is used explicitly to keep data between pages and you should handle it within them as such.
If you have to send user_id to a file on a different server, it's advised to do it inside of your PHP files and not Javascript (which is clientside and thus very prone to be abused).
You could simply use curl to perform a HTTP POST request.
First off, I will assume that you are rather new to PHP, and that is for a very specific reason: $_SESSION is meant to be a server-side storage, and should not go to the client, at any time. Because you may store sensible data in a session, which you do not want to transmit over the network, especially since you dont want any unprevileged person to sniff the data and eventually leave yourself wide open for an RCE (Remote Code Execution) or SQL Injection attack.
When you look at individual values however, that is a little bit of a different story. A User ID can be used - but what if I ran a generator attack against this page with a range of 0 to 100 with each and every of those numbers being used as an ID? You need to consider this at any given time. It is very important.
Now - to actually answer your question.
First, there are two approaches you can take: Actually and really turning over the User ID, as long as you are sure that this ID can not be used for malicious attempts OR you can use Cookies with encrypted values - or, encrypt the cookies in general.
For option one, you'd do this:
var user_id = <?=json_encode($_SESSION["user_id"])?>;
This will encode your user_id into JSON (JavaScript Object Notation) - which essentially is valid JavaScript, per-se. Therefore, if $_SESSION["user_id"] happens to be an integer like 1, the result would look like this:
var user_id = 1;
The second option of using encrypted cookies is a little bit, if not much trickier but also much more secure. Consider this:
<?php
$salt = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$cipher = "AES-128-CTR";
function encryptValue($value) {
$secret = "..."; // See below
$encryptedValue = openssl_encrypt($value, $cipher, $secret, 0, $salt)
. "::" . bin2hex($salt);
return $encryptedValue;
}
function decryptValue($value) {
list($encryptedValue, $salt) = explode("::", $value);
return openssl_decrypt($encryptedValue, $cipher, $secret, 0, hex2bin($salt));
}
?>
(Resource: https://www.the-art-of-web.com/php/two-way-encryption/ )
Now, this is a very, very simplified encrypt/decrypt mechanism based on the OpenSSL extension and it will essentially encrypt values for you - and decrypt them. The important part is the $secret. This is your encryption "password" that is being used to obfuscate what the user gets to see. Because basically, avoiding attacks starts by making it impossible to decipher what the values being sent to the server actually mean. In a production environment, at least. In development, you may actually leave this as clear-text - but that is a different topic.
So, now with those two functions available, you can do this:
<?php
$value = null;
if(array_key_exists("user_id", $_COOKIE)) {
// The user has previously been assigned a `user_id`.
$value = decrypt($_COOKIE["user_id"]);
} else {
// The user is possibly visiting for the first time, so they have no ID.
$value = get_user_id_from_somewhere();
}
?>
Now you will have a $value containing either a fresh ID or one that had been sent beforehand.
But now you need to send this value to the client so it can be used in a XHR request. Well, you will need to set the cookie first. Once done so, you can take the example from the first option and do this:
var token = <?=json_encode(encrypt($_COOKIE["user_id"]))?>;
And with "something" I really mean it - the way you get to your encrypted token is up to you :)
Next, you may want to use it to send a XHR request, so you will need to encode it for a URL. You can even use this right away and save the token variable alltogether with something like:
var url = "http://example.com/other.php?token=<?=urlencode(encrypt($_COOKIE["user_id"]))?>";
To access that URL parameter, use $_GET["token"] in other.php and decrypt it with the function from above (or with any other you come up with, really).
So which option should you choose in which case?
- If you transfer data to your client which you are very sure can not be exploited and is safe for them to know about, use json_encode and the raw variable from $_SESSION. Keep in mind, that session variables are meant to be private to the server. In fact - PHP will actually send a PHPSESSION cookie to the client, which uses such a hashed, almost encrypted-looking string, in order to identify the visitor on subsequent requests.
- If you transfer data which you definitively do not want the client to see or even know about, encrypt it. The fewer the client knows about your business logic (contents of your scripts), the lower are the chances for an attack.
Also: Never trust a user, ever. This is very much an unwritten and yet golden rule. If you are not sure, then go with the most secure method you have at hand. Only if you are very, very sure, send values in a raw format to them - which they will be able to read in all their plain glory.
A little side-note to json_encode: You can also encode an entire array as well: json_encode(["foo"=>"baz"]) will become: {"foo":"baz"}, which is valid JSON, and JavaScript too.
Thus, one more side-note: If you haven't already, use PHP's official manual and start embracing Composer. You can find many, many useful tools there which can make your live as a PHP dev much easier.
I know this is a long answer, but I only mean well =) Good luck with your app!

website with different content for each type of user (about security)

So i know some html, css, js, php and mysql but my knowledge is very limited regarding security issues
and for a website i'm building till now i just used css display:none (triggered with js) to
show or not to show some content to the user depending on his type (client, employee, boss).
I've understood that if you don't want to have the risk of someone seeing something he should
not (inspect page or some other way) you should not send that information(from server-side = php) at all.
I'm not sure if the way i have in mind is the right one.
If i have 3 types of users 1)clients 2)employees 3)Boss
and i want to show different content (basically the same content but a bit more information
to employees and even more to boss) to each of them for 5 of the pages that exist in the website would it be effective
to have 3 different php files(one for each type of user) for each page , store at $_SESSION['authority'] different values for each user during the login process and use that value to decide which page he can access?
For example the starting page is index.php and when the user logs in depending on his authority level (retrieved from database) he will be
redirected by using header("Location: name_of_page.php"); to index.php if he is a client, to index_employee.php if he is an employee
and to index_boss.php if he is the boss.
And in each of these pages use something like the following to prevent users with different authority to enter.
index_boss.php
<?php
session_start();
if($_SESSION['authority'] == 2 && $_SESSION['loggedin'] == true) {
?>
page content
<?php
}
else
{
if( $_SESSION['authority'] == 1 )
{
header("Location: index_employee.php");
}
else
{
header("Location: index.php");
}
}
?>
Is this the correct way to tackle this issue?
Are there ways to just use 1 php file for all users and hide or show some of the content with some other secure way?
YES it possible in the same page to do this! Just do tit like this:
according to: 1)Boss 2)employees 3)clients
index.php
<html>// Start the session here
<?php session_start();?>
<head>
//Your configuration
</head>
<body>
<?php
if($_SESSION['authority'] == 1 && $_SESSION['loggedin'] == true) {
?>
Here the Contents of the boss
<?php
elseif($_SESSION['authority'] == 2 && $_SESSION['loggedin'] == true) {
;?>
Here the contents of employee
<?php }else{ ?>
Here the contents of clients
<?php };?>
</body>
</html>
The appropriate solution here is a role based system. In other words, create 3 roles and put users into those roles. The objects you will need are:
User
Role
Permission
Optionally - application
Optionally - part of an application (action for example)
Create your role based permissions system using these objects. Hope that helps!
Your implementation does seem correct for a low level site. However, as you scale it might be difficult to keep track of these for every single part or sub-part of your website.
I would suggest either using a class approach (create a different class for each user and use objects) or even use a framework which would usually encompass usage of classes within its own structure to ease the process of implementation and coding from your side.
Frameworks you might like to implement include CodeIgniter or Laravel (in no particular order) - bear in mind that at the moment, your code is doing these if checks every single reload - a correctly implemented class or framework would in most cases automatically know what to do giving a slightly quicker reaction time but more importantly, a clearer code structure and a good base to develop on.

How to hide true image path (or revoke access to)?

I own a website where any user can upload photos of their daily lives. Let's, for the sake of simplicity, say all images are located in the following path:
www.example.com/assets/img/<USER_ID>/<PHOTO_ID>.png
The problem is, this allows anyone to view the photos of any person, which is not something I want. For example, here are some URLs anyone could go to and see the photos of any user (and even run a script to get all photos off the site):
www.example.com/assets/img/501/15631.png
www.example.com/assets/img/1375/78974.png
www.example.com/assets/img/2/52.png
How can I hide the true path of the image or prevent a user from viewing that image if they aren't following that person?
There are two general approaches:
The simple one: When storing the images, add a “password-like” string to the file name (e.g. 15631_wCz3YiBZ5A2.png), so that it becomes very unlikely that somebody can guess the name of an existing file.
The clean one: Have the static files served through a PHP file or something which checks if the current user is allowed to view the file. It is more work and puts much more load on the server, but it is more secure and more flexible. This could look like this:
if (userMaySeeImage($imageId))
{
header('Content-Type: image/jpeg');
echo file_get_contents($imagePath);
exit;
}
else
{
die('Nice try, buddy.');
}
This is of course just a generic example, because I don't know anything about your user authentication/authorization mechanisms, and nothing about the way you store the image references.
In the example, userMaySeeImage is a function or method that can determine if the user may access the image, $imageId is the unique identifier for the image, and $imagePath is the absolute path to the image.
Do this, it masks the URL by reading the image and creating a new one.
header('Content-Type: image/jpeg');
$imgPath="http://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Sun920607.jpg/50px-Sun920607.jpg";
$image = imagecreatefromjpeg($imgPath);
imagejpeg($image);
It's an image. It can be copied, someone can do a screenshot, so you don't need more security than to make them undiscoverable. Once someone learns the url of a given image, while logged in, it doesn't matter whether he is logged in or not.
Therefore, this is an ok solution:
Use the hard-to-guess filenames as lxg suggests in the other anwer.
Configure the server to not allow the listing of files. On Apache and others compatible this can be done with a .htaccess file containing the following line:
Options -Indexes
Put that file in the directory you want to disable listings in. When client enters url to directory
www.example.com/assets/img
Instead of list of files and subdirectories he gets error 403 Forbidden
Now it's impossible to view the file listing, and your files are named like this:
3210983j11kjdhasda980132132.jpg so it's impossible to guess their names.
Thats not tight security, but it's simple and it works well enough for very basic privacy.
If you are using .htaccess protection, here is what I would do:
Create an .htaccess protected directory to house the user's pictures. Then, when the user wants to follow someone, they would have to re-enter their password (many places do this for added security). When they were to follow someone, you could use a form like this:
<form name="signup" action="controller.php" method="POST" id="signup">
<input name="user" placeholder="Username"></input><br>
<input name="pass" placeholder="Password"></input><br>
<input type="submit" id="submit" value="Submit" style="border:none; background:MidnightBlue; color:white;" name="submit">
</form>
Then, you need to take their password and place it into the .htpasswd file. Here is that code (let's call this code file "controller.php"):
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$encrypted_password = crypt($password, base64_encode($password));
$data= $username . ':' . $encrypted_password . "\n";
$file = "user-directory/.htpasswd";
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
?>
I have tested this and it works all right for me. If you need anything, just let me know.

Modifying website through email

I wanted to try to do something where I can make changes to my site based on emails received to the sites email. Does anyone know how to do that?
I want something where if its from a specific email address, and follows a particular format, it will change a certain part of the site according to the contents of the email.
Sure you can.
You need:
Script that parses emails on schedule and adds those changes to some type of database
Script that executes updates from the temporary database and adds that data to live database
How to read email with PHP:
$mb = imap_open("{host:port/imap}","username", "password" );
$messageCount = imap_num_msg($mb);
for( $MID = 1; $MID <= $messageCount; $MID++ )
{
$EmailHeaders = imap_headerinfo( $mb, $MID );
$Body = imap_fetchbody( $mb, $MID, 1 );
doSomething( $EmailHeaders, $Body );
}
read more
You would need some server side processing to be able to do this. This thread has a couple of ways of doing this using PHP, made easier with cPanel to make changes to the mail redirects. If you tell us more about your site and hosting environment, we may be able to give better suggestions.
The server side script would need to then parse your email and perform whatever updates your commands intend. Security is also very important, and it is trivial to forge the 'From' address when sending email.

Categories