heres my code
$cont = file_get_contents("users.txt");
$lines = explode("\n",$cont, true);
if(in_array('$name', $line)) {
echo "Error user $name in database";
exit;}
I have a file with users name in a text file then that get turned into an array ($lines)
I need it to search the array to see if the user name in in the text file
If the variable $name is a string of the name you would like to find in the array you created from the file it should look more like this:
$cont = file_get_contents("users.txt");
$lines = explode("\n", $cont, true);
if(in_array($name, $lines)) {
echo "Error user $name in database";
exit;
}
I would personally recommend going to route of regular expressions though. Also, I can see the "explode" being a memory hog as the file grows and potentially slowing the site drastically.
I have not looked into this deeply, but if you are going flat file you may want to try something along the lines of http://www.niblr.com/php-flat-file-search-script/ if there will be a large amount of users in the system. Or even just running a regular expresion against the results of file_get_contents.
Related
I am trying to write a php script to confirm an email address. I am using a file instead of a database to store user info which is outside the root directory. The file is csv.
When I try to store its contents in an array and print it, it works but when I try to compare an element from the array, it doesn't work. And also I want to write the email address of the user in csv as the last entry on the same line as other info.
Please help.
<?php
$rows[] = array();
$username = $_GET["username"];
$passkey = $_GET["passkey"];
$userdata = fopen("/****/*********/*****/$username.csv", "r");
$email = $_GET["email"];
$line = file_get_contents("/****/********/*****/$username.csv");
$rows = explode(",", $line);
print_r ($rows);
$newrows = trim($rows[6]);
$newpasskey = trim($passkey);
if($newrows == $newpasskey)
{
echo "Email-Id confirmed.";
fclose($userdata);
$userdata = fopen("/****/********/******/$username.csv", "a+");
fwrite($userdata, ",".$email);
fclose($userdata);
}
?>
I suggest you take a look at PHPs csv functions to ease loading/writing .csv data.
http://php.net/manual/en/function.fgetcsv.php and http://php.net/manual/en/function.fputcsv.php
Also, in your code, make sure that $username and $passkey are set, trimmed and sanitized before continuing.
You might also want to switch from GET to POST method in your form, I personally wouldn't want my password to be seen in the URL.
Try this:
$passkey = trim($passkey);
$stored_pass = trim($rows[6]);
if($stored_pass == $passkey)
{
//do stuff here
}
I found out the reason.I had made a mistake while entering the user info onto the file. I changed the php script that enters user info to the file. Now it works perfectly.
Basically to keep it short I have an assignment for college where I have to make a few scripts.
In one of these I have to make a scripts that records when data is entered wrong in a log in form. So it will take the users IP address and place it into a text file followed by the time, date, error name (e.g. wrong username and password, wrong name, w.e.), error page and attempts made.
I have figured out:
how to get the users ip
how to get the time and date
how to record the attempts
Now, what I want to do: I want the script to search for the users IP address and if this IP address has already been recorded for a failed attempt, instead of making a new record I want it to just add 1 to the attempts made to that IP address, update the time and date. Only in the case that this IP address has not been recorded a new record should be created.
if IP ALREADY EXISTS{
FIND AMOUNT OF ATTEMPTS
attempts++;
}
else{
ADD IP;
ADD TIME;
ADD DATE;
ADD REASON;
attempt=1;
}
this is what i have so far:
<?php
$time = date("h:i:sa");
$date = date("d/m/y");
$error = "Incorrect Data Entered";
$attempts = 0;
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$myFile = "errorLog.txt";
$file = fopen($myFile, 'a') or die("can't open file");
$searchfor = "$ip";
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($myFile);
// escape special characters in the query
$pattern = preg_quote($searchfor, '$ip');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
$attempts = 1;
$stringData = "$ip, $time, $date, $error, $attempts\n";
fwrite($file, $stringData);
fclose($file);
}
?>
If you simply append to the same text file over and over then if you really want to add up the number of attempts by each individual user, then your going to need to rewrite the full txt file as far as I'm aware.
If you want to make it easier for yourself then you can write your txt file in such a way that you can easily obtain the values you need out of it, such as the ip address.
You could write each line like:
IPADDRESS,ERROR CODE,ATTEMPTS /n
Then when you want to change that line you'll need to keep a record of which line it is. A loop will be required to parse your txt file.
So the way I would attempt it would be:
Store text from file into a variable.
Use the explode() function to create an array of records. ( Like a row in a database ). I would use it like $rows = explode("/n" , $txt);
Loop through the rows. I would probably use foreach( $rows as $row) for this.
Keep track of the row number. So create a variable for it and iterate it.
Use the explode() function again to create a list($ip, $err, $attempts) by doing: list($ip, $err, $attempts) = explode("," , $row);
Now use normal php if() function to check to see if the two ips match, if the error codes are the same.
If they do, you can do $attempts++. Now the tricky/essential part.
You will need to create a string up to but NOT including that row and place it into a variable call it something like $firstpart.
You will also need to do the same for the rows after the affect row. eg $lastpart
Now create a new string for your affected row. Easily done: $str = $ip . "," . $err . "," . $attempts;
Finally, write your txt file using the variables, in the order: $firstpart, $str, $lastpart.
Not sure if this will work, not sure how practical this is, but at the very least I hope it helps you to get some sort of brainwave for how to approach your problem.
I have been struggling to create a Simple ( really simple ) chat system for my website as my knowledge on Javascripting/AJAX are Limited after gather resources and help from many kind people I was able to create my simple chat system but left with one problem.
The messages are posted to a file called "msg.html" in this format :
<p><span id="name">$name</span><span id="Msg">$message</span></p>
And then using PHP and AJAX I will retrieve the messages instantly from the file using the
file(); function and a foreach(){} loop withing PHP here is the code :
<?php
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
if(count($data) > $max_lines){
// here i want the data to be deleted from oldest until i only have 20 messages left.
}
foreach($data as $line_num => $line){
echo $line_num . " . " . $line;
}
?>
My Question is how can i delete the oldest messages so that i am only left with the latest 20 Messages ?
How does something like this seem to you:
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
foreach($data as $line_num => $line)
{
if ($line_num < $max_lines)
{
echo $line_num . " . " . $line;
}
else
{
unset($data[$line_num]);
}
}
file_put_contents('msg.html', $data);
?>
http://www.php.net/manual/en/function.file-put-contents.php for more info :)
I suppose you can read the file, explode it into an array, chop off everything but last 20 fields and write it back to file, overwriting the old one... Perhaps not the best solution but one that comes to mind if you really cant use database as Delan suggested
That's called round-robin if I recall correctly.
As far as I know, you can't remove arbitrary portions of a file. You need to overwrite the file with the new contents (or create a new file and remove the old one). You could also store messages in individual files but of course that implies up to $max_lines files to read.
You should also use flock() to avoid data corruption. Depending on the platform it's not 100% reliable but it's better than nothing.
I'm creating a humble web browser-game in PHP. I'm making a "robbery" section...
I want to greet the user if he succeeds at a robbery. Some messages like "You're the man!", "A piece of cake, it was" etc.
I want more than, like, 5 different messages/notifications like this. How could I do this? how could I pick them from a .txt file, or have them imported from another PHP page which has these messages stored in variables to the "robbery" page...
Please, if you can provide a useful snippet of code, like a function for picking random messages, etc, that would be great.
Also if you can use OOP... :)
Thank you very much in advance...
This is a function that accepts a string (the filename) and reads the messages from it. It then returns the messages as an array so you can use them in your app.
<?php
function loadMessagesFromFile($file)
{
if(!file_exists($file))
{
return false;
}
$fh = fopen($file, 'r');
$messages = array();
while($data = fgets($fh))
{
$messages[] = $data;
}
fclose($fh);
return $messages;
}
$messages_from_file = loadMessagesFromFile('messages.txt');
$key = array_rand($messages_from_file);
echo $messages_from_file[$key];
Another option is storing the messages in PHP:
<?php
$messages = array('message', 'another message');
$key = array_rand($messages);
echo $messages[$key];
I don't see a specific need for an object here, just a function...
function message(){
$mes = array("Message 1","Message 2","Message 3","Message 4");
shuffle($mes);
return $mes[0];
}
That will give you a random message from one of the ones you put in the array. You could make as many messages as you like.
Or...
You could do an include file like you asked. I would again store them in an array in the include file then return a random message.
messages.php:
$mes = array("Message 1","Message 2","Message 3","Message 4");
index.php
include('messages.php');//be sure to include path to messages.php
shuffle($mes);
echo $mes[0];//will echo a random message
Put your messages into a file, one message per line, and then you can load that file into an array using file. The FILE_IGNORE_NEW_LINES flag will strip the newline from the end of each element in the returned array. Then you can shuffle the array to randomize it.
$messages = file('messages.txt', FILE_IGNORE_NEW_LINES);
shuffle($messages);
$message = $message[0]; // get the first of the shuffled $messages
I've got a php file echoing hashes from a MySQL database. This is necessary for a remote program I'm using, but at the same time I need my other php script opening and checking it for specified strings POST parsing. If it checks for the string pre-parsing, it'll just get the MySQL query rather than the strings to look for.
I'm not sure if any functions do this. Does fopen() read the file prior to parsing? or file_get_contents()?
If so, is there a function that'll read the file after the php and mysql code runs?
The file with the hashes query and echo is in the same directory as the php file reading it, if that makes a difference.
Perhaps fopen reads it post-parse, and I've done something wrong, but at first I was storing the hashes directly in the file, and it was working fine. After I changed it to echo the contents of the MySQL table, it bugged out.
The MySQL Query script:
$query="SELECT * FROM list";
$result=mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
echo $row['hash']."<br>";
}
What I was using to get the hash from this script before, when it was just a list of hashes:
$myFile = "hashes.php";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
$mystring = $theData;
$findme = $hash;
$pos = strpos($mystring, $findme);
The easiest thing to do would be to modify your first php file which echoes everything, along these lines:
change every instance of echo to e.g. $data[] =
at the bottom, do foreach($data as $d) echo $d (this will produce the same result as you have right now)
you now still have your $data array which you can loop through and do whatever you like with it.
To provide working code examples, it would be great if you could post the current code of your file.
EDIT
If you change your script like so:
$query="SELECT * FROM list";
$result=mysql_query($query);
while($row=mysql_fetch_array($result, MYSQL_ASSOC)){
$data[] = $row['hash']."<br />";
}
foreach($data as $d) {
echo $d;
}
...you'll have the array $data that contains each hash in a key. You can then loop through this array like so:
foreach($data as $d) {
//do something
}