I have a text file with 700,000 lines of login attempts some of which are successful but mainly - not. Here is an example:
login attempt 2 to server IP as user_name - password failed
login attempt 3 to server IP as user_name - password failed
login attempt 4 to server IP as user_name - **successful**
login attempt 5 to server IP as user_name - password failed
login attempt 6 to server IP as user_name - **successful**
and so on. How can I delete all lines that do not end with 'successful" word?
pseud-ocode:
convert all lines to separate arrays with each word as an array element
to write something like this (pseudocode):
while(line_number <= 700000) {
$all_occurrences .= (end($array) == 'successful') ? whole_line : '';
}
so only these will remain:
> login attempt 4 to server IP as user_name - **successful** login
> attempt 6 to server IP as user_name - **successful**
Any thoughts?
Thank you!
The best thing is to read the files line by line so you don't run into memory constraints.
Solution 1:
<?php
$if = '/tmp/login.attempts';
$of = '/tmp/login.attempts.purged';
$ifh = fopen($if, 'r');
$ofh = fopen($of, 'w');
while(($line = fgets($ifh)) !== false) {
if(preg_match('/successful/', $line)) {
fwrite($ofh, $line);
}
}
fclose($ifh);
fclose($ofh);
?>
Or if you want to use arrays like your sudo code.
Solution 2:
<?php
$if = '/tmp/login.attempts';
$contents = file_get_contents($if);
$all_attempts = explode("\n", $contents);
$successful_attempts = array();
foreach($all_attempts as $attempt) {
if(preg_match('/successful/', $attempt)) {
$successful_attempts[] = sprintf("%s", $attempt);
}
}
// The successful_attempts array contains all your entries
//print_r($successful_attempts);
?>
Related
I'm creating an intranet PHP website without any login requirements. I have an IIS application (based on PHP), authentication is done with Windows Authentication (Anonymous Authentication is disabled). I've successfully managed to set up IIS and windows authentication with some GPO tweaks. My simple PHP page contains $_SERVER['REMOTE_USER']; so active directory user without any login prompts can see DOMAIN\User.Name
In my understanding IIS Windows authentication is very limited and can only display the user's name and domain name. So I enabled LDAP to display more information about the user such as display name or phone number. But I'm stuck here because as far as I know, LDAP uses username and password bind to retrieve information. When I use active directory admin credentials it gives me a table of all user's information but how to filter that table to display only current user information (based on windows authentication).
Code:
<?php
$current_user = get_current_user();
$ldap_password = 'AdminPassword';
$ldap_username = 'Administrator#domain.name';
$ldap_connection = ldap_connect("domain.name");
if (FALSE === $ldap_connection){
echo 'ERROR';
}
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)){
$ldap_base_dn = 'OU=Users,DC=domain,DC=name';
$search_filter = '(|(objectCategory=person)(objectCategory=contact))';
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
echo '<h2>Result</h2></br>';
echo '<table border = "1"><tr><td>Username</td><td>Last Name</td><td>First Name</td></tr>';
for ($x=0; $x<$entries['count']; $x++){
$LDAP_samaccountname = "";
if (!empty($entries[$x]['samaccountname'][0])) {
$LDAP_samaccountname = $entries[$x]['samaccountname'][0];
if ($LDAP_samaccountname == "NULL"){
$LDAP_samaccountname= "";
}
} else {
$LDAP_uSNCreated = $entries[$x]['usncreated'][0];
$LDAP_samaccountname= "CONTACT_" . $LDAP_uSNCreated;
}
//Last Name
$LDAP_LastName = "";
if (!empty($entries[$x]['sn'][0])) {
$LDAP_LastName = $entries[$x]['sn'][0];
if ($LDAP_LastName == "NULL"){
$LDAP_LastName = "";
}
}
//First Name
$LDAP_FirstName = "";
if (!empty($entries[$x]['givenname'][0])) {
$LDAP_FirstName = $entries[$x]['givenname'][0];
if ($LDAP_FirstName == "NULL"){
$LDAP_FirstName = "";
}
}
echo "<tr><td><strong>" . $LDAP_samaccountname ."</strong></td><td>" .$LDAP_LastName."</td><td>".$LDAP_FirstName."</td></tr>";
}
}
ldap_unbind($ldap_connection);
echo("</table>");
}
?>
EDIT: Managed to filter current user by editing LDAP filter:
$search_filter = "(|(objectCategory=persons)(sAMAccountName=*$current_user*))";
Your query is almost right, but it's working in a roundabout way :)
There is no objectCategory called persons. It's just person (no "s"). So objectCategory=persons is always false for every object on your domain. But it's working because you're using an OR (|).
So the only criteria it's really using is sAMAccountName=*$current_user*. But that's asking for any object where sAMAccountName contains $current_user. That has two unintended consequences:
If you have a user called neil, and another called oneil, then whenever neil logs in, you will find both accounts in that search.
Because your search criteria starts with a wildcard (*), it cannot use the index to find the account. That means that it has to look through every object on your domain to find a match. That might not matter if you have a small domain, but the more objects you have on your domain, the longer it will take.
IIS is giving you the exact username, so there is no need to make a "contains" comparison. So your query can be simplified to:
(sAMAccountName=$current_user)
Since sAMAccountName is an indexed attribute, that will be a super fast query.
You will often see the added criteria of limiting the search to user accounts, like this (notice the &):
(&(objectClass=user)(objectCategory=person)(sAMAccountName=$current_user))
But really, only users can authenticate to IIS, and the sAMAccountName is unique across all object types, so it doesn't really matter.
I have tried and tried to get this to work. Essentially I want to read a line of a text file and compare it to the user input. If they are the same then it will continue the log in process.
For now I am just using an echo to see if it actually finds something. it seems that the if statement doesn't see the two inputs as a match even when they are.
$myFile = fopen("users.txt", "r");
$username = $_POST['username'];
while(!feof($myFile))
{
$userN = fgets($myFile);
//compares entered user to text file users
if (($username === $userN)){
echo 'found';
}
}
The only time that it ever finds a match is if the input is left blank as it will be matched with the final line of the file.
Try this code.
<?php
$myFile = fopen("users.txt", "r");
$username = $_POST['username'];
while(!feof($myFile))
{
$userN = fgets($myFile);
//$userN = rtrim(fgets($myFile, "\r\n")); //More cleaner way suggested in comment
//compares entered user to text file users
if ($username == trim($userN)){
echo 'found';
} else {
echo "non found";
}
}
I guess $userN is taking some white spaces or other predefined characters before or after string, so use trim() to remove it.
Although it's not the best way to check users exist, you can load all the users using file() (without the new line and removing any blank entries), which will produce an array of the users. Then just use in_array() to see if the user is in the list...
$username = $_POST['username'];
$userList = file("users.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ( in_array($username, $userList)) {
echo "Found";
}
how are you store user information? are you using commas or something else to separate users and can't you use JSON instead of this in that way it's much easier to store, retrieve and check. if you still need to use i wold like to suggest this method first get all and store in string then convert it to array using PHP function explode and then check the array (assuming text file only contain user name and user separate by , )
myuser.txt
jhone,jonney,mark kevin
read.php
$file = file_get_contents('./myuser.txt', FILE_USE_INCLUDE_PATH);
$arry = explode(",",$file);
$count = 0;
while($count<sizeof($arry)){
if($arry[$count]== $userInput){
echo 'found';
}else{
echo "non found";
}
$count++;
}
How to solve this message Access denied for user 'dbtsorder'#'localhost' (using password: YES) this message appear only online on localhost work fine
i try to load in file from csv file and this message appear only where this code is
database connection:
$host="localhost";
$user="dbtsorder";
$password="M#07765729s";
$db="tsorder";
$conn=mysqli_connect($host,$user,$password,$db);
mysqli_query($conn,"SET NAMES utf8");
mysqli_set_charset($conn,'utf8')
/*************************************/
Load in file code:
if(isset($_POST['submit'])){
$link = realpath('/var/www/order/projectmanagment/');
$checklist = $link.'checklist.csv';
$username=$_SESSION['username'];
$query=mysqli_query($conn,"select* from tbl_user where db_username='$username'")or die(mysqli_error($conn));
$res=mysqli_fetch_array($query);
$fname=$res['db_fname'];
$lname=$res['db_lname'];
$name=$res['db_fname'].' '.$res['db_lname'];
$projectname=$_POST['dep'];
$location=$_POST['cname'];
$psd=$_POST['txt_psd'];
$pdd=$_POST['txt_pdd'];
$past=$_POST['txt_past'];
$padd=$_POST['txt_padd'];
$duration=$_POST['duration'];
$aduration=$_POST['txt_aduration'];
$pnote=$_POST['txt_pnote'];
$transferredto=$_POST['txt_transferredto'];
$client=$_POST['txt_client'];
$cpercentage=$_POST['txt_cpercentage'];
$epercentage=$_POST['txt_epercentage'];
$mpercentage=$_POST['txt_mpercentage'];
$sum=$cpercentage+$epercentage+$mpercentage;
if($projectname=="" || $location=="" || $psd=="" || $pdd=="" || $client=="" ){
echo"Enter All Information.";
}
else{
if($sum==100){
$_SESSION['projectname']=$projectname;
$sql=mysqli_query($conn,"INSERT INTO tbl_project(db_projectname,db_location,db_transferredto,db_psd,db_pdd,db_duration,db_past,db_padd,db_aduration,db_pnote,db_user,db_client,db_cpercentage,db_epercentage,db_mpercentage)VALUES('$projectname','$location','$transferredto','$psd','$pdd','$duration','$past','$padd','$aduration','$pnote','$name','$client','$cpercentage','$epercentage','$mpercentage')")or die(mysqli_error($conn));
$import=mysqli_query($conn,"LOAD DATA INFILE '$checklist' INTO TABLE tbl_checklist FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n' set db_projectname='$projectname' ")or die(mysqli_error($conn));
header("location:allproject.php?msg=2");
}else{echo"Percentage should be equal to 100";}}
}
You can use this code to read csv file and insert data into database
$row=1;
if (($handle = fopen("test.csv", "r"))!== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
$row++;
if($row>2)
{
if($data[0]!="")
{
//write your inset query
}
}
}
fclose($handle);
}
user this code this will work for you,
$data[0] is the first column, for second use $data[1] etc.
So by looking into my Crystalball the issue seems to be with your Permissions.
In mySql you'll have the choice to whitelist certain clients, i suggest you take a read from http://dev.mysql.com/doc/refman/5.7/en/create-user.html to understand how your users work
The next step would be to read the following to learn more about the meaning of permissions http://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html
What's the output of "SHOW GRANTS FOR dbtsorder"
Error is clearly showing that there is a connection problem, please check wheather dbtsorder user has access of tsorder or not. If not then first give this user access to particular database.
So I found/made an "online users" page that shows the users online as well as the visitors, when I log in it shows me as a visitor. I think my sessions aren't working correctly, I've had a lot of problems with database selections too (I'm supposed to get results according to the username, but it doesn't work). I also can't access pages that are set to only allow logged in users.
Here's the code that creates the session name that I call up later
$_SESSION['userlogin']=$username;
Here's the code that prevents users from accessing the page if they aren't logged in, but I get the "You must be logged in" even when I am logged in!!
<?php
include("header.php");
if(isset($_SESSION['userlogin'])){
echo "You must be logged in to view this page!";
}else{
echo "Success, figured it out eh?";
?>
<?php
}
include("footer.php");
?>
And here's the entire users online code
<?php
include("connect.php");
include("header.php");
include('userson.txt');
if(isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['userlogin']) ? $_SESSION['userlogin'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows); // number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
Here's the weird error I get on the users online page too - "127.0.0.1-vst-^^1411198259"
Any ideas? You can test this out yourself as well as my website is up (www.velrania.com), try to ignore all the other errors too :P
Start the session in first row...
session_start();
include("connect.php");
include("header.php");
include('userson.txt');
I'm trying to create a session variable when a user opens the email i send them. Everything is done with two .php files. (mailer.php and register.php)
mailer.php gets all the information for a user and sends them a email with a url to the register.php page.
I want to get a session variable (User_id) from mailer.php into register.php. I've put the following in the email that i send from mailer.php. I doubt it works, but it illustrates what I need.
`$message = $Url . "php session_start(); '$_SESSION[id]' = " . $row['user_id'] . " ?>";
...
$mail->MsgHTML($message);
$mail->Send();`
And then on the register page
`$userID = $_SESSION['id'];`
You cannot attach function inside of the variable...Instead just create new table to store verification code,
function genRandomString() {
$length = 10;
$characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$code = genRandomString();
$message = "http://localhost/start_session.php?verify=$code";
$mail->MsgHTML($message);
if($mail->Send()){
echo 'Message Sent';
// Then execute a query to insert the generated code to your database
}
When user opens his email and click the link, hell go to the verification page.
Match the verification code in the database using get variable and if found, start the session otherwise no session
$code = mysql_real_escape_string($_GET['verify'];
$query = mysql_query("SELECT * FROM verifications WHERE verification_code=$code");
$rows = mysql_num_rows($query);
if($rows > 0){
session_start();
session_regenerate_id();
}
First off, php executes code once, and that is when the page loads.
With that said, correct me if I take your question wrong. You send a mail with an ID that ID you want to be able to fetch once someone opens the mail? I would recommend a regexp or a simple string substr ( string $string , int $start [, int $length ] ) to fetch it from the mail.
If you get the mail as raw text (which you will under normal circumstances) then just grab it.
Example mail:
"Hello12ID:5 My name is..."
A while ago I did handle strings like this, but here it goes.
$id = substr($email, strpos($email,'ID:'), strpos($email, ' ', strpos($email,'ID')));
if (is_numeric ($id)) echo 'failed: '.$id.' is not numeric'; exit;
What it does is that it returns what is between 'ID' and the space therafter. In my case it is 5. So $id = 5 in this case. Then you just save that 5 into a session, which is possible to do at once as well, but better check so it grabs something okay before.
Hope it was what you meant.