Rectangle 27 2

You stumbled over the biggest problem with encrypting data in the database:

Encryption cannot solve the problem of securing data, it can only "concentrate" it to a key. Wherever you store the key, your application must be able to decrypt the data, so can do an attacker. There are two possible solutions to this problem i know of:

  • Place the key in a place as secure as you can. That means, it should surely be placed outside of the www-root directory in an inaccessible directory on the server. Depending on the importance of the data, you can also consider to outsource encryption to another dedicated server.
  • Don't store a key at all and derive it from the user password. This is the only really safe way, because not even the server can decrypt the data then. The cons are of course, that the user needs to enter the password every time he uses your service. If the user changes the password, you need to re-encrypt all data. If the user forgets the password, the data is lost.

P.S. I would recommend to encrypt the data before storing it to the database, because MySQL AES_ENCRYPT uses the ECB mode without an IV. This allows to search for a certain value, but is less secure (i'm pretty sure that you don't want to search by password).

Now THAT makes sense! Thanks for your answer; it seemed like everything I read online was dancing around this fundamental point (probably because it's understood by most and therefore isn't worth reiterating). Also good to know on your AES_ENCRYPT point. Is there a tutorial out there that you would recommend to get me started on a good encryption practice for PHP? Clearly I'm planning on Googling one up for myself but I was just wondering if there was anything that you might recommend. Thanks again for the help.

@neanderslob - There is a library Zend/Crypt which is often recommended, though i never used it myself, because it probably requires the Zend framework. To do it yourself, choose a mode that uses an IV (like CBC, but not ECB). The IV can be combined with the resulting cyphertext. Then use a binary string of the required length as key (often 32 bytes), not a short password. A simple example you can find on my homepage search for encryptTwofish().

php - Encrypting user data for automatic login to third party system -...

php mysql encryption password-encryption
Rectangle 27 1

You can run this query in model and will get the data from both the tables and then can use it. send id to the model of the id_pengguna. This id will be the user id for comparison Model

function getdata($id){
    $query = "select peng.*, masha.* 
    from pengguna peng join mashasiswa masha 
    on id_pengguna where masha.id_pengguna = $id";
    $query = $this->db->query($query);
    return $query->result_array();
}
$data['result'] = $this->model_name->getdata($id);

first you will get the id from the table where you actually login in. then pass that id to the model.

id_pengguna this is the id you need to get. and then pass through the controller. You got it.

php - get user data from its session Codeigniter - Stack Overflow

php mysql codeigniter
Rectangle 27 1

Its simple, you can create a new query selecting data from your mahasiswa table.

$data["row"] = $this->Mprofile->getmahasiswa();
function getmahasiswa(){
   $idpengguna = $this->session->userdata('idpengguna');

   $this->db->where('id_pengguna', $idpengguna);
   $q = $this->db->get('mahasiswa');
   return $q->row();
}

And in your view

<ul class="category-t">
   <li><?php echo $nim;?></li>
   <li><?php echo $nama_mahasiswa;?></li>
   <li><?php echo $email;?></li>
   <li><?php echo $telepon;?></li>
</ul>

Add this at the top of your view

<?php
   if ($row){
       $nim= $row->nim;
       $nama_mahasiswa = $row->nama_mahasiswa;
       $email = $row->email;
       $telepon= $row->telepon;
   } else {
       $nim =
       $nama_mahasiswa =
       $email = 
       $telepon = "";
   }
?>
<?php echo $row->nim;?>
<?php echo $row['nim'];?>
$this->db->where('idpengguna', $idpengguna);
$this->db->where('id_pengguna', $idpengguna);

still i've got the same issue

@MirzaChilman do you test it when not logged in?

yes i did and still the same issue, and when i called it with another way like using $row['nim'];, there's no result at all, how to change it into an object?

php - get user data from its session Codeigniter - Stack Overflow

php mysql codeigniter
Rectangle 27 1

When I'm working with Auth systems in CodeIgniter I have made it a practice to include the "user" object globally in views, and also globally in my controllers, by fetching the userdata in the constructor, like so...

<?php

class My_Controller extends Controller {

    private $the_user;  //global var to store current user data

    function My_Controller() {
        parent::Controller();

        $data->the_user = $this->ion_auth->get_user();       //get user data
        $this->load->vars($data);                  //load into all views as $the_user "$the_user"
        $this->the_user=$data->the_user;         //load into private class variable "$this->the_user"
    }

At that point $the_user variable object is available in all views by default AND $this->the_user is always available to controller functions. It always represents the user currently logged in.

I am using Ion_auth for authentication and fetching the user, so that piece you would have to fill in.

I actually just constructed a "How-to" to implement extended Controller classes so all the Auth logic is automatically inherited to all "protected" Controllers.

php - How to post non-post data into session when user logs in - Stack...

php mysql class codeigniter methods
Rectangle 27 1

I have fixed it. It was pretty simple.

$config['total_rows'] = $this->db->get_where('dayone_entries', array('uid' => $uid))->num_rows();

php - Codeigniter - Using pagination, display only user's data from da...

php mysql codeigniter pagination
Rectangle 27 1

It'd be as simple as doing something like:

session_start();
$_SESSION['userdata'] = $u_data;

within your CheckLogin method. The session is just a regular PHP array that happens to be automatically preserved for you. You can put anything you want into it, but you do have do put things into it yourself - PHP won't do it for you.

gotcha. So, you simply modify you class to fetch that information from the DB once the login's authenticated. I don't know how your DB class works, but instead of merely checking if there's a matching row, fetch the first/last name, using a query something like this:

select firstname, lastname
from users
where email=$email and password=$password

If you get a result row, you know it's a valid login, and then you just retrieve the name data. I have no idea how your db class works, but it shouldn't be too hard to get it to do that.

I may have it wrong, but I think OP is tracking sessions in a DB table - possibly to support multiple front ends, such as for load balancing. Then again, I may have misread it and s/he really is looking for your answer :)

When user registers and is automatically logged on, first_name, last_name etc are put into my sessions table in the db. This is because the post data is available from when user fills out the registration form. With login now the only fields available are email and password so the only post data I can grab to put into my sessions table would be email. So that's where I became stuck.

php - How to post non-post data into session when user logs in - Stack...

php mysql class codeigniter methods
Rectangle 27 1

If you're tracking sessions in your DB, two solutions come to mind.

First, you could select the first/last from the user table and insert it into the session table. This requires changes to your application.

Second, you could set up a view for your application, in which the session table is automatically joined with the appropriate user, but that assumes you already have some unique identifier for which user it is in the session (was that the email address?*). This solution would not require any changes to the application code, but would require changes to the DB, which may be the preferred method depending upon your deployment requirements (or it may not :) ).

* as a side note, if you're using email addresses for unique identifiers, be aware that some people share email addresses as you decide if this is the right solution for you.

I was thinking of something along those lines. I would like to use the ID of the user. So when the email address is recognised it then get's the id from the row the email address is in then grabs all the associated data such as first_name, last_name and puts this into the session table. Kind of complicated though as my sessions table has 1 column for all the session data.

@Psychonetics: then you may either need to refactor your sessions table or make a second sql query.

php - How to post non-post data into session when user logs in - Stack...

php mysql class codeigniter methods
Rectangle 27 0

Yes, the key (password for decrypting data) has to be stored on the server. There's no way around this, unfortunately.

You can store it in form of a plain text file, somewhere in a folder outside of the users access zone, where only root system user will be able to get it.

You can store it in a different, separate database, with separate set of keys.

You can make your scripts get the key (or second database credentials) from some other script/app on the server, thus improving anti-transparency. In case someone will gain access to first script, he may not gain access to the other.

Finally, you can store it somewhere else, in depths of your network and this is the most complex but secure thing, called KMS - Key Management Server.

Actually KMS doesn't have to be a cloud service or expensive enterprise solution (although, it's the most secure way). It can be just another server outside of the "war zone" (separate network) which stores and "tells" the key only to the trusted server.

I could write a book ~300 pages about managing keys, as I have supervised many quite sensitive data projects complying with PCI DDS3 security standards. You can google for key management and try to find some easy tutorials and schemes.

Thanks for replying. I'm glad to hear from someone with experience in this, it's been helpful; didn't know about KMS before. At least I was thinking along the right lines with storing the encryption key on the server, I'll probably go a head with that implementation. Thanks again, Neil.

Even more, the keys usually are stored encrypted themselves. The key which you encrypted the key with is called key encryption key, or KEK. Just FYI, it's a very vast field for googling, reading and learning.

php - Encrypted MySQL data with varying user number access - Stack Ove...

php mysql encryption
Rectangle 27 0

I believe the industrial standard practice is to check the login once (when the user login to the system) and then create a session out of that. And you can store any data related to current login in that session. Every time a server gets a request it will check the session first and if the session is valid it will return back the details required and there is no interaction with the database (By default PHP store the session data in file, you can change to any storage engine as you like) for validating the user.

Also creating a json file with all the data in user table is not going to be a good practice because it will cause performance problem as you start scaling.

php - Are there performance/security issues or benefits when parsing S...

php mysql json
Rectangle 27 0

Let's take a simple example. Let's say we have a table Characters, with fields id, name and age.

One of the cleaner ways (IMO) to provide an edit form for this table, is to have the form assume there's an array (let's call it $char) that has these fields. The main code would get this array from wherever, be it from the form fields or from the database.

(Note, a lot of stuff has been omitted. I don't know or care what database you're using, or how you do validation; the important part is the form processing, and that works regardless of DB.)

<form method="post">
 <input type="hidden" name="Character[id]" value="<?= intval($char['id']) ?>">
 <input name="Character[name]" value="<?= htmlentities($char['name']) ?>">
 <input name="Character[age]" value="<?= htmlentities($char['age']) ?>">
 <input type="submit">
</form>

When the form is submitted, $_POST['Character'] would be an array, and contains all the info the form submitted about the character.

Let's have a saveCharacter that would take that info and save it as a row... (pseudocode lines start with ...; fragments look ...like this...)

function saveCharacter($char) {
    if (empty($char['id'])):
        ... do insert
        ... $char['id'] = last insert ID
    else:
        ... do update
    endif;

    // return the saved char; inserting would have added an ID
    return $char;
}

...and a loadCharacter to SELECT that row, and return its contents with the same names as you had them in the form. (Keeping the form and database field names consistent helps quite a bit here. If the two use the same names, you can just return the row directly.)

function loadCharacter($id) {
    ... $result = result from: SELECT id, name, age FROM Characters WHERE id = ?
    ... return first (should be only) row of $result
}

(If the names are different, you'll need to convert. You can usually have the DBMS do this for you; google for "SQL column alias" for more info.)

if (isset($_POST['Character'])) {
    $char = saveCharacter($_POST['Character']);
}
elseif ( ...the user already has a character id... ) {
    $char = loadCharacter(...character id...);
}
else {
    // first time on the page, and there's no saved character
    // give $char the right field names, to prevent notices
    $char = array('id' => null, 'name' => null, 'age' => null);
}

And when you include the form from above, it will put $char's values in the proper elements.

Best way to fill in a PHP/HTML form with user specific mysql saved dat...

php html mysql database forms
Rectangle 27 0

I think your approach can be acceptable depending on the amount of accuracy you require.

A more accurate (and probably more complex) approach would be to actually store all locations in coordinates. You can use a geolocation webservice (I believe Google provides one, others too) to map location names into coordinates. You can also use IP based geolocation to try to guess where the user is so they won't necessarily have to type their own address.

There are formulas (and probably libraries) for calculating distances between coordinates relative to each other, which would make it easy to display things within a certain radius from the user's coordinates and stuff like that.

You could also consider using the new HTML5 geolocation API which is supported by the latest browsers

I'm not sure how the geolocation API can help me - if the user provides an invalid location that doesn't validate with the API, then a distance measure between the user and the event's location (which will be much better specified with a street address/Google location API 'place') is not possible.

You can use the geo API to detect the user's location from devices such as the iPhone without them having to manually input (or know) their exact location. Of course it may or may not be useful to you depending on the sort of application you're working on.

Ah, I see. Thanks Jani. The only problem with that, I guess, is that a user will have to manually allow me to collect user agent location information - not particularly user friendly and a lot of users would be suspicious of such functionality.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - Best practices for user physical location (input, data type, dis...

php mysql location user validation
Rectangle 27 0

This can best be achieved using AJAX. There is a tutorial on w3schools.com which explains how ajax works. You will simply have to modify the code they supply.

Fundamentally, what you need is:

<SELECT name='name' id='123' onchange='userhint(this.value)'><OPTION value='usercode'...

As your select. The key is putting the onchange call in the SELECT.

You will also need a form goes here

function userhint(str)
{

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("changingdiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","myphpfile.php?q="+str,true);
xmlhttp.send();
}

This will replace the content of 'changingdiv' with whatever myphpfile.php returns in response to a get request of q. You are clearly capable of writing that file yourself.

Depending on how you want to do it, the php can either create the complete HTML of the new div or return a json string which you can then use to populate your original areas. For a beginner, the first option is definitely easiest (and is expected by the very basic js above) but the json method will use a fair bit less bandwidth and makes it easier to re-use the same file to feed multiple pages.

php - Displaying data from the database when user selects single value...

php jquery
Rectangle 27 0

This can occur when you pass user input directly to the database, something like this:

$query = "SELECT * FROM Table WHERE field = " . $_POST['field'];
$result = mysql_query($query);

The user can put whatever they want into the 'field' field on the form, and the database will execute it. This means a user could enter a malicious string which prematurely terminates your intended query and then runs a query of their own.

Don't directly construct your queries with user input. Instead, you should look into using prepared statements (This is typically handled with the PDO library). Prepared statements can take several forms, but they all involve using placeholders in the actual query string to tell the database where to stick other data you'll pass in later. That way the database can handle any appropriate escaping itself. The code would look a bit like this:

$statement = $db->prepare("SELECT * FROM Table WHERE field = :field");
$statement->bindValue(":field", $_GET['field']);
$statement->execute();

In this case, :field indicates the placeholder for the value later supplied by bindValue. PDO will take care of the escaping as needed.

That said, you should still sanitize any user data as needed.

Cross-Site Scripting, or XSS, occurs when unsanitized user input is passed directly back to the browser. If the user entered JavaScript commands, these commands could be executed in another users browser, possibly allowing the original hacker to gain access to that users credentials.

Rather than going into a lot of detail here, I'll simply say that this can be avoided by setting the HttpOnly flag on any cookies you set, so that they cannot be accessed in JavaScript (malicious or otherwise), and by never, ever echoing back unsanitized inputs to a user.

PHP has some nice features built in for sanitizing many forms of user input. I'll simply recommend that you check out the filter_var function and the various filters it can apply.

Never just echo user input back to the user. You should do your best to validate your inputs and reject anything that doesn't conform, but for inputs you need to display back to the user, always use something like htmlentities(). For a heavier but much more thorough option, you can take a look at the HTML Purifier library.

Hope that gets you started in the right direction.

php - best way to filter data from user(xss and sql injection) - Stack...

php xss sql-injection
Rectangle 27 0

Definitively 3). Storing a serialized array means being dependend on a language (php, json etc), and selecting via sql is impossible. 2) ist bad, because of several reasons; mainly, you are less flexible in extending and selecting. Create a meta table like 3), this is an established approach.

Update: 3) must be improved a bit: Create a table like this:

PHP/MYSQL: What should the best way to record any undefined optionals ...

php mysql
Rectangle 27 0

Save the persistent data (which need to be preserved even if user closes the browser) into database.

As for cookies, please note that it gets sent back and forth with each request. I don't recommend using cookies, except maybe for session ID.

security - What is best way to save user's data to carry through the w...

php security
Rectangle 27 0

Most SQL injections can be prevented with mysql_real_escape_string(), assuming you're running MySQL. Other database systems also have similar functions.

Protecting your site from XSS attacks is more complicated. The simplest way to prevent javascript code injection is stripping away all HTML tags with strip_tags(), but that will prevent using harmless tags like <b> as well, though they can be whitelisted if needed.

php - best way to filter data from user(xss and sql injection) - Stack...

php xss sql-injection
Rectangle 27 0

Does just doing the direct approach (using the index you already have) work? I'm thinking of something like:

select count(*) from user_points where points > x

where x is the number of points for the user you are looking at.

php - Best practices storing, modifying and retrieving user reputation...

php mysql
Rectangle 27 0

MySQL is probably the best option to store large amounts of data. Facebook uses MySQL, and you can only image the amount of data they have on everyone!

The benefits of MySQL: 1, Best for beginners 2, The "goto" database language for PHP 3, Massively open source

The biggest thing to keep in mind the your structure of your database. You can handle an uber amount of information, but just keep in mind that setting data types can, and will, restrict the amount of space for specific columns.

Facebook uses MySQL because that's what they started with (it was free). They have expressed many times their issues with MySQL and with switching RDBMSs. gigaom.com/2011/07/07/

php - Storing large amounts of data related to each user? - Stack Over...

php mysql
Rectangle 27 0

Your best bet is to store all account information on your database as if the user created the account before sending them to PayPal.

So store everything including the username before allowing them to proceed to the checkout. This enables you to validate their information and username before they go to PayPal. Then you cache it all for 48 hours just to make sure they don't lose the username while checking out. You could also take advantage of PHP's session support to track the user if they happen to come back the next day to make the purchase. As long as they didn't clear their cookies/cache and your session lifetime hasn't expired the session server-side, they should be able to resume the session right where they left off and go straight to PayPal.

I would still send all vital data to PayPal just in case the user somehow manages to sit on PayPal's payment page for a week and then decides to put in CC info.

You could also use this system to "check" if the user has already started paying. Perhaps ask them to enter an email address first. Associate all data to that email and the user's IP address ($_SERVER['REMOTE_ADDR']). If you don't have session concurrency for a user, but they enter an email address already in the database. Check their IP (and maybe even browser too if you want to be really anal about it) and if it's a match, tell the user "looks like you started checking out before and never finished. want to continue?" and let them pick up where they left off. Obviously don't store any sensitive information this way, and only cache it in the temp table for paypal stuff so it only lasts for 2 days at best.

This way the user can click "Yes" and they don't have to choose their subscription again and go through all that picking/deciding a second time. If the user says "No, I'd like to start over" then just delete the row in the temp table and make a new one for them.

php - Data integrity when data is stored on our site and the user is t...

php paypal