PHP, Reading Text File For String - php

i am trying to read a text file and find out if there is a string in there. i have tried many different ways. this is what i have so far,
$file = "./userpass.txt";
$loginuser = $_POST[loginuser];
$loginpass = $_POST[loginpass];
$fileauth = file_get_contents($file);
if (strpos($file,$loginuser) !== false and strpos($file,$loginpass) !== false) {
echo 'Incorrect Password';
} else {
echo 'Hello The Master';
}

change
$loginuser = $_POST[loginuser];
$loginpass = $_POST[loginpass];
to
$loginuser = $_POST['loginuser'];
$loginpass = $_POST['loginpass'];
and this code reads file contents
$fileName = "newfile_testing.txt";
$file_handle= fopen($fileName , "r");
$theData = fread($file_handle, filesize($fileName));
print_r($theData);

You have syntax error. Fix it first. $_POST[loginuser]; should be $_POST['loginuser']; and $_POST['loginpass'];. In strpos() $file should be $fileauth.
$file = "./userpass.txt";
$loginuser = $_POST['loginuser'];
$loginpass = $_POST['loginpass'];
$fileauth = file_get_contents($file);
if (strpos($fileauth,$loginuser) !== false and strpos($fileauth,$loginpass) !== false) {
echo 'Incorrect Password';
}else {
echo 'Hello The Master';
}

Your main problem is that you are trying to find the user/password combination in the filename of that particular file ($file) instead searching against it's contents ($fileauth):
if (strpos($fileauth,$loginuser) !== false and strpos($fileauth,$loginpass) !== false) {
As noted by #Please Wait in his answer (nice catch), you also need to reference the $_POST indexes as a string, so
$loginuser = $_POST[loginuser];
$loginpass = $_POST[loginpass];
should be :
$loginuser = $_POST['loginuser'];
$loginpass = $_POST['loginpass'];

Related

My PHP Script dont want to create a ZIP File

I tried to code a script, that put some data in a zip file. I think I have done all right, but he does not create the zip file.
I already tried a lot, but don´t find the issue.
<?php
$sql_abfrage_cloud = "SELECT * FROM dateien WHERE code = '$zugang' ORDER BY id";
$abfrage_cloud = $mysqli->query($sql_abfrage_cloud);
$verzeichnis = '/upload/';
$zip_name = date("dHis").'_fc.zip';
$anz_dateien = 0;
$error = 'fatal';
while($fetch = $abfrage_cloud->fetch_assoc()){
$anz_dateien = $anz_dateien + 1;
$zip_datei[$anz_dateien] = $fetch['path'];
}
$zip_arch = new ZipArchive;
$status = $zip_arch->open($zip_name, ZipArchive::CREATE);
if($status==true){
foreach($zip_datei as $datei){
$zip_arch->addFile($verzeichnis.$datei, $datei);
}
if(file_exists($zip_name)){
$error = 'false';
} else {
$error = 'true';
}
}
?>
I expected that $error would be 'false' but it´s 'true'.
You need to call $zip_arch->close() to save finish writing the file.
You should also use === when comparing the result of $zip_archive->open(), since the non-true results are numbers, and any non-zero number compares equal to true when type juggling is allowed.
$zip_arch = new ZipArchive;
$status = $zip_arch->open($zip_name, ZipArchive::CREATE);
if($status===true){
foreach($zip_datei as $datei){
$zip_arch->addFile($verzeichnis.$datei, $datei);
}
$zip_arch->close();
if(file_exists($zip_name)){
$error = 'false';
} else {
$error = 'true';
}
}

How to read a file line by line in php and compare it with an existing string?

I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>

php auto generate code on the same file

The following code generates a new php file playlist.php which contains the code as in $start $result variable
$path = "./files/";
$path2="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/";
//echo $path2;
$folder = opendir($path);
$start="<asx version='3.0'>\n<title>Example ASX playlist</title>";
$Fnm = "./playlist.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
$result="<entry>\n<title>$file</title>\n<ref href='$path2$file'/>\n<param name='image' value='preview.jpg'/>\n</entry>\n";
fwrite($inF,$result);
}
}
fwrite($inF,"</asx>");
closedir($folder);
fclose($inF);
I want to generate the same code in the same file which contains this code on a specified line number
is this possible ?
The above php script generates the following code on a new file
http://tinypaste.com/ff242cd6
Here's how to append:
$path = "./files/";
$path2="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/";
//echo $path2;
$folder = opendir($path);
$start="<asx version='3.0'>\n<title>Example ASX playlist</title>";
$Fnm = "./playlist.php";
// build content
$fileContent=$start.'/n';
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
$result="<entry>\n<title>$file</title>\n<ref href='$path2$file'/>\n<param name='image' value='preview.jpg'/>\n</entry>\n";
//append to content
$fileContent .= $result;
}
}
//append to content
$fileContent .= "</asx>";
// append to file and check status
if ( file_put_contents(__FILE__ , $fileContent , FILE_APPEND) === false )
{
echo "failed to put contents in ".__FILE__."<br>";
}
That should do it...
EDIT:
Okay, before I get into it, you should first take a look at some basic PHP tutorials which can be found all over the net.
SO, instead of writing the content to the file, just echo it, and add your dynamic stuff while you echo:
$title='the title of your playlist';
$start="<asx version='3.0'>\n<title>".$title."</title>/n";
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
$result="<entry>\n<title>$file</title>\n<ref href='$path2.$file'/>\n<param name='image' value='preview.jpg'/>\n</entry>\n";
}
}
$endCont = $start.$result."</asx>";
echo $endCont;
I created a new variable called $title. The value of that will be the title generated in the output. You can do this with other tags too like you've done with <entry>\n<title>$file</title>.
echo highlight_file(__FILE__,true);
http://www.php.net/manual/en/function.show-source.php
This gets you back the source code of the current file.

Codeigniter function skipping

Hi this is a simple question, however I have now stared at it long enough to realise im simply not seeing the error. If anyone can see where this is going wrong I would be very thankful.
public function create()
{
$this->load->model('ticket_model');
if($_POST)
{
// validate form
if($this->_validate())
{
// save updates
foreach($_POST as $key => $value){if(!is_array($value)) $_POST[$key] = htmlspecialchars($value);}
if ($_POST['subject'] == '') $body_data['error'][] = "You did not enter a subject.";
if ($_POST['priority'] == '') $body_data['error'][] = "You did not select a priority.";
if ($_POST['status'] == '') $body_data['error'][] = "You did not select a status.";
if ($_POST['ipAddress'] == '') $body_data['error'][] = "You did not enter a ipAddress.";
if ($_POST['text_area'] == '') $body_data['error'][] = "You did not enter a message.";
else
{
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) == FALSE) $body_data['error'][] = "IP Address is not valid IPV4 Address.";
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) == FALSE) $body_data['error'][] = "IP Address cannot be from RFC1918 private space.";
if (filter_var($_POST['ipAddress'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) $body_data['error'][] = "IP Address cannot be from reserved range.";
}
if ($_FILES['filename']['name'] != '')
{
if ($_FILES['filename']['size'] > '1024000')
{
$body_data['error'][] = "The file you uploaded is too large.";
unlink($_FILES['filename']['tmp_name']);
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
else
{
//the file is under the specified size. so copy it from temp to import folder and proccess
$thisFileHumanName = $_FILES['filename']['name'];
$thisFileSize = $_FILES['filename']['size'];
$thisServerFileName = strtoupper(uniqid('A'));
$thisFileType = $_FILES['filename']['type'];
$temp_file_location = $this->config->item('rootpath').'/assets/ticketuploads/'.$thisServerFileName;
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $temp_file_location))
{
$body_data['error'][] = "File could not be moved due to a permissions error.";
unlink($_FILES['filename']['tmp_name']);
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
}
}
//clean error array
$body_data['error'] = array_filter($body_data['error']);
if ($body_data['error'])
{
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
unlink($_FILES['filename']['tmp_name']);
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
}
else
{
$_POST['userId'] = $this->session->get_user_id();
$thisMessageId = $this->ticket_model->save_message($_POST);
if ($_FILES['filename']['name'] != '')
{
//set variables for save
$_POST['file_path'] = $temp_file_location;
$_POST['file_name'] = $thisFileHumanName;
$_POST['file_size'] = $thisFileSize;
$_POST['file_type'] = $thisFileType;
$_POST['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($_POST);
}
$this->ticket_model->save_ticket($_POST);
redirect(base_url().'ticket/');
return;
}
}
}
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['message_list'] = $this->ticket_model->list_message($ticket_id);
$body_data['customer_list'] = $this->ticket_model->list_customers();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$foot_data['contact_search'] = true;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/create',$body_data);
$this->load->view('foot',$foot_data);
return;
}
This is my code, and everything is going well, except for the section where i save the upload, as nothing seems to be firing the model, even thought there is a file being posted from the from submit and there for the filename being posted is != ''......
e.g
if ($_FILES['filename']['name'] != '')
{
//set variables for save
$_POST['file_path'] = $temp_file_location;
$_POST['file_name'] = $thisFileHumanName;
$_POST['file_size'] = $thisFileSize;
$_POST['file_type'] = $thisFileType;
$_POST['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($_POST);
}
my apologies if this is silly mistake.
Why are you doing it this way? Codeigniter has a built in class for uploading files. You also should be using the input class instead of $_POST.
It will make it a lot easier!
As for your code. You're actually setting the $_POST variable and trying to use that in save_ticket. You can't do that.
The predefined $_POST variable is used to collect values from a form
sent with method="post"
You're trying to use it the other way around.
So to make it work, change the $_POST into $something and it should work, but it's still not the way to go.
//set variables for save
$something['file_path'] = $temp_file_location;
$something['file_name'] = $thisFileHumanName;
$something['file_size'] = $thisFileSize;
$something['file_type'] = $thisFileType;
$something['messageId'] = $thisMessageId;
$this->ticket_model->save_upload($something);
didn't have this set.......enctype="multipart/form-data"
red face on this end.

how to modify this code to include logging of ip address to another file

please look at the simple php webpage code below
how can modify my code so that a log file is created on my server which logs each visitor's ip and whether it was successfully redirected to the correct page . something like that.
<?php
$a = $_SERVER['REMOTE_ADDR'];
if ( $a == "117.96.112.122" )
{
header("Location: ad_sams_mobile.html");
return true;
}
else
{
header("Location: ad_other_mobile.html");
return true;
}
?>
See the PHP function file_put_contents. You'll need to use the append flag:
file_put_contents("log.txt", "IP: ". $a .", Location: ad_other_mobile.html", FILE_APPEND);
The Apache access.log should have all the information you need.
All you have to do is parse it.
Something like this:
$logfile = 'redirect.log';
$handle = #fopen($logfile, "a");
$a = $_SERVER['REMOTE_ADDR'];
if ( $a == "117.96.112.122" )
{
$redirect_loc = 'ad_sams_mobile.html';
header("Location: {$redirect_loc}");
}
else
{
$redirect_loc = 'ad_other_mobile.html';
header("Location: {$redirect_loc}");
}
if ($handle && is_writable($logfile))
{
$log = "{$a} -> {$redirect_loc}\n";
fwrite($handle, $log);
fclose($handle);
}
return true; // you always return true so just put it at the end
Or this for IP logging:
<?php
$file = fopen("log.html", "a");
$time = date("H:i dS F");
fwrite($file, "<b>Time:</b> $time<br/>" );
if( $REMOTE_ADDR != null)
{
fwrite($file,"<b>IP address:</b> $REMOTE_ADDR<br/>");
}
if( $HTTP_REFERER != null)
{
fwrite($file,"<b>Referer:</b> $HTTP_REFERER<br/>");
}
fwrite($file,"<b>Browser:</b> $HTTP_USER_AGENT<hr/>");
fclose($file)
?>

Categories