i am new to PHP so don't know how this would turn out. Lets say i have a add friend page. And in the database lets say i have a table called "friends" and the following rows: my_id and friend_id and id_request.
And now i have a php page that will look something like: addfriend.php?id=friendid
And then i use the id from that link to insert in to the database my id and that friendid.
The question is what will happen if someone enters "kdjfkldjlfk" in the link in the address bar?
you need to prevent those cases and validate
ex:
test that the $_GET['id'] isset and that the friendid is real , you could query the database to see that the id exists ...
If you mean "What will happen if someone visits the URI for an id that does not exist?", then it depends on what your PHP says should happen.
If your PHP doesn't check how many results it got from its SQL query, then it is quite possible that the page will spit out a 500 Internal Server Error.
If you've designed it properly, then it would return a document that explains that you cannot add a user that does not exist as a friend.
Actually, if you've designed it properly then the data should be sent via POST not GET since adding a friend is not an idempotent event. (See the HTTP specification — GET should be free of side effects)
You need to validate your user input. First, cast the $_GET value to an int type, and if it's equal to 0, tell them they've mistyped it.
$var = (int)$_GET['id'];
if($var == 0)
{
// Error
}
else
{
// The rest of your code
}
It turns out that PHP has some pretty cool filter functionality built-in. You should learn them and use them:
if (filter_var($_GET['id'], FILTER_VALIDATE_INT) === false) {
// error
}
if (filter_var($_GET['email'], FILTER_VALIDATE_EMAIL) === false) {
// error
}
if (filter_var($_GET['ip_address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
// error
}
http://us.php.net/manual/en/function.filter-var.php
Related
I am building my wedding website and want to integrate an RSVP form using Gravity Forms. The issue I am running into is how to set certain guest that have +1's. I would like to show an additional guest entry (First Name, Last Name, Meal Option) when the initial First Name and Last Name has been populated. How would I go about doing this? Any help would be great! Thanks in advance!
Here is how I'd solve this problem:
First, you need to put everything in the DB, the easiest way would be to either do it manually or somehow loop through an array/CSV calling add_option($key, $value) Again, I would recommend a mobile/phone number as they'll be unique so you don't pull the wrong "John Smith". I'll assume you'll keep it basic with $key as the unique identifier and $value as boolean as to whether to show additional info. Interestingly, by default, if not found get_option($key) will return false and therefore not show your additional data, which I would assume you'd want anyway. If you'd rather it return true just pass true as the second argument.
Now for your answer:
Your URL is something like https://somesite.com/rsvp?id=1234.
function allowed_plus_one() {
$id = $_GET["id"];
$allowed = get_option($id);
return $allowed;
}
Then assumedly it'll be something like
if (allowed_plus_one()) {
// show form with plus one
} else {
// show form without
}
EDIT:
Keeping separate incase this has already been viewed.
You should also be checking for the existence of $_GET["id"] and behaving accordingly. eg:
if (isset($_GET["id"] && !empty($_GET["id"]) {
//do logic above
} else {
//here by mistake so don't show any form?
}
I am currently working on a Banlist for my game, and it is currently functional, but I want to know if there is a way to use post ex: http://example.com/banlist?newentry=SAVETHIS
and save into a new case in the switch statement.
Basically, I want to store the "SAVETHIS" after the newentry into a brand new case.
Here's an image to help you understand what I mean.
You need some type of storage instead of writing a code that writes itself.
if(isset($_GET['newentry'])){
if(file_put_contents('./banlist.txt', $_GET['newentry'] . PHP_EOL, FILE_APPEND) === false){
die('no perms, cant create file in '.getcwd());
} else {
die('user banned');
}
} elseif(isset($_GET['id'])){
if(in_array($_GET['id'], explode(PHP_EOL, file_get_contents('./banlist.txt')))){
die('user is banned');
}
}
See this as an EXAMPLE code, preferred is to use a database and put this code behind a login wall of some sorts as it has NO SECURITY checks.
In its current state, if I know the location of this script I can simply create a loop and ban every user in range of 0 to MAX_INT. Also it does not check if the user is already banned, so I can fill up your hard drive by looping a simple script to infinity. Noor does it check for potential XXS attacks.
I am checking if the particular parameter is passed and if a folder exists for that parameter. ex
if ((! isset($_GET["name"])) or (! is_dir($_GET["name"]))) {
print "----------------USER NOT FOUND-----------------" ;
}
and in my URL if have name=Erik and if that folder does not exist in that name, I want to print the Error message.
Also I would like to check if the parameter'name' is passed into URL using isset.
Somehow the above does not work and I am unable to figure out why.
Any input will help.
Thanks
or has a different use. It's for whenever something you are trying to do does not work, then it executes the other bit. Typical deprecated example would be when you try to do some database interaction, you'd write back then $STH = mysql_query('SELECT * FROM users') or die();. For your case, you should use the || operator instead, as explained in the documentation
Besides, you are not checking if someone submitted something. This will never print anything if a form is submitted with nothing in it. Both errors fixed, your code should look something like this:
if (empty($_GET["name"]) || !is_dir($_GET["name"])) {
print "----------------USER NOT FOUND-----------------" ;
}
Because, if someone submits the form, the url will be example.com/index.php?name=, which makes $_GET['name'] to be set while it's empty. I assume you want to say User not found in that situation.
Help! I'm writing some code to update a mySQL database using similar to the code below:-
$.post('http://myURL.com/vote.php?personID=' + personID + '&eventID=123');
The vote.php code takes the querystring values and inserts a record into a database with those values in it.
This kind of code is working fine, but I've realised the problem is that people could just type something like:
http://myURL.com/vote.php?personID=5&eventID=123
into their address bar and essentially spam the app...
Is there a straightforward way I can ensure this doesn't happen? I'm reasonably new to these technologies so not aware of how everything works or fits together, but I'm learning fast so any pointers would be super useful.
It is not a good idea to use GET parameters for data that goes to a database. Generally, you want to use POST parameters which are not visible in the URL. So instead of :
$.post('http://myURL.com/vote.php?personID=' + personID + '&eventID=123');
You would do it like this :
$.post('http://myURL.com/vote.php', { "personID" : personID, "eventID" : 123 });
And in your PHP script, you would access your data with the $_POST array like this :
$personID = $_POST['personID'];
$eventID = $_POST['eventID'];
However, don't forget to properly filter input before saving to the database to prevent bad things like SQL Injection.
This is not a silver bullet : spam will still be possible because any HTTP client will be able to send a post request to your site. Another thing you can look at is Security Tokens to make it even less vulnerable to spam. Or implement a system that limits the number of request/minute/user... but I'm getting too far from the original question.
Correct syntax of $.post is
$.post(url,data_to_send,callback_function)
By using this method your user will never be able to damage your site.Use like
$.post('http://myURL.com/vote.php',{"personID":personID,"eventID":123);
Whether you're using POST or GET, you could always consider signing important fields in your page by using hash_hmac. This prevents people from changing its value undetected by adding a signature that no one else can guess.
This also makes CSRF more difficult, though not impossible due to fixation techniques. It's just yet another technique that can be put in place to make it more difficult for "fiddlers".
The following function adds a salt and signature to a given person id to form a secured string.
define('MY_SECRET', 'an unguessable piece of random text');
function getSecurePersonId($personId)
{
$rnd = uniqid("$personId-", true);
$sig = hash_hmac('sha1', $rnd, MY_SECRET);
return "$rnd-$sig";
}
You would pass the output of getSecuredPersonId() to JavaScript to pass as data in the $.post() or $.get(); posting would be recommended btw.
When the form is submitted your person id would end up in either $_GET['personID'] or $_POST['personID'] depending on the request method. To validate the given value, you run it through this function:
function validateSecurePersonId($securePersonId)
{
if (3 != count($parts = explode('-', $securePersonId))) {
return false;
}
// reconstruct the signed part
$rnd = "{$parts[0]}-{$parts[1]}";
// calculate signature
$sig = hash_hmac('sha1', $rnd, MY_SECRET);
// and verify against given signature
return $sig === $parts[2] ? $parts[0] : false;
}
If the value is properly signed, it will return the original person id that you started out with. In case of failure it would return false.
Small test:
$securePersonId = getSecurePersonId(123);
var_dump($securePersonId);
if (false === validateSecurePersonId($securePersonId)) {
// someone messed with the data
} else {
// all okay
}
Here's a situation, i have a list of support tickets that when you click the title of the ticket takes you to a page that displays the ticket in more detail. If uses URL GET variables to query the database. I've taken SQL injection into account but what if someone modifies the url to an id that doesn't exist? whats the best way to deal with that?
Thanks,
Jonesy
If the ID does not exist, send a 404 - Not Found header along with a nice error page telling the user that it wasn't found.
You probably have to make a page handling unsuccessful searches anyway; just route it in there. Then you can help the user to find what (s)he searches in a consistent way, provide cues and "most-searched-after" and what not.
This may seem too simple, but you should always validate your GET (or POST) variable before doing anything with them. In your case, just verify that the ID exists in the database. If it doesn't, inform the user.
You should always check if your query returned anything. If it returned 0 rows, the ID doesn't exist.
<?php
$result = mysql_db_query("your query", $link);
$num_rows = mysql_num_rows($result);
if($num_rows < 1) {
// row with that id doesnt exist
// do whatever you want
} elseif($num_rows > 1) {
// you have problem with your ids in db
} else {
// everything went fine
// do your thing here
}
?>
Check if the ticket exists; if not, react accordingly. What "react accordingly" means is determined by your business logic: create a new ticket? raise an error? take the user to a list of available tickets?
An example using the old mysql extension for brevity:
$sanitized_numeric_id = (int) $_GET['ticket_id']; // assuming id is numeric
$query_resource = mysql_query('SELECT `somecolumn`, `column2`, `othercolumn`
FROM `tickets`
WHERE `id`= ' . $sanitized_numeric_id);
if (mysql_num_rows($query_resource) > 0) {
// the ticket exists, do something with it
} else {
// the ticket doesn't exist, react accordingly
}