Easiest way to store data from web site (on server side) - javascript

I have very simple web site (which is actually single page), there is one input field and a button.
I need to store data submitted by users somewhere on server side. Perfect way could be simple text file and new lines appended to it after each button click. Log file will be also ok.
As I understand it is not possible with JavaScript itself. I'm looking for easiest solution, preferably with no server-side programming (but if it is required, it should be as easy as possible and work out-of-box). I can use some side service if it could be helpful.
Please help.
Thanks in advance.
UPD. Just want to rephrase the main question. I do not really need to store something on server side. I need to collect some input from users. Is it possible? It would also be ok if it for example will be just sent to my e-mail.

For a very simple form-to-server-log script:
Your form:
<form action="save-to-log.php" method="POST">
<fieldset>
<legend>Add to log</legend>
<p>
Message:
<textarea name="message"></textarea>
</p>
<p>
<input type="submit" value="SAVE" />
</p>
</fieldset>
</form>
Then save-to-log.php
<?php
$log_file_name = 'mylog.log'; // Change to the log file name
$message = $_POST['message']; // incoming message
file_put_contents($log_file_name, $message, FILE_APPEND);
header('Location: /'); // redirect back to the main site
if it's a unix host you'll need to add 755 permissions to the directory of the log so PHP has access to write to it. Other than that, you'll have a form that keeps appending information to mylog.log.
Follow-Up
If you don't necessarily need it store on the server (you mentioned email) you can use the following instead as the PHP script:
<?php
$to_email = 'kardanov#domain.com';
$subject = 'User feedback from site';
$message = $_POST['message'];
// this may need configuring depending on your host. If you find the email isn't
// being sent, look up the error you're receiving or post another question here on
// SO.
mail($to_email, $subject, $message);
header('Location: /');

You can't store information on the server without some sort of server side script.
There are two different places to store data, on the client and on the server.
On the client side, there are lots of ways from cookies to Store.js, however it sounds like you want to store the information on the server.
To store on the server you need some sort of application that can receive posts from javascript/http and save them in a file.
In your case a very simple PHP script like the below would be perfect:
<?php
//Was the request (post or get) parameter data supplied?
if(!empty($_REQUEST['data']) {
$file = 'log.txt';
$data = $_REQUEST['data']."\n";
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
?>

How about dumping JSON to a file with PHP and then loading it on request?
How to safely write JSON data to file using PHP

If you want to get the data sent to your email address, there are several free services that can do this without installing any server side applications... A PHP or CGI script is still being used but it is hosted by the service, not by you.,
All you have to do is paste some code into your site and then all submitted data will be sent to your email address., A lot of people don't have the know-how to do this on their own, or their hosting service will not allow send-mail to work. Thats why these services exist. And of course most of them are supported by ads that are placed in the email that you get from the form. Anyway, here is the link for a good service I found. You can also Google "Free Form Processing" to find more.
https://secure.tectite.com/hf/auth/GetStarted?WWWTECTITE
Hope this helps.

Related

End Session in all browser after logout.php

I currenly have this on my logout.php
<?php
//LOGOUT.PHP
session_start();
//// unset all $_SESSION variables
session_regenerate_id();
session_unset();
session_destroy();
$_SESSION['logoutsuccess'] = 'You have successfully logged out.';
header("Location: index.php");
exit;
But after changing password using changepassword.php that has logout.php in the end. It just destroy the session on current tab. But it doesn't destroy the session on the other browser/tab. TIA!
Do this:
$_SESSION = array();
session_destroy();
setcookie (session_name(), '', time()-3600);
You can try this
//LOGOUT.PHP
session_start();
//// destroy all $_SESSION variables
session_destroy();
echo "<script>alert('You have successfully logged out.')</script>";
echo "<script>window.open('index.php','_self')</script>";
What you are attempting to do isn't easy when it comes to pure PHP. Javascript will be your friend in a situation like this.
If I were to implement this I would create something in JS that checks every x amount of seconds/minutes with the backend to see if the password has changed. This will require a separate endpoint that is specifically for this check.
Here would be a rough outline of what I would consider doing:
When the user logs in take the username and hashed password to create a hash of that data using something like $userAuthHash = sha1("{$username}${password_hash}) and save that in the user session.
In your page (in the header more than likely) display the created hash. This is generally best to do in a meta tag in the header (ex: <meta name="user_auth_hash" content="<?php echo $userAuthHash; ?>">). You can obviously set this up however you want as long as you can look it up using JS.
Have the JS script get the value of the hash from the meta tag and every x interval send this to the validation endpoint. The endpoint should in some way indicate if the users token is still valid.
If the users token is no longer valid you can have the JS script redirect the user to the logout script as needed.
There are a lot more complex ways of doing this but this is one of the easiest ways of going about this that I know of.
Also remember not to over think these things when building software. Security is important but imagine the case where an account gets hacked and the hacking party changes the password. Your now legitimate user has been logged out and thats never any good. This would be a case where you would need to evaluate your initial strategy and possibly implement an email that forces the user to validate a password change before it is persisted to the database. Just some food for thought.

Access PHP SESSION value in JavaScript

I generate a session value for each visitor on my website. If they submit the form, it sends the data via a jQuery AJAX request to my PHP validator script.
This script performs several checks on the data the user submitted. If everything has been validated, it returns a sha256 hash which is generated with the function hash_hmac('sha256', 'success', $_SESSION['secret_key']). I hash this so users cannot manipulate the response with software such as Charles.
The jQuery request receives the hashed string and I have to hash 'success' with the secret key again to check if they match. However, the secret key is stored in a PHP session and I am not able to figure out how to get access to it through JavaScript.
An AJAX request to a PHP script would not be ideal — an attacker can then edit the response to make it match with their own hashed strings.
I'll simply elaborate on my comments in this answer.
You say
An AJAX request to a PHP script would not be ideal — an attacker can
then edit the response to make it match with their own hashed strings.
They can edit the response, but if it's all done client side, they can still edit it.
You want to send the data hashed, then you want the client to be able to check the hash, so I'm not sure what the point in hashing would be, other than security in transport. I can't tell you what you really need, because I'm not seeing the use case here.
I do know you'll either need to go to the server for something you want to keep secret from the client. There's no security on the client side.
As long as you are using javascript in your php file, something like this will suffice...
<script>
var secret_key = <?php echo json_encode($_SESSION['secret_key']); ?>
<script>

How can my javascript code get access to POST variables?

This is an odd situation and my current thought is that it doesn't work this way, but I need to some other eyes on this.
A different website I don't have control over has a form with a hidden field in it. The form action is a POST and to send it to a url on my website and I need to be able to get the value of that hidden field using javascript.
As a GET that would be included in the url and I think I would just be parsing that apart. But since it's a POST being sent to me I'm not entirely sure how to get the value of that hidden field out.
Is this doable? If so, where should I be looking to do it?
Thank you!
If your server that is receiving the sended form data uses PHP, you can get all form values using:
<?php
print_r($_POST);
?>
If the page in your server is a static html page, then you cannot get the POST data. Or you can, but then you have to make html pages to be executed as php pages (not recommended however).
You talk about that you need this value be accessible by javascript. Simply do something like:
<script>
<?php
echo 'var input_field_value="'.htmlspecialchars($_POST['name_of_input_field']).'";';
?>
</script>
The question doesn't provide information what server software is used, so I assume that is PHP.
EDIT: after Saturnix's comment I added a call to htmlspecialchars() to make it safe to execute in javascript.

How do I get user-inputted information from the website directly to my e-mail?

So I've decided to make a website a few months ago and have then picked up basic HTML, CSS, Javascript and Jquery. Now I want to do two things with my website,
show a user-voted poll somewhere on my website that will update live as the users vote on different optinos.
A form on my website that when the user fill out and click the "submit" button, the form will automatically be forwarded to my desired e-mail address
I've been told to learn PHP because it's suppose to help my problem, but so far I have yet to see how it's going to help me solve the above two problems. Any suggestion on how I can achieve the two things above??
PS: if someone can explain what exactly is PHP, I will also be really grateful. I've been looking up what PHP is and the majority of the responses I get is "it's a server side language", which is not exactly helpful. And if PHP does help me solve the two questions above, how?
PHP standing for Hypertext Preprocessor, is a server side programming language. Taking a look at what you have currently learned (HTML, CSS and Javascript) these are all Client side languages.
The difference is that any processing done by a client side language is done within the browser straight in front of the user's eyes.
A server side language like PHP is used when we want to compile relevant data from sources like a MySQL database, before sending the information to the browser. Meaning it's far more dynamic.
You should start by going through some tutorials, do not use w3schools.com, because I don't believe they teach the best practices and it will probably do you more harm than good in the long run.
A quick google search should lead you to some decent tutorials, however I'd highly recommend http://php.net/manual/en/getting-started.php
PHP is actually a "server side language" (mostly) :)
It means that it allows your web server to be smart, i.e:
load/read data from a database
send emails
generate pages dynamically (instead of just serving static pages)
etc...
Sending mail with PHP is documented here: http://us2.php.net/manual/en/function.mail.php
Basically in your HTML you'll tell your form to be posted to a specific PHP script which is hosted on your web server, e.g:
<form action='send_mail.php'>.....</form>
And this script will retrieve the form data and handle the mail sending, e.g:
<php>
$data = $_POST; // contains the form's input values
mail("foo#mail.com", "Notification mail", "A form has been submitted with some data: ".$data["fieldName"]);
</php>
PHP is exactly what they have told you - a server side scripting language. What that means is that PHP will perform actions at the server level before rendering a page. This includes:
Loading dynamic content from a database
Posting information from a form to a database
Sending it to an email address like what you want to do
A lot of other stuff you'll learn if you stick with it.
To send an email when someone submits your form, the form needs to post to a PHP page.
Your form:
<form method="POST" action="sendmail.php">
<input type="text" name="name" />
<!-- Other inputs go here, etc. -->
<input type="submit" value="submit">
</form>
PHP to send the form (In sendmail.php)
<?php
$email = $_POST['inputName1'];
$name = $_POST['inputName2'];
$message = $_POST['inputName3'];
$phone = $_POST['inputName4'];
$yourEmail = "youremail#domain.com";
$to = $yourEmail;
$subject = "My Contact Form";
$message = $message;
$from = $email;
$headers = "From:" . $name;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
Here is a tutorial I found via Google: http://www.daniweb.com/web-development/php/threads/38784/php-sendmail-tutorial
There are probably better ones, but that should get you started.
Long story short, you need to learn PHP, and javascript.
Your other requirement (The poll) can be done many different ways, just google "Set up an online poll" for different ways. You can probably use jQuery/javascript and JSON, or XML, etc to power the polls as well as php. This tutorial may help you with that: http://net.tutsplus.com/tutorials/javascript-ajax/creating-a-dynamic-poll-with-jquery-and-php/
Good luck.
PHP is processed at the server level and the results are sent to the client's computer for display. JavaScript does its processing on the client's computer.
You can use the PHP Mail function to have the data entered in the form by the user sent to your email. Here is a link on how to use that: http://www.w3schools.com/php/php_mail.asp

Is possible to get the previous form POST variable using javascript?

Client goes to example.com/form.html where a html POST form is displayed
Client fills the form with specific information and submit it to example.com/form.html
When example.com/form.html receives the POST request redirects the Client on example.com/redirected.html
Is possible to retrieve the variables that the client filled and POSTed to example.com/form using javascript ? The javaScript being deployed on example.com/redirected.html only . I presume that can be some "back" controls iframes and ajax involved but I couldn't find a reliable solution yet.
The operation will take place on the same domain so no cross domain issue is involved
Nope, I don't think this is possible.
You have to either
Store the posted value in a cookie
Store the posted value in a session variable on server side
Add the posted value as a GET parameter to the new URL
Use GET to post the original form, and painfully extract the posted value from document.referer on the new page
With HTML5, use localstorage. (The answer describes how to store object in localstorage- you could store an object of your form fields in there).
But you have to store the data on posting with js at example.com/form.html and then can get it on example.com/redirected.html. Without js at form.html, this is not possible with this method.
This works if you plan to use html5 and do not store too much data in it, iirc it has a limit of 5-10mb depending on the browser.
I don't think there is a way to do this by using plain html. With some server-side language (like PHP) it can be done with no problem.
I have been in a similar situation before, and the way I managed to give the data to JS is by including the data in a tag while preparing the output using PHP.
Assuming the redirected to php script receives the POST data from the script it's being redirected in. I would include this in the php code:
<?php
echo '<script type="text/javascript">';
echo 'var postData = '.json_encode($_POST).';';
echo '</script>'
?>
This will have the javascript know what the POST values contained.
To access the values from js:
//assuming you need the value for $_POST['foo']
var foo = postData.foo;
// or if json is encoded as just an associative array
var foo = postData['foo'];
If the POST data is not being passed to the redirected to script (haven't checked if this happens automatically), you could write the $_POST data in a $_SESSION variable, in the first php script:
<?php
$_SESSION['postdata']=$_POST;
?>
and then get it back from SESSION from the redirected to script.
<?php
$postdata = $_SESSION['postdata']; //use this to create the inline script in the html
unset($_SESSION['postdata']; //empty this from the SESSION variables
?>

Categories