HTTP Request to Edit Database [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to use a MySQL database to verify that a user has bought a program from my site. I don't need to use a database, but this is the easiest way that I though this could be accomplished (any suggestions on different ways to accomplish a purchase-verification system are greatly appreciated).
My current algorithm:
User pays for the program (through one of various payment gateways provided by WooCommerce)
User is given a unique, randomized hex string by the server (this string is also stored in the database, as a key/value pair; string: 0; the 0 signifies unused)
User enters the string into the program (required), which sends an HTTP request (which includes the string) to the server. This request tells the server to look for the given string in the database. If it's found, change it's value to 1 (used). If the value is already 1 OR the string cannot be found, send an error report back to the user (program will not work).
If everything works correctly, the user can now use the program.
I have to use the HTTP request because only the server can edit the database. My website uses shared hosting, so I cannot directly modify the database on any local user.
I've never worked with databases before, but I know I have to use the INSERT, CREATE TABLE, UPDATE, and SELECT commands. In addition, I've never directly worked with HTTP requests.
How should the HTTP request look like, and how do I handle them on the server? Any other tips on how to work the database would also be appreciated.
Note: I'm probably going to use PHP (server-side) and Python (client-side).

Your html would look like this
<html>
<body>
<form action="validate.php" method="post">
Name: <input type="text" name="name"><br>
unique string: <input type="text" name="uniqueString"><br>
<input type="submit">
</form>
</body>
</html>
And on the server side, your validate.php would look like this.
<?php
$name = $_POST["name"];
$unqString = $_POST["uniqueString"];
//connect to your DB
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT uniqueStringUsedFlag FROM <stringTableName> WHERE uniqueString='.$unqString.'")
or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
if $info['uniqueStringUsedFlag']==1{
return 'Error Message';
}else
{
mysql_query("update <stringTableName> set uniqueStringUsedFlag =1 where uniqueString='.$unqString.'");
return 'Success';
}
}
//if the control comes here, it means the record was not found.
return 'Error message'
?>
Replace < stringTableName > with your actual table name.
And do the same with the columns too.
PS: This code is untested. And please do proper validations, etc. Haven't included that here.
Let me know if this works.

Related

How does this POST request works? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
"Send a message as a POST request to a web service. The address must
start with “http://”, and may optionally include the port number
(default is 80) and the path to a specific web service. The
notification message fills the body of the content part of the POSTed
message, with no key=value form-style formatting – you just read the
input stream directly."
The above is extracted from the Alien UHF RFID F800 manual. The mentioned request is used to send the RFID tags that are scanned by the reader to a web service. The domain name is myrfidtest.com and the path is /insertdb.php. Now the insertdb.php is set up to accept two parameters, for example, id and RFID tag number. So the complete URL is http://myrfidtest.com/insertdb.php?id=21&rfid=2eda1. This data then gets successfully inserted into my database.
Hence I understand how to insert data into the cloud-hosted database using the above URL. However, I do not understand the extract, and what is meant by "you just read the input stream directly"?
In addition, how do I change the insert.php script to accept the tags from the reader?
My insert.php scritp:
<?php
class data_new
{
public $conn='';
function __construct($id,$rfid)
{
$this->storeInDB($id,$rfid);
}
function storeInDB($id,$rfid)
{
$conn = new mysqli('localhost','user','password','db');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into cloud set id='".$id."', rfid='".$rfid."'";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
if($_GET['id'] != '' and $_GET['rfid'] != '')
{
$data_new = new data_new($_GET['id'],$_GET['rfid']);
}
?>
Normally when you post form data in a HTTP request, you (or your browser) puts the posted data into the body of the HTTP request, and formats it rather like a querystring e.g. field1=value1&field2=value2, so that the server receiving the request can tell the fields apart and know which value belongs to which field. I think the article is saying that in this particular request, the entire body of the request is simply a single field containing the notification data, without any name=value style formatting - because there's only one parameter in the body.
In PHP, posted data normally appears in the $_POST array, with one entry in the array per parameter in the data (so you'd end up with $_POST["field1"], $_POST["field2"], etc. But you can also read the raw input data using:
$postdata = file_get_contents("php://input");
instead. This would be useful in the case mentioned above where the data is just one big stream of text inside the request body, rather than being formatted.
P.S. I can't answer the second part of your question " how do I change the insert.php" because I don't know what script you're referring to, what it does or looks like, or what tags you're talking about. I suggest asking a second, separate question about that as it sounds like a different issue, and giving a clear example of what you mean, within the question text.

A web application to allow the user to type SQL queries

I am just wondering, if possible, the best way to go about allowing users to actually input an SQL query from within a web application.
I have so far got a very simple web application that allows users to view the database tables and manipulate them etc etc..
I wanted to give them an option to actually type queries from within the web app too (SELECT * FROM).. and then display the results in a table. (Exactly the same as a search bar, but I don't think that would cut it, would it?).
I am only using PHP at the moment, is what I'm looking to do possible with just HTML/PHP or will I need the help of other languages?
This may be too complex for me, but if someone could give me a starting point that would be great, thank you.
UPDATE:
From my understanding to answer my question, i need something like:
<form action= Search.php method="POST">
<input type="text" name="Search">
<input type="submit" name"">
Search.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$SEARCH = $_POST['Search'];
if (!isset($_POST)) {
$sql = "'%".$_POST['$SEARCH']."%'";
$results = mysqli_query($con, $sql);
echo "<table border ='2'>";
if (mysqli_num_rows($results) !=0) {
while ($row=mysqli_fetch_array($results)) {
echo "<tr><td></td></tr>";
}
echo "</table>";
}else {
echo "Failed! Try another search query.";
}
}
}
?>
At the moment in returns one error:
Undefined index: Search
It's talking about the $SEARCH = $_POST['Search'];
But I thought I am defining that Search, as that's the Search in the form?
Sounds like you're building your own minimalistic version of phpMyAdmin. That's perfectly doable with just PHP and HTML.
A very basic implementation would be a standard HTML form with a textarea, which submits to a PHP script that executes the query and renders a table of the results. You can get the required table column headers from the first result row's array keys if you fetch the results as an associative array.
You may (or perhaps I should say "will") run into situations where users provide a query that returns millions of results. Outputting all of them could cause browsers to hang for long periods of time (or even crash), so you might want to implement some sort of pagination and append a LIMIT clause to the query.
Since the user is providing the SQL query themselves, they need to know what they did wrong so they can correct it themselves as well so you'll want to output the literal error message from MySQL if the query fails.
Allowing users to provide raw SQL queries opens the door to a lot of potential abuse scenarios. If it were my application, I would not want users to use this feature for anything other than SELECT queries, so I would probably have the user-provided queries executed by a MySQL-user that only has SELECT privileges on the application database and not a single other privilege -- that way any user that tries to DROP a table will not be able to.
Undefined index: Search
This error will show only when the PHP is executed for the first time as it's simply expecting "Search" in $_POST.
$_SERVER['REQUEST_METHOD'] checks if the request method is POST it does not check if $_POST have any post data in it.
(Source :$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST')
But the page is being loading for the first time so it wouldn't have anything in POST.
You can simply avoid it by check if the page is loading for first time, using the "isset()" method.
If its loading for the first time just ignore the further execution of php code and simply show the form to enter the query.
<?php
if(isset($_POST['Search']))
{
`// Query execution code`.
}
?>
<form action= Search.php method="POST">
<input type="text" name="Search">
<input type="submit" name"">
So if the search index is not set in the $_POST it wont execute the php code and will not generate any error.

php stop form from posting

Basically i have a form where a studentID is inputted, i then want to check id the inputted studentID is in the database, if it is post the form to the next page. If not then display an error on the page where you input studentID
Don't really know where to start
Cheers
is this what you want?
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
<?
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
// echo $_SESSION['module'];
if ($result == NULL) { // nothing found
echo "the student id you entered is not in the database";
}
else {
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/"); // send the browser where you want
exit();
}
?>
EDIT:
I went over the other answers. I assume you check for mysql injection properly. I recommend implementing AJAX AFTER everything works and is secure. The idea behind my solution was to solve the problem as simple as possible. If you want to make something fancy out of it you could:
generate the whole form via php and tell the user in the input field, that the id wasn't found
tell your Javascript to present the information in some fancy way
Use AJAX. Everybody loves forms with AJAX.
You could, as suggested, assume that the user entered a valid id. You would check on the "whereever" page wether the id is actually valid. If it weren't, you would simply send the user back to the form and tell the php to output an error message (maybe via get). This possibility is not usual, I am not sure if it has any advantages.
the mysql_num_rows hint is nice, too, if you don't want any data from the user. I thought you wanted to do something with the data because of the SELECT *.
Make a seperate controller that does the checking of the username.
Use ajax to check if user input is valid or not.
So you'll have something like this:
<input id="stud" onchange="checkStudentId(this)" />
<script>
function checkStudentId(inputElement) {
var id = inputElement.value();
$.ajax({
url: "test.html",
context: {id:id}
}).done(function() {
// Check the return result
});
}
</script>
Here is a reference to jquery ajax
http://api.jquery.com/jQuery.ajax/
You actually have to connect to the server in some fashion to figure out of the student exists. What you'd normally do in this situation is submit the form to the server and do validation server-side. If the student exists, you return the "next" page. If the student doesn't exist, then you return (or redirect to using a Location header) the same form again with an error message.
Another popular method would be to use an AJAX request to check asynchronously (which I see many other people are recommending). I'd only recommend this way if you're actually doing validation right as they've finished entering the student id and are showing an error message in real-time, effectively. In this way, AJAX is a nice-to-have to provide quick user feedback, but not a real solution. Keep in mind that regardless of this, you need to check for and handle this when the form is submitted anyway, or at the least, consider what will happen when the form is submitted with an invalid id.
People can bypass this check (EVERY request from the client side is considered hostile, you can't implicitly trust anything)
Another user may have deleted the student ID between the time the check was done and the form was submitted
There could be an error in your code that causes validation to falsely pass or not to recognize a negative response
Doing AJAX onsubmit makes no sense, because effectively you're doubling the amount of work by making the server handle two separate requests in a row. It's simply the wrong answer to the problem.
The biggest trouble with this implementation is the PHP code can quickly get quite hairy and hard to follow as you have everything mixed together.
This is where you probably start to tip over using PHP like a templating language (mixed php code and html markup) and start getting into using a framework where your views (the HTML) are decoupled from your PHP code (if you're using the very-populate MVC pattern, this code is called your controller -- precisely because it controls how the server responds). This is how any professional developer will work. Kohana, CakePHP, and Zend are all examples of fairly popular MVC frameworks, all of which are used professionally.
You can do this in two different ways
AJAX - make ajax call to your server and check the ID if its exist display the error else go to the next page
PHP - put a hidden input in your form and make the action of the form to the same page and check everything their and keep the values of the input fields is the $_POST['field_name'];
And you can make the action into another page and return back variable or make a session to hold the error message
Try this:
<?
if(isset($_POST['stud'])){
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$host="hostname";//your db host
$user="user";//your db user
$pass="pass";//your db pass
$conn=mysql_connect($host,$user,$pass);
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql,$conn);
if(mysql_num_rows($result)>0){//the id was found in the DB, do whatever here...
echo $_SESSION['module'];
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/");//redirect to wherever
$error=false;
}
else{//id was not found
$error=true;}
}//end of isset
?>
<? if($error===true){?> <div> The id was not found.... </div> <?}?>
<form id = "form" action = "<? echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; ?>" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
So what this does is: When the user hits submit, conects to the DB, and checks if the ID exists...if it does, then it redirects it to wherever.com (see comments) and if it don't an error messege will show up. Be sure to change the db variable values to your own ($host, $user, $pass).

Generate PHP script for HTML form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
To preface, I am sorry for asking what is likely an extremely simple question. I am an intern for a non-profit helping with some web tasks and have been asked to build a submission form. I want the data inputted in the fields to send to my email address. The form code is fine, however it is the PHP script that seems to not be working. Can anyone suggest a simple PHP code (or another method) to parse this info a designated email address? Currently using method="post"
Here is the form code: http://pastebin.com/7Gxb92n5
Thank you!
Alex
Your form uses the method POST, so in send_form_application.php you will have to use the mail() function.
Name [Last, First MI] <input type="text" name="name" /><br />
Primary Organization <input type="text" name="primary_organization" /><br />
This above is your HTML that will POST variables contained in a $_POST array.
So $_POST['name'] will contain you name and
$_POST['primary_organization'] will contain the primary organization (what the user made as an input in the form)
The "most important part" of this HTML input is the name because it is what you will use to "fill" the mail function with it's attributes.
Your PHP will look something like:
mail($to, $subject, $message, $headers);
?>
The $content could be all the elements of the post like this (should actually be above the previous code)
$content = $_POST['name'] . "\n";
$content .= $_POST['primary_organization'] . "\n";
?>
And so on...
Please tell me if you cant understand something!
IMPORTANT: while this might work, this is not really secure yet, you should ALWASY validate the user input!
On the .php page handling the post ("send_form_application.php" in your case),handle all incoming form fields in the following way:
1) Create variables to store each of your incoming form fields...
...
$name = $_POST["name"]
$primary_org = $_POST["primary_organization"]
$primary_pos = $_POST["primary_position"]
..
ETC...
2) Create an email body string variable to hold all these values however you want to...
3) Then use php's mail functionality to email the info to yourself...
More info here-> http://php.net/manual/en/function.mail.php
Hope that helps!
To verify your server/mail configuration is okay, try the simplest possible code:
<?php
mail("info#nonprofit.org", "form info", print_r($_POST, TRUE));
And you could assemble the body much easier like this (note that clean_string makes no sense for the email body):
$email_message = <<<END
Name [Last, First MI] : $_POST["name..."]
Primary Organization : $_POST["org..."]
Street Address : $_POST["street..."]
City : $_POST["city..."]
State : $_POST["state..."]
END;
Well here is a script that should give you the basic Idea on how to send an email via PHP
http://email.about.com/od/emailprogrammingtips/qt/How_to_Send_Email_from_a_PHP_Script.htm
But other than that your html looks fine...

Creating basic PHP script to add lines to a webpage

I'm predominately a Java guy, which is why I need some assistance on what I assume is rather simple to do in PHP (and rather simple with Java too, although perhaps a bit... verbose).
Simply put, I want to construct a webpage which has a list of string items that users have added. At the bottom of the page would be a place in which a user could type "Hello World" in a box for instance and hit a submit button, adding it to the list of items. Adding to the top or the bottom of the list is irrelevant - I can probably tweak that later.
I'm the kind of guy who doesn't just like answers, but at the same time I have no idea where to even start searching. I've done no PHP development before. What sorts of constructs or functions should I be looking at? I own the physical box it'll be running on (it's literally right next to me now) so permissions aren't a restriction, and neither is getting anything else that might help the situation (although I can't see how it would be needed for such a simple script). What sorts of input validation should I be really wary of? This service will be restricted to people who have be given access to a particular section of an apache-based website, so they have to log in to even see this planned page, but I'd like to cover all possibilities.
Additionally, I would perhaps like output to look like
"Hello World" added by user User1
"This is an additional line" added by User2
"Goodbye World" added by user User1
in the future. What should I be looking at to do this?
Update to answer questions:
When it comes to storage of the actual content, I'd be leaning towards a simple file holding each entry line by line, as Col. Shrapnel suggested. A think a database would be overkill, although I do have the wherewithal to implement it. If a user submits "Hello World!" then adding a line to a file that says
"Hello World!" posted by User1
is sufficient.
With regards to authentication, this is already set up in apache's httpd.conf configuration file. Currently this allows access to a certain group of users through an AuthGroupFile entry. This is where the script will be hosted. To access this script, users will have already authenticated themselves with their credentials. The authentication currently works for that section of the site. Really, this is a secondary concern of mine. It is enough that lines are simply added with no record of who said what. This is just sugar on the PHP cake if it can be done easily with what I already have implemented.
Well, yes, in PHP it's quite short.
Assuming Apache based authorization is used
<?
$file = "messages.txt";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$_POST['mess'] = str_replace(array("\r","\n"),"",$_POST['mess'];
file_put_contents($file, $_POST['mess']." ".$_SERVER["REMOTE_USER"]);
header("Location:".$_SERVER["PHP_SELF"]);
exit;
}
echo nl2br(htmlspecialchars(file_get_contents($file)));
?>
<form method="POST">
<input type="text" name="mess">
<input type="submit">
</form>
You're going to have a few things to do:
Pick a data store. MySQL is a popular choice when working with PHP. It doesn't sound like this'll be high-volume, so most any persistent store would work.
When accepting input, you'll need to sanitize it for insertion into the DB (again, if using MySQL, check the docs), and then you'll execute an INSERT statement to put it into the database.
When displaying the page, you'll connect to the DB (check the docs), query data from the data store, loop over it, and echo each line after sanitizing it of any potentially malicious data.
A short example might be something like:
<?
// Assuming a database named "my_database" with a table called "chat_lines", which has "username", "line", and "timestamp" fields.
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("my_database", $db);
// If data was posted to the script, scrub it and store it in the database.
if($_POST["username"] && $_POST["line"]) {
mysql_query(sprintf("INSERT INTO chat_lines (username, line, timestamp) VALUES (\"%s\", \"%s\", NOW())",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["line"])
));
}
// Fetch all lines from the database in reverse chronological order
$result = mysql_query("SELECT * FROM chat_lines ORDER BY timestamp DESC");
while($row = mysql_fetch_assoc($result)) {
echo sprintf("<div>%s said %s</div>", strip_tags($result["username"]), strip_tags($result["line"]));
}
?>
<form method="post">
<div>Username: <input type="text" name="username" /></div>
<div>Line: <input type="text" name="line" /></div>
<input type="submit" />
</form>
That example makes assumptions about users being allowed to enter whatever username they want (that is, it doesn't assume to implement the authentication system), the data store and the existence of the table and all that, but should get you started. The PHP documentation is pretty extensive, and can be very useful. In particular, read Getting Started and the Language Reference.

Categories