I am trying to setup a way where users can change the password to a certain area of a website they have access too and that password is stored as part of a .cfg text file. That is the file I need to pull it from. The contents of the file looks like this:
[main]
roomname = "Room Name"
topfile = /my/link/here
bannerfile = /my/link/here
bannersfile = /my/link/here
banner_freq = 40
bodyfile = /my/link/here
configfile = /my/link/here
actionfile = /my/link/here
memberfile = /my/link/here
moderatorfile = /my/link/here
logfile = /my/link/here
bootfile = /my/link/here
numusers = 30
password = mypassword
defaultmessage = "$USER$ : $SAYS$"
messagewrapper = '<TABLE WIDTH="100%" border=0 cellpadding=0 cellspacing=0><TR><TD>($DATESTAMP$ : $TIMESTAMP$) $PROVE$ $REGISTERED$ $MOD$ $MESSAGE$</TD></TR></TABLE><P>'
I have the change password form created, however what I am having trouble with is the .php file to process the form. I've been reading manuals but am not quite sure what else is missing or certain variables to use.
====
Edit/Update
I am updating my code below with my save.php form. It seems to be working except that its overwriting the entire file blankly and I'm not sure why its doing that. I'm also including my form coding from the send page.
<?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['password'];
$filevar = '/my/site/location/here/prpwtest/prtest.txt';
$fh = fopen($filevar, "w");
$file_contents = file_get_contents($filevar);
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$data.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
$success_page = '/my/site/location/here/pulldowns/savesuccessful.html';
header('Location: '.$success_page);
}
}
?>
And here is a snippet of my save code:
<form name="loginform" method="post" action="my/site/location/here/prpwtest/prpwtestsave.php">
<input name="password" type="password" /><p><input name="Submit" type="submit" /></form></p></center>
</div>
Give this a try:
$fileurl = '/path/to/my/file/here/file.cfg';
$replace = 'what I want to put in there when they submit';
$file = file($fileurl, FILE_IGNORE_NEW_LINES); // Get file as array of lines
foreach ($file as $n=>$line)
if (substr($line, 0, 8) === 'password') // Line starts with 'password'
$file[$n] = 'password = '.$replace; // Replace password line
file_put_contents($fileurl, implode("\n", $file)); // Put file back together
You need to parse data from $file_contents.
I.e. after reading of this string, you have to process it line by line to find string starting with 'password=' to modify it. You can use explode() for splitting of this string:
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$newpassword.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
}
Try this.
$array = parse_ini_file('your_ini_file.ini', 'main');
$array['main']['password'] = 'set your password here';
$str = '[main]'."\r\n";
foreach($array['main'] as $key => $value){
$str .= $key.' = '.$value."\r\n";
}
file_put_contents('test.ini', $str, LOCK_EX);
Related
I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}
i have a text file with the following design:
john smith|1|john#smith.com|nopassword|admin
Tom smith|3|tom#smith.com|admin123|user
....
And so on.
Every field is delimited by "|".
What i need to do is replace values for example the password or the account type of a user in this text file.
Tom smith|5|tom#smith.com|admin1234|admin
I succeeded in finding the line and spiting it with explode() but how do i modify the value and write it back on the text file ?
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
foreach($mydb as $line) {
if(stristr($line,$name)) $pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);
There are various ways to do this. Here's one way. I commented the code to explain how it works.
$name = $_POST['name'];
// use FILE_IGNORE_NEW_LINES so you won't have to deal with the line breaks
$mydb = file('./DB/users.txt', FILE_IGNORE_NEW_LINES);
// use a reference (&$line) so the code in your foreach loop modifies the $mydb array
foreach ($mydb as &$line) {
if (stristr($line,$name)) {
// assign the elements of the row to variables
list($name, $number, $email, $password, $type) = explode('|', $line);
// change whatever you need to change
$password = 'new password';
$type = 'new type';
// overwrite the line with the modified values
$line = implode('|', [$name, $number, $email, $password, $type]);
// optional: break out of the loop if you only want to do the replacement
// for the first item found that matches $_POST['name']
break;
}
};
// overwrite the file after the loop
file_put_contents('./DB/users.txt', implode("\n", $mydb));
PHP gives the options of reading, writing, and appending to files.
You need to open the file, read all content in, and then overwrite the file. You will get duplicate entries using append.
Here is an example code from https://www.w3schools.com/php/php_file_create.asp:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
For your code:
<?php
$name = $_POST['name'];
$mydb = file('./DB/users.txt');
$output = array();
foreach($mydb as $line) {
if(stristr($line,$name)) {
$pieces = explode("|", $line);
$position = str_replace(array("\r\n","\r"),"",$pieces[1]);
$email = str_replace(array("\r\n","\r"),"",$pieces[2]);
$password = str_replace(array("\r\n","\r"),"",$pieces[3]);
$atype = str_replace(array("\r\n","\r"),"",$pieces[4]);
// Glue the variables back together and overwrite $line so that it gets up in the array
$line = $name & "|" $position & "|" $email & "|" $password & "|" $atype & "\r";
}
// put everything in the $output array so that it can be writen to file after this loop
array_push($output, $line);
}
fclose($mydb);
// Write your output to file
$mydb = fopen('./DB/users.txt', "w") or die("Unable to open file!");
foreach($output as $line) {
fwrite($mydb, $line);
}
fclose($mydb);
?>
I want to increment $userCount by 1 every time $data and $fileLineArr2[0] have the same value. Could someone explain why $userCount remains 0? I'm a programming student, so please keep help in a way that is understandable to someone with only intermediate experience.
if(!empty($_GET["user"]) && !empty($_GET["pass"]) && !empty($_GET["fname"]) && !empty($_GET["lname"])){
$handle = fopen($accountInfo, 'a') or die('Cannot open file: '.$accountInfo);
$data = $_GET["user"]."; ";
$data = strtoupper($data);
fwrite($handle, $data);
$data2 = $_GET["pass"]."; ";
fwrite($handle, $data2);
$data3 = $_GET["fname"]."; ";
fwrite($handle, $data3);
$data4 = $_GET["lname"].";\n";
fwrite($handle, $data4);
fclose($handle);
$reading2 = fopen($accountInfo, 'r') or die('Cannot open file: '.$accountInfo);
echo "$userCount";
while(!feof($reading2)){
$fileLines2 = fgets($reading2);
$fileLineArr2 = (explode("; ", $fileLines2));
//print_r($fileLineArr2);
**if($fileLineArr2[0] == $data)
{
$userCount++;
}**
echo "$fileLineArr2[0] ";
echo " $data". "\n";
echo "$userCount";
}
fclose($reading2);
if($userCount > 1)
{
$validSignUp = false;
?>
<font color='red'>Username already taken!</font>
<?php
}
elseif($userCount == 0)
{
;
}
else
{
$validLogin = true;
$validSignUp = true;
}
}
When reading from a file, there is an invisible new line character at the end of the string. You will want to remove that and then compare against the $data.
To remove the new line character, you can do something like
$string = trim(preg_replace('/\s+/', ' ', $string));
Where $string is the line from the file.
EDIT
Based on a discussion in the comments section, this is not what you want.
What you will want to do is the following:
$line = explode('; ', $lineData);
Where $lineData is the information being read from the file.
This will give you an array of all the elements that were listed on the line. We know that the username is listed in the first position, IE $line[0]. So we compare our data with that.
if ($line[0] == $data) {
$userCount++;
}
Where $data is the information we are comparing against.
<?php
$userName = array();
$tutorial = array();
$myFile = "students.txt";
$fh = fopen($myFile,'r');
while( !feof($myFile) ){
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
}
fclose($myFile);
echo "$userName";
echo "$tutorial";
?>
and my students.txt content
dasdsa
A
asdasd
D
How to read that and store into different array and print them out
your code should work as expected. I assume you're bit confused with echo "$userName"; output as it displays Array word. try var_dump($userName) instead
Do exactly as you've done, but change
$userName[] = array(fgets($fh));//Save first line content
$tutorial[] = array(fgets($fh));//Save second line content
to
$userName[] = fgets($fh);//Save first line content
$tutorial[] = fgets($fh);//Save second line content
(no need to keep the subitems in their own seperate array)
and print them out by either using print_r, or iterate through them:
for ($i = 0; $i < count($userName); $i++) {
echo $userName[$i] . " - " . $tutorial[$i];
}
$text = file_get_contents('students.txt');
$text = explode("\n",$text);
$output = array();
foreach($text as $line)
{
$output[] = $line;
}
Use function file() in PHP
file — Reads entire file into an array
$array_lines = file('students.txt');
$count = count($array_lines);
$first_arr = array();
$sec_arr = array();
foreach ($array_lines as $i => $line){
if($i%2) $first_arr[] = $line;
else $sec_arr[] = $line;
}
print_r($first_arr);
print_r($sec_arr);
With file() function every line is read as element in array. You can check it with:
print_r($first_arr);
For example, I have a variable "$foo" that includes all the data which I want to show in the CSV:
$foo = "some value,another value,last value";
My goal is to:
Create a CSV file named "some.csv" whose contents are equal to $foo
Upload "some.csv" to my server.
How can this be done?
Update: Here's the exact code that worked for me.
$foo = "some value,another value,last value";
$file = 'some_data.csv';
file_put_contents($file, $foo);
Number 1:
file_put_contents("foobar.csv", $yourString);
Number 2:
$c = curl_init("http://"...);
curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "#foobar.csv"));
$result = curl_exec($c);
curl_close($c);
print_r($result);
note the # before the filename
See
fputcsv()
If $foo is already csv-formatted. You can use file_put_contents()
You don't specify the upload method. Here is an example using ftp (UNSECURE):
$foo = '...csv data...';
$username = "myUser";
$password = "myPassword";
$url = "myserver.com/file.csv";
$hostname= "ftp://$username:$password#$url";
file_put_contents($hostname, $foo);
If you already have the variable with all the data you can use file_put_contents to save it as a csv
How to upload CSV file using PHP (Working Code)
Query Library
<?php
class query{
function mysql_query_string($string){
$enabled = true;
$htmlspecialchars = false; # Convert special characters to HTML entities
/****************************************************************
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
*****************************************************************/
if($htmlspecialchars){
# Convert special characters to HTML entities
$string = htmlspecialchars($string, ENT_QUOTES);
}
else{
/****************************************************************
'"' (double quote) becomes '"'
''' (single quote) becomes '''
****************************************************************/
//$string = str_replace('"',""",$string);
//$string = str_replace("'","'",$string);
}
if($enabled and gettype($string) == "string"){
# Escapes special characters in a string for use in a SQL statement
return mysql_real_escape_string(trim($string));
}
elseif($enabled and gettype($string) == "array"){
$ary_to_return = array();
foreach($string as $str){
$ary_to_return[]=mysql_real_escape_string(trim($str));
}
return $ary_to_return;
}
else{
return trim($string);
}
}
}
?>
Call Csv Method
public function csvFileSubmitData(){
$this->load->library('query');
$query=new query();
$root = DIR_PATH.'public/administrator/csv/';
$fileToUpload= (isset($_FILES['fileToUpload']) and $_FILES['fileToUpload']['size'] > 0 and
$_FILES['fileToUpload']['error'] == 0) ? $_FILES['fileToUpload'] : "";
if(is_array($fileToUpload)){ # CHECK UPLOADED FILE 1 FOR VALIDATION
$fileToUpload['name'] = str_replace(" ","_",$fileToUpload['name']);
$fileToUpload['name'] = str_replace("&","and",$fileToUpload['name']);
# CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
$fnarr = explode(".", $fileToUpload['name']);
}
$rand = rand(1000,10000);
$filecsv = $rand."_".$fileToUpload['name'];
$file1 = $root.$filecsv;
move_uploaded_file($fileToUpload['tmp_name'],$file1);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = $file1;
$addauto = 0;
$save = 0;
$outputfile = "output.sql";
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 1;
$queries = "";
$linearray = array();
$values = "";
$m =0;
$linestext = split($lineseparator,$csvcontent);
foreach($linestext as $line){
if($m++==0){
continue;
}
$lines++;
$line = trim($line," \t");
if($line == ''){
break;
}
$linearray = explode($fieldseparator,$line);
$topicname = $linearray[0];
$question = $linearray[1];
$answer1 = $linearray[2];
if(isset($linearray[1]) and $linearray[1] != ''){
$topicname = $query->mysql_query_string($linearray[0]);
$question = $query->mysql_query_string($linearray[1]);
$answer_type = $query->mysql_query_string($linearray[2]);
}
//Save Csv data in your table like this
//query(insert into topics SET `topic`='".$topicname."',`question`='".$question."');
}}
If you are using Codeignitor Framework so this code is too easy to integrate ,No hard&fast rule you can also use this code plain PHP as well as .....
Thanx
AbdulSamad
To create the CSV you would need to break your string into an array, then loop through it. After that you can save the file to any directory the web server account has access to on your server. Here is an example ...
//variables for the CSV file
$directory = '/sampledir/';
$file = 'samplefile.csv';
$filepath = $directory.$file;
//open the file
$fp = fopen("$filepath",'w+');
//create the array
$foo = "some value,another value,last value";
$arrFoo = explode(',',$foo);
//loop through the array and write to the file
$buffer = '';
foreach($arrFoo AS $value) {
$buffer .= $value."\r\n";
}
fwrite($fp,$buffer);
//close the file
fclose($fp);
Your file will now be written to the directory set in $directory with the filename set in $file.
-Justin