Modifying website through email - javascript

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.

Related

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!

Using Twilio JS client, how can I call to a number entered in the texbox?

In order to make outbound call from browser, I followed "https://www.twilio.com/docs/quickstart/php/client/outgoing-calls" link, and now I can make outbound browser call to a particular number(Which hardcoded behind).
But If I am entering a number in the text-field, to make call to this number, then how can I do this?
Please help me.
for your reference I have attached the screen-shot.
Screen to make outbound call
Thanks
Twilio evangelist here.
The Outgoing Calls sample code already includes the client side JavaScript to grab a phone number from an input field in the webpage and include it as a parameter in the connect() function:
function call() {
// get the phone number to connect the call to
params = {"PhoneNumber": $("#number").val()};
Twilio.Device.connect(params);
}
Specifically this code: $("#number").val() gets the value from an input field named number.
One the server side, Twilio will take the collection of parameters that you provide to the connect function and forward those to the URL you have specified as your TwiML Application URL as simple form-encoded values. You can use PHP's $_REQUEST global function to grab those and dynamically generate a TwiML response:
<?php
if (isset($_REQUEST['PhoneNumber'])) {
$number = htmlspecialchars($_REQUEST['PhoneNumber']);
}
?>
<Response>
<Dial callerId="+15555555555">
<?php echo $numberOrClient ?>
</Dial>
</Response>
Hope that helps.

I'm putting my entire $_SESSION variable into a json object on page load. While this works for me, is this a good practice?

I've been doing something this at the bottom of all my views:
<script type='text/javascript'>
$.post('php/ajax.php', {type:'session'}).done(function(data){
var session = JSON.parse(data);
$(document).ready(function(){
$.getScript('resources/redactor/redactor.js');
$.getScript('javascript/year_long_calendar.js');
$.getScript('javascript/edit_lesson_modal.js');
});
});
</script>
This works really well for me. All my scripts get loaded inside of a single docReady, and all my ajax requires a token that gets generated upon login and stored in $_SESSION. This stops people from hitting my ajax logic using fake headers. By doing this, my ajax calls look something like:
$.post(url:'ajax.php', {token:session.token, id:id}).done(function(data){ ... });
I can also access other session variables
var user_id = session.user_id;
Since I've been doing this from the start of the project, I intentionally keep any sensitive information like passwords out of the session variable. What are your thoughts on this? Does any of this strike you as insecure, or terribly inefficient? I realize $.getScript is often used as a lazy way to load libraries, but I think I've found a pretty valid use for it.
None of the data in $_SESSION is sensitive except the token, and you have to be logged in to get one. Unless someone malicious hops on a machine while the real user is away and knows exactly where my ajax logic is, how it works, how I store my session, and fakes a quick header on PostMan to delete all my tables, I don't see it being an issue.
EDIT:
#AnotherGuy helped me realize a much better solution. My ajax.php file now looks like this:
<?php session_start();
include('connect.php');
include('functions.php');
// check to see if http request is ajax (easy to fake but hey might as well)
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
// when the user logs in, a random number is generated and saved to $_SESSION['token'].
// this block is used to pass the token to a javascript variable securely
if($_POST['type'] == 'session'){
$session = [
'token'=>$_SESSION['token'],
'user_id'=>$_SESSION['user_id']
];
echo json_encode($session);
}
// all post requests must pass the correct token variable to step into this block and access the ajax logic
if(isset($_POST['token']) && $_POST['token'] == $_SESSION['token']){
if($_POST['type'] == 'get'){
$where = null;
if(isset($_POST['where'])){
$where = json_decode($_POST['where']);
}
$order_by = null;
if(isset($_POST['order_by'])){
$order_by = json_decode($_POST['order_by']);
}
echo json_encode(get($_POST['db'], $_POST['table'], $where, $order_by)->fetchAll());
}
if($_POST['type'] == 'put'){
$set = json_decode($_POST['set']);
echo put($_POST['db'], $_POST['table'], $set);
}
if($_POST['type'] == 'update'){
$set = json_decode($_POST['set']);
$where = json_decode($_POST['where']);
update($_POST['db'], $_POST['table'], $set, $where);
}
if($_POST['type'] == 'delete'){
$where = json_decode($_POST['where']);
delete($_POST['db'], $_POST['from'], $where);
}
From how you describe you are using the session I cannot see any harm in it, but I still think it is dangerous. Imagine you in the future work on another project and then come back to this. Will you still remember not to store any sensitive information inside the session? As a basic rule of thumb is to never store sensitive information in the session unless it is the only solution, which it rarely is. But sometimes mistakes are made and they can hurt you!
I would change this to something that looks/works in the same way, but offers you more decoupling from the session. If you are fetching the entire session you are bound to retrieve some information which would never be used or should never be available to client side (through Javascript). I would create a single page that you request which can only provide the necessary information. That way you can also ensure only required information is exposed to the client side.
So instead of requesting a generic ajax.php file, I would create a page called (or something like it) userInfo.php. That way you can also eliminate the type variable you send along with it.
Hope this can help you, happy coding!
You could store that session data in browser with sesssionStorage in a serialized JSON string and manipulate it from there. Many recommend this approach over using cookies W3Schools
Cheers.

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

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/

HTML email confirmations - can I us js or php within the email?

I created an html email confirmation that gets sent to people who fill out my order form.
In the Shipping Address fields of the email I want it to show either: the separate shipping address they entered OR the same info from their billing address IF they didn't enter separate shipping info. This is what I have done:
<td><?php
$txt = false;
if( file_exists( 'text46' ) )
$txt = file_get_contents( 'text46' );
else if ( file_!exists( 'text46' ) )
$txt = file_get_contents( 'text12' );
?>
</td>
Dont' laugh. I got this code from somewhere else and it looked like the closet thing I've seen that could work (but it doesn't). But I have NO idea what some of it means. Like: should $txt=false?
I don't know. I just need this table data in the email to show 'text46' (the shipping address) if it was entered on the form, and if it wasn't then I want the table data to show 'text12' (the billing address). Can this even be done in the actual email?
I'm a MAJOR beginner and I know what I want it to do, but I have no idea how to do it.
You can't put code inside an e-mail and expect that it will work because of some simple reasons:
When people receive your e-mail, the service that handles it automatically blocks any code inside of it from being executed. So javascript will not work, PHP neither, and so on. It would be a huge security flaw if this could be possible.
PHP will never work anyway because is a server-side language. This means that it can't be executed on your pc. It needs to be executed on a server that sends a response back when finished.
Lear more about what server-side means: http://en.wikipedia.org/wiki/Server-side_scripting
Update:
Need to let everyone know that I found a solution. Instead of putting anything IN the email that would get ignored by email clients, I found some code that would auto-fill the Shipping fields on my form if a box was checked. Then I get the results in the email like I wanted.
I could have done this months ago if I had known to ask if emails would even work with scripts in them. Your answers helped me look for a different way to get the overall job done.
Thanks for all the help guys!
Here is the code I used for the auto-fill and the check box:`
<script type="text/javascript">
function SetShipping(checked) {
if (checked) {
document.getElementById("Shippingitem46_text_1").value = document.getElementById("item12_text_1").value;
document.getElementById("Shippingitem47_text_1").value = document.getElementById("item17_text_1").value;
document.getElementById("Shippingitem48_text_1").value = document.getElementById("item14_text_1").value;
document.getElementById("Shippingitem49_select_1").value = document.getElementById("item15_select_1").value;
document.getElementById("Shippingitem50_text_1").value = document.getElementById("item51_text_1").value;
document.getElementById("Shippingitem52_text_1").value = document.getElementById("item18_text_1").value;
} else {
document.getElementById("Shippingitem46_text_1").value = '';
document.getElementById("Shippingitem47_text_1").value = '';
document.getElementById("Shippingitem48_text_1").value = '';
document.getElementById("Shippingitem49_select_1").value = '';
document.getElementById("Shippingitem50_text_1").value = '';
document.getElementById("Shippingitem52_text_1").value = '';
}
}
</script>
<div class="fb-checkbox" style="color: rgb(168, 28, 45); font-weight: bold; font-size: 11px;">
<input type="checkbox" onclick="SetShipping(this.checked);"/>Check Box to copy info to Shipping.
</div>`

Categories