I'm working on making a small application just to get the hang of REST and I'm having some trouble with the DELETE method. I've never used it before so I'm not sure how it behaves.
Anyway, I followed this tutorial to get a hang of the basics. I modified it so instead of using a pre-made array, the user can submit data and view it from a MySQL databse.
I have 3 files:
server.php - the "API" which determines the method used and acts accordingly
input.php - displays a form for the user to input data
viewinput.php - displays the inputs that have been entered.
I'm trying to now place a "delete" button on viewinput.php so that an entry can be deleted. Here's my code that displays the entered information.
while ($result = mysql_fetch_array($sql)){
?>
<tr><td><? echo $result['id']." "; ?></td><td><? echo $result['text']; ?></td>
<form method = "delete" >
<td><input type="submit" name="delete" value="delete"></input></td></tr>
<input type="hidden" name = "hidden_delete" value="<? echo $result['id']; ?>"></input>
</form>
<?
}
Now, in my server.php file (the API), this is the very first function that is called which determines the method and breaks the URL into components for further processing.
public function serve() {
$uri = $_SERVER['REQUEST_URI'];
echo $method = $_SERVER['REQUEST_METHOD']; //GET and POST are displayed, DELETE isn't
$paths = explode('/', $this->paths($uri));
array_shift($paths); //
$resource = array_shift($paths);
When I press a delete button, the URL goes from
/rest/viewinput
to
/rest/viewinput?delete=delete&hiddendelete=3 //assuming I deleted the 3rd entry
From what I understand, the URL should be /rest/viewinput/3 when a DELETE method is submitted
In my server.php file, when I echo the method, "DELETE" isn't shown like it does for POST and GET methods.
I found this resource regarding DELETE, and from what I understand an identifier will be passed through the URL, but there should be some method received just like GET and POST (meaning my code should display DELETE when I echo the method).
Here is the current lowdown on PUT and DELETE.
If you are "plain browsing", most browsers don't actually use either of these verbs. They do however support them for XML Http Requests (i.e. AJAX). So from the client side, you can't really use PUT or DELETE directly on an HTML form element and have it work. You would need to use the work-around suggested by Complex857, i.e. include the intention in the request.
If you are using background AJAX calls, or indeed if you are not using a browser to make the requests, you can use the full suite of HTTP verbs, including PUT and DELETE. One caveat to this is that on IIS you may need to change your settings to allow these verbs as you can set the specific verbs your server accepts.
Related
Hey I'm new to php need help creating anew page per user. I have a user login and registration system already. I also have a profiles.php page but, how can I let the website make an automatic webpage for every new user.
Whenever I try to connect it through $_GET or $_POST I get an Undefined index error.
include ("includes/profiles.dbh.inc.php");
$requested_user = $_POST['mailuid'];
try{
$stmt2 = $conn2->prepare("SELECT * FROM profile WHERE id = ?");
$stmt2->execute(array($requested_user));
$mydata = $stmt2->fetch();
} catch (Exception $e) {
//error with mysql
die();
}
I've seen this question come up a few times. One of the first things you need to consider is how is the user going to interact with this page.
Are they going to access it via links? http://example.com/index.php?user=1
Or are they going to submit a form via post? http://example.com/index.php
This distinction is important because it changes the way you handle their request.
Let's look at each one:
Via a link: http://example.com/index.php?user=1
This will issue a get request to your server so you need to handle it via $_GET.
if (isset($_GET['user'])) {
$userId = $_GET['user'];
// ... query your DB and output result
}
Via a form using post: http://example.com/index.php (body with contain "user=1").
This will issue a post request to your server so you need to handle it via $_POST
if (isset($_POST['user'])) {
$userId = $_POST['user'];
// ... query your DB and output result
}
On a side note, it is important to know that an HTML <form> can submit either a post or get request. You can control this via it's method attribute. If you don't specify the method attribute, then it defaults to get.
<form method="post">
...
</form>
<form method="get">
...
</form>
So, to answer your question. You're likely getting an undefined error because you're trying to access the post array using the key mailuid ($_POST['mailuid']) but that does not exist. It doesn't exist because:
you're receiving a get request and the post is empty OR
you are receiving a post request but it doesn't contain the key mailuid
To debug, go back to the basics - use $_GET
Change your code to use $_GET['mailuid'] and then make sure you access your page with the corresponding query string - ...?mailuid=1.
Finally, turn on error reporting - https://stackoverflow.com/a/5438125/296555. You should always do this and correct all errors and warnings.
I am currently trying to work out a basic referral form. The process is as follows:
The referrer will use a form to send an email to their friends. (Example: http://www.graphicgoldfish.com/refer.html) As you can see, the form requires their Username and their IGN (in-game name). This is very important.
A link is generated using the referrer's information as the parameters. The parameters will be used to reward the referrer once the friend has completed the second form. (Example: http://www.graphicgoldfish.com/referral.html?ref_username=LRRoberts0122&ref_ign=DerpyGoldfish)
When that link is clicked, it opens up a second form where the friend can input their information. My problem is, that when the friend submits the form, the parameters from the original URL do not get passed.
How am I able to keep those parameters after the submission?
My PHP:
<?php
echo $_GET['ref_username'];
echo $_GET['ref_ign'];
if (isset($_GET['ref_username'])) {
$r_username = $_GET['ref_username'];
}
if (isset($_GET['ref_ign'])) {
$r_ign = $_GET['ref_ign'];
}
None of this seems to be doing what I want. My guess is that it doesn't exist, because if I run the PHP and manually add the parameters, it works. I'm just not sure how to go about doing this automagically.
EDIT: The parameters are being passed into an HTML file from the link that was generated. The friend needs to fill out a form. How can I get the values that were passed in the parameters to the HTML file, and concatenate them to the action (where it submits to a PHP file)?
This is not working for me.
<form action="http://www.graphicgoldfish.com/php/referral.php?ref_username=<?php echo $ref_username ?>&ref_ign=<?php echo $ref_ign?>" method="POST">
First off...in your generator.php form. You are using POST not GET
So you should retrive your variables as such.
if (isset($_POST['ref_username'])) {
$r_username = $_POST['ref_username'];
}
if (isset($_POST['ref_ign'])) {
$r_ign = $_POST['ref_ign'];
}
Secondly when you generate that link with the paramters in it. You are passing the parameters to an html file.
http://www.graphicgoldfish.com/referral.html?ref_username=LRRoberts0122&ref_ign=DerpyGoldfish
You need to pass them to a php file for this to work...
http://www.graphicgoldfish.com/referral.php?ref_username=LRRoberts0122&ref_ign=DerpyGoldfish
How can I avoid that users changing the values in the console. As example my link is:
example.com/delete.php?id=8. When I'm open my console and I change the 8 to 10 then row 10 is deleted.
How can I avoid this? Or by which way I can do it instead of the URL?
The security of an application must never be only on the client side.
You must always consider that URIs called on the client side can be called not just via a form.
If your interface offers a short list of choices, the webservice or server script must check the same reduced choice list before before any other treatment.
You can use a <form method=post action=delete.php ><button type=submit value=8 name=id>delete</button></form> and then, in the PHP, use $_POST['id'] instead of $_GET['id'].
You can also use $_SESSIONs to see if the user is logged in and if he is allowed to delete that id; For instance, when delivering the page set something as $_SESSION['allow_id'] = 8 and then, on the PHP side, you could do something as:
if ((!empty($_SESSION['allow_id'])) && (!empty($_POST)) && ($_SESSION['allow_id'] == $_POST['id'])) { // allow the deletion } else { // don't allow }
I'm very new to web programming and everything I learn I basically learn from looking up documentation online. I have a website running a type of game with an inventory and such. I can't seem to think of a clean way of giving items to the user. It currently uses a JavaScript function, but I realized the user could just call the function from the URL bar and exploit the system.
On a given page, this is the code that calls for an item to be given. The user will click a button like the "Get Hat" button, and will be redirected to another page:
<script>
function giveitem(name, quant)
{
document.getElementById("itemnamefield").value=name;
document.getElementById("itemquantfield").value=quant;
document.itemform.submit();
}
</script>
<form id="itemform" name="itemform" action="./itemget.php" method="post">
<input type="hidden" id="itemnamefield" name="itemnamefield" value="">
<input type="hidden" id="itemquantfield" name="itemquantfield" value="">
</form>
<input type="button" onClick="javscript: giveitem('Hat',1);" value="Get Hat"><br>
itemget.php then executes this function using the post data from the previous page. $id is the user's ID number stored in a cookie, $name is the title of the item, $quant is the desired quantity of the items.
function additem($id, $name, $quant){
include 'sqlconnect.php';
$result = mysqli_query($con, "SELECT * FROM inventory WHERE id='$id' AND name='$name'");
if ($row = mysqli_fetch_array($result)){
mysqli_query($con, "UPDATE inventory SET quant=quant+'$quant' WHERE id='$id' AND name='$name'");
}
else{
$subresult = mysqli_query($con, "SELECT name FROM itemdef WHERE name='$name'");
$subrow = mysqli_fetch_array($subresult);
mysqli_query($con,"INSERT INTO inventory (id, quant, name) VALUES ('$id', '$quant', '$subrow[name]')");
}
}
itemget.php then displays what items the user received.
So I can't use javascript because that's exploitable. I'm not really intent on using jquery or anything besides standard HTML and PHP (I'm trying to keep it simple because I'm so inexperienced). Is my only alternative to create a new form for every "give x item" button?
You can use javascript, forms, or just simple hyperlinks.
The trick is to let the server know which possibilities the user has. So when you generate the page, you can store in the user's session on the server that you generated the 'get hat' link, so 'get hat' therefor is a valid command.
If you receive a command that is not valid, the user may be cheating, or they clicked 'back' and executed a command from an outdated page. Anyway, you can then ignore the command or display a message instead.
So the trick is to keep the validation on the server. That way, they cannot cheat, because everything other than the commands you provided are blocked.
So talking techniques, you can just write the game logic and session handling in PHP and use plain HTML (hyperlinks) to render the commands. If you like, you can use Javascript/JQuery or forms as well, if you think it is easier or makes your gameplay better. As long as you do the checking on the server, you should be fine.
Small example. When you send data to a .php file for the information be processed further, always, and I mean always be panicked(not like bad panic, but just be carefull) and don't trust user info. If you know that the variable $x is supposed to be only integer, then use an if condition to make sure it is an integer so bad/malicious data won't be a problem.
Use PHP Sessions initialized by <?php session_start(); ?>, then you can store information stored on server referenced by a cookie with a session id.
For example don't store user's id in a cookie, use sessions: <?php $_SESSION['user_id'] = 1; ?>
Then, for example you can store available items in that session, too.
game.com/view-x.php
<?php
session_start();
...
$_SESSION['items_available'] = array('hat', 'shoe');
?>
When for example a user requests a an item via html form, link, ...:
game.com/item-add.php?item=stone
<?php
session_start();
...
if (in_array($_GET['item'], $_SESSION['items_available'])) {
..
}
else {
// 'stone' is not an available item
}
...
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).