PHP - Insert to database without refresh page ( OOP ) - javascript

I am trying to find a way how can I insert something to my MySQL database without refreshing the page and also don't make a security hole.
After some hours of trying and searching I have this:
<form name="form1" action="">
Enter Name <input type="text" name="t1" id="t1"></td> <br>
Enter City <input type="text" name="t2" id="t2"></td> <br>
<input type="button" name="button1" value="Insert to DB" onClick="aa()">
</form>
<div id="d1"></div>
<script type="text/javascript">
function aa()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "insert.php?name=" + document.getElementById("t1").value + "&city=" + document.getElementById("t2").value, false);
xmlhttp.send(null);
document.getElementById("d1").innerHTML=xmlhttp.responseText;;
}
</script>
Which is simple form, which call JS , and that JS redirect info to .php file where is SQL command for inserting things to database.
But I'm not sure if this is "secure" and also I would prefer to call some method which will insert (using MVC) or something like that.
Is here anybody who can give me some knowhow?

Your question is legitimate. A lot of websites are using this technique this day where a page communicates with a server without reloading the whole page, without sending full headers and reloading all resources. Is a very useful technique, pioneered by Microsoft some years ago and then adopted and supported by all browsers, with the advantage of being more user-friendly and faster. You can use your own code, like you did to create an AJAX request or use a library (like jQuery, DOJO, mootools, YUI, etc) that solve for you a lot of differences between browsers. In my opinion you should start by using a library as they have examples and will help you a lot at the beginning.
The infrastructure of an AJAX request is still the HTTP verbs: GET and POST mainly, used to get a new chunk of information or to save some input. This JavaScript part is like any other Javascript executed on clients side, in the client browser, which makes it insecure by default. The security rule is:
always check user input and distrust humans by default :) - filter it, sanitize it, do a thousand checks before trusting it to be saved in your database or before using it anywhere.
This you have to do it on PHP side. Again, you can, filter yourself or you can use libraries or MVC that can help you with that. Here is a little more tricky in my opinion to recommend something. Sometimes those come with a lot of extra information and may introduce more headaches.
Learn how the things work by experimenting with a JS library and a simple PHP script and later you can move from there.

What you want is called a 'ajax' request. If you google for that term you will find some interesting examples.
You might wanne consider using a library, for example jquery, which basicly abstracted it to a nice function

I guess that what you are asking for is security. As said before, if you don't want to reload the page your option is AJAX, but if your main issue is security, then you have to implement CSRF (Cross-Site Request Forgery). To avoid csrf, you should check this link.

Related

Simple php script fetching visitor details like screen resolution, country of origin etc

First a little bit about me because it might help:
I am NOT a professional coder, I write HTML and CSS by hand with notepad++ because i like the lightweight and effective code + I have total control and clue of what is going on in my files/website.
I don't like WP. Its too much hassle and yes i know it's "easier" but since I know nothing about php, except that it's a server side language, it's not easier for me to get the look of the website that I want with it. (recently I found out I can INCLUDE a part(s).html in actual.html and compose actual.html - not up for that right now as it makes a new connection for each part.html (when i get to more complex web-developing, as my sites are static, etc...)) Tried multiple times, ended up deleting everything and writing my own code from scratch. I don't like to learn the (php) code from WP editing (extremely time-consuming and messy), I prefer learning it by using the code when i need it. That's how i remember and learn. That's how I learned C#.
I like one-file type of web pages as they are pretty much static. Any pics that i might use i DON'T create any links, I convert them in base64 and paste the code where i need it. So as minimalistic as possible with fewer requests as possible with least kb as possible - but resemble WP by look and behavior (responsivness).
I reserve one request for style.css and one for favicon.ico; #1 it's neater, #2 can't be base64-ed nor CSS loaded.
Anyway, a php contact form that I used in one of my sites was working perfectly, with just contact.php file on the server and a little bit of js in html. Therefore i ASSUME that fetching user data such as IP, time of access, screen resolution and OS would be easy similarly as the contact form was.
What I would like to know is next:
fetch device.useragent + device.resolution + time + IP;
write fetched to log.txt
Then i ftp the log.txt to my pc and investigate.
Thank you for reading and considering to help :)
The user agent, time, and IP address can be stored in variables as follows:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$time = date('Y-m-d H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
For resolution, you'd have to determine it with JavaScript and send it to the server with an AJAX request or as part of the request body. All of this can then be written to a log.txt file using file_put_contents('path/to/log.txt', $data);.
Note, that there are usually simpler ways of achieving this if using a framework (e.g. Symfony, Laravel, Zend), or there may even be a plugin for your CMS of choice.
Check this post, PHP's get_browser, and also this post is very helpful. For the resolution, like Sheraz said, you need JS or any JS library that can read the device resolution. If you want to use jQuery, check this post. To fetch user time of access, you can create a $_SESSION variable and use time. For the ip, check this. And for file handling, fopen, file_get_contents, file_put_contents and fclose will help you.

Is it possible to write ColdFusion statement within Javascript? [duplicate]

Can I use ColdFusion tags in JavaScript? For example:
<script language="javascript" type="text/javascript">
function validateUser() {
var userName = document.getElementById("username");
<CFQUERY DATASOURCE="mydatasourcename" NAME="getUser">
select USER_ID,COUNT(*) from user u
where u.firstname=userName;
</CFQUERY>
<cfif getUser.recordCount EQ 0>
<!--- Show eroor message --->
<cfelse>
<!--- Assign userId to hidden field --->
document.getElementById("userid").value=#USER_ID#
</cfif>
}
</script>
<input type='textbox' name='username' id='username' onblur=validateUser()/>
<input type='hidden' name='userid' id='userid'/>
When the end user enters their username, I would like to check in a database if this username exists or not. If it exists, I have to keep the userid in the hiddenfield or else throw an error.
Am I doing this correctly? If it is wrong, could you suggest the correct way?
Long version: http://blog.adamcameron.me/2012/10/the-coldfusion-requestresponse-process.html
Short version: no, you're not doing it right.
Mid-sized StackOverflow-friendly version: CFML code runs on the server side of a request; JavaScript runs on the client browser. And to be clear: the ColdFusion server never communicates with the browser directly at all: there's a web server in between. The client browser requests a file, the web server is configured to pass .cfm requests to the ColdFusion server, and it runs its code, returning the resulting string (eg: an HTML web page) to the web server which then returns that to the browser. That HTML might include JavaScript (inline or as external requests) which the browser will then execute.
Hopefully from that you can see that there's no direct interaction between server-side code and client-side code.
You have two facilities at your disposal to get the two communicating asynchronously though. Firstly: CFML code writes out text, but that text can be JS which the browser then runs when it finally receives it. Something like:
<cfset msg ="G'day world">
<script>alert("<cfoutput>#msg#</cfoutput>");</script>
Once the CFML server has processed that, what gets sent back to the browser is:
<script>alert("G'day world");</script>
In this way server-side code data can be used in client-side process if the server-side code "writes out" the data as part of its response. The example above is very trivial and not a "good practice" way of going about this, but it demonstrates the technique.
If you need to use JS code on the client to communicate back with the server, your only (real) recourse is to make an AJAX request back to the server to pass it client-side information for further server-side processing and for the server to respond with something. It is outwith the scope of your question to explain how best to do this, but there is a tonne of information out there to do this.
CFML provides some "wizards" to write HTML and JS out for you to facilitate this, but on the whole this is a bad approach to achieving this end, so I will not recommend it. However I will point you to a project which offers HTML/JS/CSS solutions to the inbuilt CFML wizardry: https://github.com/cfjedimaster/ColdFusion-UI-the-Right-Way
Back to the short answer: no, you cannot do what you are setting out to do for very good reasons, but if you revise your approach, you can achieve the ends that you want.
What you need to look at is passing the form fields back to the server via AJAX (jQuery makes this very easy), and run your <cfquery> code in a separate request.
If you read that blog article I mention from the outset (discloure: I wrote it, but I wrote it specifically for situations like this), then you'll understand why.
If you get stuck when working on part of your solution: raise another question more focused on whatever part you are stuck on.

Smarty Variable in Javascript

I need to print this variable:
{$array}
And i have this code:
<script type="text/javascript">
function write() {
writing = document.getElementById('box_user');
if(writing.innerHTML == ""){
writing.innerHTML = "{$array}";
}else{
writing.innerHTML = "";
}
}
</script>
When I click here, i dont get the result of the variable:
<td><button name="ver" onclick="write()"></td>
And the result must be here:
<div class="col-lg-12" id="box_user">
</div>
Content of variable:
while($array = mysqli_fetch_assoc($resultado)){
if($tabla1 == ""){
$tabla1 = "<table>
<thead>
<tr>
<td><strong>ID Formador</strong></td>
<td><strong>Nombre</strong></td>
<td><strong>Apellidos</strong></td>
<td><strong>Email</strong></td>
<td><strong>Teléfono</strong></td>
<td><strong>DNI</strong></td>
</tr>
<tr>
<td><strong>".$array['ofca_idFormador']."</strong></td>
<td><strong>".$array['daco_nombre']."</strong></td>
<td><strong>".$array['daco_apellido1']." ".$array['daco_appelido2']."</strong></td>
<td><strong>".$array['usrs_mail']."</strong></td>
<td><strong>".$array['daco_telefono']."</strong></td>
<td><strong>".$array['daco_dni']."</strong></td>
</tr>";
}else{
$tabla1 .= "<tr>
<td><strong>".$array['ofca_idFormador']."</strong></td>
<td><strong>".$array['daco_nombre']."</strong></td>
<td><strong>".$array['daco_apellido1']." ".$array['daco_appelido2']."</strong></td>
<td><strong>".$array['usrs_mail']."</strong></td>
<td><strong>".$array['daco_telefono']."</strong></td>
<td><strong>".$array['daco_dni']."</strong></td>
</tr>";
}
}
$tabla1 .= "</thead></table>";
I'm using a .tpl and all of controllers a model work great the problem is here.
I´m starting on smarty, this is my first project.
I'm not hugely familiar with Smarty, but I've done some PHP in my day, and I'll take a shot at an answer here. Forgive me if this answer is overly simplistic and sounds unnecessarily patronizing; I'm going to answer in a way that even a beginner could understand, since I don't know your skill level or familiarity with these concepts.
The main problem you're having has to do with the separation between the server and the client. PHP is a server-side language; JavaScript and HTML are client-side. The server is what hosts your website for the client, usually your web browser, to request and read.
The interaction usually goes something like this: your browser asks the server for a certain webpage, the server does some stuff to build that webpage up from the templates, and the server hands the completed webpage to your browser. From that point on, the server no longer has any access to your webpage, and server-side code won't do anything, because your browser doesn't know what it means, so if any server-side code is left as part of the webpage, it's just going to be rendered directly as text. Your browser does understand client-side code, however, and that will still work just fine.
Of course, sometimes you need information from the server after the page has loaded. The way your client-side code running in the browser gets new data from the server is generally through AJAX requests; essentially, the browser talks to the server again and asks for some data, the server again runs some server-side code to build up the data you're asking for, and it hands it back to the browser. This usually won't be in the form of another webpage, but will instead be in a data format like JSON or XML, which your client-side code can then process and use to add content to the page. But notice that the server-side code never touches the page; all it does is hand over some data that the client-side code can use to update the page.
If you're familiar with C and similar languages, think of PHP-style templates as preprocessor code. The preprocessor code can, in effect, add and remove sections of the C code at compile time, but once the build is complete, that preprocessor code doesn't exist anymore, and the preprocessor can't do anything at runtime; at that point it's all C. Similarly, PHP can build up client-side code, generate bits of HTML or JavaScript, etc., but once that page is handed off to the browser, PHP doesn't exist anymore as far as that page is concerned.
Based on the code I'm reading above, I think you have two options, depending on what you're trying to do. I can't quite tell whether you mean for that table code to be generated dynamically at runtime when the user requests it, based on some user input, or whether the table exists completely and is just waiting to be displayed.
If the table code already exists, I recommend moving it out of a PHP variable and into the page. If you don't want it to show immediately, you should use CSS to hide it initially and use that button click function to show it, something like this (assuming the Bootstrap .invisible class based on some other Bootstrap classes you used):
<div class="col-lg-12" id="box_user">
<div id="table-wrapper" class="invisible">{$tabla1}</div>
</div>
<script>
function write(){
document.getElementById('table-wrapper').classList.remove('invisible');
}
</script>
If you need to dynamically generate the table based on some user-generated info and MySQL queries, which it looks like you're using, then you have a little extra work to do. You need to look into how to set up a REST interface for your server, whether through PHP or something else, and you need to look into how to make AJAX calls. You should return data from the server as a JSON object, then convert that PHP code you're using to generate the table into a JavaScript function and pass in the JSON you get back.
Hope that helps! Please feel free to ask for any clarification you might need.

How "secure" is the ASP .NET Controller

I am still very new to the concepts and design of ASP .NET's MVC and AJAX and I was wondering how secure the Controller is to unwanted user's when webdeployed.
I ask because for fun I made a little admin panel that requires a user name and password. Once input is entered the information is AJAX submitted to a ActionResult method in the Controller that just compares the strings to see if they match, then returns the response back to the AJAX.
My question is, how easy is it for someone to get into my Controller and see the hard-coded password?
No professional-type person will ever try to break into this, as it is a free site for a university club, but I want to make sure that the average Computer Science student couldn't just "break in" if they happen to "rage" or get mad about something (you never know! haha).
Question: Is having a password validation within the Controller "decently" secure on a ASP .NET MVC web-deployed application? Why or why not?
Here is the actual code in case the use of it matters for the answer (domain is omitted for privacy)
Note: I understand this use of Javascript might be bad, but I am looking for an answer relative to AJAX and Controller security of the password check.
View (Admin/)
//runs preloadFunc immediately
window.onpaint = preloadFunc();
function preloadFunc() {
var prompting = prompt("Please enter the password", "****");
if (prompting != null) {
$.ajax({
url: "/Admin/magicCheck",
type: "POST",
data: "magic=" + prompting,
success: function (resp) {
if (resp.Success) {
//continue loading page
}
else {
//wrong password, re-ask
preloadFunc();
}
},
error: function () {
//re-ask
preloadFunc();
}
});
}
else {
// Hitting cancel
window.stop();
window.location.replace("google.com");
}
}
Controller (ActionResult Snippet)
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "pass")
{
success = true;
}
else
{
success = false;
}
return Json(new { Success = success });
}
Again I am new to MVC and AJAX, let alone anything dealing with security so I am just wondering how secure the Controller is, specifically on webdeploy for this simple password setup.
During normal operation, there is no concern as your code is compiled, the DLL prevented from being served, and there is no way for the browser to request the controller to divulge its own code.
However, it is not impossible (but quite rare) that unforeseen bugs, vulnerabilities, or misconfigurations of the server could lead to the server divulging compiled code, web.config, etc., whereby someone could disassemble the code (IL is easily decompiled) and reveal your secret.
More worrisome would be someone having physical access to the server just grabbing the binaries directly and disassembling to find your secret.
Another thing to consider is who, during normal situations, might see that secret and whether or not they should know it. A developer, tester, or reviewer may be allowed to write or inspect code, but you may not want them to know the secret.
One way to handle this is not store secrets in plain text. Instead, create a hash of the valid value, then update your application to hash the user's input in the same manner, and compare the results. That way if the user ever gets your source code, they can't read the original plain text value or even copy/paste it into your UI. You can roll your own code to do the hashing, use the FormsAuthentication API, or something else.
Finally, do not rely on client-side enforcement of security. You can check security on the client side to have the UI react appropriately, but all server-side requests should be doing checks to make sure the user's security claims are valid.
The question really goes out of scope from here, regarding how to manage identities, passwords, and make security assertions. Spend a little time looking through the myriad articles on the subject. Also, the Visual Studio ASP.NET project templates include a lot of the security infrastructure already stubbed out for you to give you a head start.
Never leaving things to chance is an important policy. Learning about ASP.NET and MVC's various facilities for authentication and authorization is a worthwhile effort. Plus, there are numerous APIs you can plug in to do a lot of the heavy lifting for you.
As has already been pointed out if you can get a hold of the binaries for an app (or for that matter ANY .NET application not just MVC) then it's definately game over.
Just sat in front of me here and now I have 3 applications that make it child's play to see what's inside.
Telerick - Just Decompile
IL-Spy
Are both freely downloadable in seconds, and the former of the two will take an entire compiled assembly, and actually not just reverse engineer the code, but will create me a solution file and other project assets too, allowing me to load it immediately back into Visual Studio.
Visual Studio meanwhile, will allow me to reference the binaries in another project, then let me browse into them to find out their calling structure using nothing more than the simple object browser.
You can obfuscate your assemblies, and there are plenty of apps to do this, but they still stop short of stopping you from de-compiling the code, and instead just make the reverse engineered code hard to read.
on the flip side
Even if you don't employ anything mentioned above, you can still use command line tools such as "Strings" or editors such as "Ultra Edit 32" and "Notepad++" that can display hex bytes and readable ASCII, to visually pick out interesting text strings (This approach also works well on natively compiled code too)
If your just worried about casual drive by / accidental intrusions, then the first thing you'll want to do is to make sure you DON'T keep your source code in the server folder.
It's amazing just how many production MVC sites Iv'e come accross where the developer has the active project files and development configuration actually on the server that's serving live to the internet.
Thankfully, in most cases, IIS7 is set with sensible defaults, which means that things like '*.CS' files, or 'web.config' files are refused when an attempt is made to download them.
It's by no means however an exact science, just try the following link to see what I mean!!
filetype:config inurl:web.config inurl:ftp
(Don't worry it's safe, it's just a regular Google Search link)
So, to avoid this kind of scenario of leaking documents, a few rules to follow:
Use the web publishing wizard, that will ensure that ONLY the files needed to run end up on the server
Don't point your live web based FTP root at your project root, in fact if you can don't use FTP at all
DO double check everything, and if possible get a couple of trusted friends to try and download things they shouldn't, even with a head start they should struggle
Moving on from the server config, you have a huge mountain of choices for security.
One thing I definitely don't advocate doing though, is rolling your own.
For years now .NET has had a number of very good security based systems baked into it's core, with the mainstay being "ASP.NET Membership" and the current new comer being "ASP.NET simple membership"
Each product has it's own strengths and weaknesses, but every one of them has something that the method your using doesn't and that's global protection
As your existing code stands, it's a simple password on that controller only.
However, what if I don't give it a password.
What happens if I instead, decide to try a few random url's and happen to get lucky.
eg: http://example.com/admin/banned/
and, oh look I have the banned users page up.
This is EXACTLY the type of low hanging entry point that unskilled script kiddies and web-vandals look for. They wander around from site to site, trying random and pseudo random URL's like this, and often times they do get lucky, and find an unprotected page that allows them to get just far enough in, to run an automated script to do the rest.
The scary part is, small college club sites like yours are exactly the type of thing they look for too, a lot of them do this kind of thing for the bragging rights, which they then parade in front of friends with even less skill than themselves, who then look upon them as "Hacking Heroes" because they broke into a "College Site"
If however, you employ something like ASP.NET membership, then not only are you using security that's been tried and tested, but your also placing this protection on every page in your site without having to add boiler plate code to each and every controller you write.
Instead you use simple data annotations to say "This controller is Unprotected" and "This one lets in users without admin status" letting ASP.NET apply site wide security that says "NO" to everything you don't otherwise set rules for.
Finally, if you want the last word in ASP.NET security, MVC or otherwise, then go visit Troyhunt.com I guarantee, if you weren't scared before hand, you will be afterwards.
It looks like you are sending a password via AJAX POST. To your question, my answer would be that you should consider using SSL or encrypt the password prior to sending it via POST. See this answer for an example and explanation SSL Alternative - encrypt password with JavaScript submit to PHP to decrypt
As HackedByChinese said, the actual code being stored in your compiled files (DLL) wouldn't be too big of a deal. If you want to be extra paranoid, you can also store the password in your web.config and encrypt it there. Here's an example and explanation of that How to encrypt username and password in Web.config in C# 2.0
This code is not secure at all. Your JavaScript code can be replaced with EVERYTHING user wants. So someone can just get rid of your preloadFunc. Average computer sience student will execute this code directly from console:
if (resp.Success) {
//continue loading page
//this code can be executed by hand, from console
}
And that will be all when it comes to your security.
Authentication and authorization info should go to server with every request. As a simple solution, you could use FormsAuthentication, by calling
FormsAuthentication.SetAuthCookie("admin")
in /Admin/magicCheck, only if password is correct.
Then you should decorate data retrieval methods with [Authorize] attribute to check if cookie is present.
Using SSL to secure communication between browser and server would be wise too, otherwise password travels in clear text.

How do modern web-apps/sites do postbacks? javascript/ajax, <form> or X?

I am curious to know how "modern" web-apps/sites do postbacks, meaning when they are sending back user-input to the site be processed.
Do modern sites still use the old fashion <form>-tags or do they use some sort of javascript/ajax implementation? or is there even a third option?
I tend to use both, where a full page refresh from a normal <form> submit works, but if JavaScript is enabled you hook up to the submit event and override it. This gives you fancy AJAX if possible, and graceful degradation if it's not.
Here's a quick example (jQuery for brevity):
<form type="POST" action="myPage.htm">
<input type="text" name="UserName" />
<button type="submit">Submit me!</button>
</form>
If the user has no JavaScript, no problem the form works. If they do (and most will) I can do this:
$(function() {
$("form").submit(function() {
$.ajax({
url: this.action,
type: this.type,
data: $(this).serialize(),
success: function(data) {
//do something with the result
}
});
});
});
This allows the graceful degradation, which can be very important (depends on your attitude/customer base I suppose). I try and not screw over users without JavaScript, or if a JavaScript error happens on my part, and you can see from above this can be done easily/generically enough to not be painful either.
If you're curious about content, on the server you can check for the X-Requested-With header from most libraries and if it's present, return just the <form> or some success message (since it was an AJAX request), if it's not present then assume a full page load, and send the whole thing.
It will vary depending on what exactly is being done, but most web-apps will do a combination of AJAX for short content (esp where live/interactive updates are helpful without requiring a page refresh) and "old-fashioned" forms for longer content wherein a full page load is not an issue.
Note that nothing about AJAX prevents its use for long content as well as short.
Also note that from the stand-point of the code driving the server app, there is not necessarily much difference at all between a request coming from a standard form or a request coming from an AJAX submission. You could easily structure a single script to properly respond to both types of request (though in some cases you can save bandwidth by sending a shorter "data-only" response to the AJAX version, since the client-side code can be responsible for parsing the data into meaningful content).
Basically, there are three models.
The traditional form model uses form postbacks for every action that requires going to the server, and may use javascript to perform client-side tasks that make the user's life easier without compromising security (e.g. pre-postback validation). The advantage of this is that such a web application, if written correctly, will work without needing any javascript at all, and it is easier to make it work on a wide range of devices (e.g. audio browsers).
The server-centric ajax model uses ajax calls to provide partial page refreshes; the page is built like in the traditional model, but instead of triggering a full page post-back, client-side script uses ajax calls to send clicks and other events, and retrieves information to replace a part of the document (usually in JSON or XHTML form). Because you don't post the entire page every time, the response is usually quicker. This model is useful if you want to use ajax where possible, but still want to be able to fall back to traditional postbacks if javascript isn't available.
Client-centric ajax takes a different path; the core idea is that you write your entire application in javascript, using ajax to exchange data, not markup. When you click a button, the application sends a request to the server, and receives data. The data is then used for further processing on the client. This is more flexible and usually faster than the other methods, but it requires good knowledge of javascript. Applications written in this style generally don't work at all when javascript is disabled on the client.
Most decent web applications try to put progressive enhancement. Meaning that a simple old fashioned button click results in a form post which can be handled by the server. This is for the scenario of people who use an old browser or turned off javascript for some reason.
The enhancement can be done by using hijaxing. Meaning that that same page can perform, with the help of some ajax, the form post to the server but not the entire page. This enables users with javascript enabled to have a better user experience.
old fashion -tags or do they use some sort of javascript/ajax implementation?
In order to have javascript to work on something you still need that somethingl old fashioned tags. Web applications can be structured down to 3 major parts:
Content: HTML
Layout: CSS
Behavior: javascript/ajax

Categories

Resources