-1

I'm creating a small classroom-app website, where students will be logging in with a random generated code which the teacher will give them. I need every student to have a unique code so I'm using the following script

$count = file_get_contents($classcode . "/count.txt");
$count = $count + 1;
file_put_contents($classcode . "/count.txt", $count);

Now my question is, will clients be able to receive the same value for $count if they load up the page simultaneously? And maybe anyone has an better way to do such thing?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    Why not use a database? – George Irimiciuc Sep 25 '15 at 19:46
  • @GeorgeIrimiciuc the program it self is really small, setting up a database seems unnecessary to me. There should be other ways (like above), and wouldn't it raise the same question? Getting the number out of a database is almost the same as getting it out of a file, right? – Merijn Den Houting Sep 25 '15 at 19:51
  • You can create a random string on each login ? – Subin Thomas Sep 25 '15 at 19:52
  • TXT can be manually altered, are vulnerable to data corruption, can be polluted, demands extra logics and a lot of headache to work queries, statements, procedures, data fetching of any kind... It's about changing the scope to evade problems that can be evaded. Just look at the trouble you're getting just to produce primary keys while a DB would do the dirty work for you with handful of security and availability. – al'ein Sep 25 '15 at 19:53
  • I highly recommend SQLite. – George Irimiciuc Sep 25 '15 at 19:53
  • It would be much better for the application in general to use a database because you can not narrow down results by query when you are grabbing from a file. Also if you go down this path and you are then asked to do a page that summarizes all the codes or something, you have loop through folders and such and such, it will be a pain...you will ask yourself why you didn't do a database in the first place... – Rasclatt Sep 25 '15 at 19:53
  • Those above are the answers to your question *And maybe anyone has an better way to do such thing?* --> **definitively a database**. – al'ein Sep 25 '15 at 19:56
  • well the only thing they need is a number.. and doing that in order is the easiest since the teacher client can read the file as well and display the amount of students connected.. a database for just a number?.. – Merijn Den Houting Sep 25 '15 at 19:57
  • @AlanMachado actually my main question was if it would be possible using the script above for clients to get the same number, I would be really interested to know – Merijn Den Houting Sep 25 '15 at 19:59

1 Answers1

0

To answer your question, yes, the file can be overwritten unless you lock it

file_put_contents($file, $person, FILE_APPEND | LOCK_EX);

Documentation: file_put_contents

More info - file_get_contents does not respect file locking

Community
  • 1
  • 1
George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88