I am working on this website(for minecraft servers) that when you enter in a few things about your server, it will upload the info onto the list of servers. The thing is, I am a complete noob at PhP.
Here is my form code:
http://pastie.org/8061636
And here is my php code:
<?php
$name = $_POST['sName'];
$ip = $_POST['sIp'];
$port = $_POST['sPort'];
$desc = $_POST['sDesc'];
$finalName = $ip."(".$port.").txt";
$file = fopen($finalName, "w");
$size = filesize($finalName);
if($_POST['submit']) fwrite($file, "$name, $ip, $port, $desc");
header( 'Location: http://www.maytagaclasvegas.com/uniqueminecraftservers/upload/' ) ;
?>
Now what I am trying to do it get do is create a new file name using $ip and $port, and put this into a table. Can anyone help a newbie out? Thanks
Try something like this
file_put_contents("/path/to/files/".$ip."-".$port.".dat",
$_POST['sName'].",".$_POST['sIp'].",".$_POST['sPort'].",".
$_POST['sDesc']);
Then to create your table you would need to do something like this.
$files = glob("/path/to/files/*.dat");
echo "<table>";
foreach($files as $file){
echo "<tr><td>".implode("</td><td>", explode(",",file_get_contents($file),4))."</td></tr>";
}
echo "</table>";
It would be a lot safer though to just use a database.
Try this one:
<?php
$name = $_POST['sName'];
$ip = $_POST['sIp'];
$port = $_POST['sPort'];
$desc = $_POST['sDesc'];
$finalName = $ip."(".$port.").txt";
if($_POST['submit']) {
$file = $finalName;
// Append a new person to the file
$content = "$name, $ip, $port, $desc";
// Write the contents back to the file
file_put_contents($file, $current);
}
?>
Note: Be sure you have write (may be 777 in linux) permission on your folder where you are saving the file.
Related
I'm making a simple setup form where you are asked to enter your database credentials which are stored in another PHP file but when the user submits it the contents in the database credentials file are deleted and the file is just empty. I have tried debugging my code but still can't figure out what is causing the problem.
My database credentials file:
<?php
define("DATABASE_HOST", "{DB_HOST}");
define("DATABASE_USER", "{DB_USER}");
define("DATABASE_PASSWORD", "{DB_PASSWORD}");
define("DATABASE_DATABASE", "{DB_NAME}");
My code:
$databasehost = $_POST['databasehost'];
$databaseuser = $_POST['databaseuser'];
$databasepassword = $_POST['databasepassword'];
$databasename = $_POST['databasename'];
$searchF = array('{DB_HOST}','{DB_USER}','{DB_PASSWORD}','{DB_NAME}');
$replaceW = array($databasehost, $databaseuser, $databasepassword, $databasename);
$fh = fopen("../static/database.php", 'w');
$file = file_get_contents('../static/database.php');
$file = str_replace($searchF, $replaceW, $file);
fwrite($fh, $file);
fclose($fh, $file);
Thanks,
Nimetu.
You read the file with the call
$file = file_get_contents('../static/database.php');
after you have opened the file using w. Opening it for write will automatically blank the file. So change the order to
$file = file_get_contents('../static/database.php');
$fh = fopen("../static/database.php", 'w');
I'm trying to make a PHP page that queries a database, creates a CSV in the tmp folder then sends that csv to the browser to download, but the file that downloads contain only the last echo in the PHP script, not the file that is stored on the server (that file is saved on the server is perfect).
<?php
$db_host = "localhost"; //can be "localhost" for local development
$db_username = "root";
$db_password = "";
$db_name = "seinventory";
$link = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die(mysqli_error($link));
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$softwareName = $_GET['soft'];
$result = mysqli_query($link,"SELECT * FROM `seinventory` WHERE software LIKE '%$softwareName%' or apps LIKE '%$softwareName%'");
$timeStamp = date('d.m.Y-h.i.s');
$csvFile = 'C:/xampp/htdocs/tmp/file.csv';
$new_csv = fopen($csvFile, 'w');
$headings = Array('PC Name','Software Name','Software Version');
fputcsv($new_csv, $headings);
while($row = mysqli_fetch_array($result))
{
$pcName = $row['pcName'];
$software = $row['software'];
$app = $row['apps'];
$softwareArray = explode(";", $software);
$appArray = explode(";", $app);
$multiArray = array_merge($softwareArray, $appArray);
foreach ( $multiArray as $value ) {
$singleSoftwareArray = explode(":", $value);
$softwareItem = $singleSoftwareArray[0];
$pcName = str_replace('.domain.local', '', $pcName);
if (stripos($softwareItem, $softwareName) !== false) {
$singleArray = Array($pcName, $singleSoftwareArray[0], $singleSoftwareArray[1]);
fputcsv($new_csv, $singleArray);
}
}
}
fclose($new_csv);
mysqli_close($link);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="file.csv";');
//unlink($csvFile);
echo "<script>window.close();</script>";
I read somewhere I'm supposed to put exit; after the fclose to stop it writing to the file, but my file on the server is perfect somehow it's being changed during the download process.
You must echo the content of the CSV file to get the correct file. Remove the last echo from your code and replace it with this one.
echo file_get_contents('C:/xampp/htdocs/tmp/file.csv');
As you are storing the file locally you can also redirect the user to a file URL and it should trigger the download. You won't have to pass the content-disposition header if you do it. You have to remove lines providing Content-Type, Content-Disposition header, and last echo statement if you decide to do it this way.
header("Location: tmp/file.csv");
If you are creating the file just temporarily and removing it afterwards then I suggest you should store the data in memory and echo it afterwards.
<?php
$db_host = "localhost"; //can be "localhost" for local development
$db_username = "root";
$db_password = "";
$db_name = "seinventory";
$link = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die(mysqli_error($link));
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$softwareName = $_GET['soft'];
$result = mysqli_query($link,"SELECT * FROM `seinventory` WHERE software LIKE '%$softwareName%' or apps LIKE '%$softwareName%'");
$timeStamp = date('d.m.Y-h.i.s');
$new_csv = fopen('php://memory', 'w+');
$headings = Array('PC Name','Software Name','Software Version');
fputcsv($new_csv, $headings);
while($row = mysqli_fetch_array($result))
{
$pcName = $row['pcName'];
$software = $row['software'];
$app = $row['apps'];
$softwareArray = explode(";", $software);
$appArray = explode(";", $app);
$multiArray = array_merge($softwareArray, $appArray);
foreach ( $multiArray as $value ) {
$singleSoftwareArray = explode(":", $value);
$softwareItem = $singleSoftwareArray[0];
$pcName = str_replace('.domain.local', '', $pcName);
if (stripos($softwareItem, $softwareName) !== false) {
$singleArray = Array($pcName, $singleSoftwareArray[0], $singleSoftwareArray[1]);
fputcsv($new_csv, $singleArray);
}
}
}
mysqli_close($link);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="file.csv";');
// set the file pointer position back to 0
rewind($new_csv);
// echo all the contents from current file pointer position(In this case from start of the file)
echo stream_get_contents($new_csv);
So for an assignment, I have to create a form where users can post ride shares so other people can see and join their ride. I'm doing this by writing the form to a file data.txt, and reading the file to display all the rides on a board. My only problem is when I get the contents of data.txt, it's all combined together. I need to be able to display each ride separately. How would I go about doing this?
Here is my code so far:
The writing:
if (isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['date'])
&& isset($_POST['destination'])
&& isset($_POST['msg'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$destination = $_POST['destination'];
$msg = $_POST['msg'];
//TODO the file write here VV, use 'a' instead of 'w' too ADD to the file instead of REWRITING IT.
$arr = [$name,$email,$date,$destination,$msg];
$write = json_encode($arr);
$file = fopen('data.txt', 'a');
fwrite($file, $write);
fclose($file);
}
And the reading:
$path = 'data.txt';
$handle = fopen($path, 'r');
$contents = fread($handle, filesize($path));
echo $contents;
fclose($handle);
$newarr = [json_decode($contents)];
foreach($newarr as $stuff)
{
echo $stuff[0];
}
And the output is something like:
["Simon Long","example#gmail.com","2109-01-01T01:01","canada","this is a message"] Simon Long
Let's say there are multiple postings in there, it would just print them all together. I need a way to separate postings so I can display them nicely on the board.
Use a multidimensional array.
$arr = [
"Simon Long","example#gmail.com","2109-01-01T01:01","canada","this is a message",
"John Doe","john#gmail.com","2109-01-01T01:01","canada","this is a message",
"Jane Doe","jane#gmail.com","2109-01-01T01:01","canada","this is a message"
];
Then you when you add to it just append to the final array and replace the whole file.
$contents = file_get_contents($path);
$decoded = json_decode($contents);
$decoded[] = [$name,$email,$date,$destination,$msg];
file_put_contents($path, json_encode($decoded)); //replace the entire file.
Also just as a side note. isset accepts multiple arguments so you don't need to use it as you are. You can do this:
if (isset($_POST['name'], $_POST['email'], $_POST['date'], $_POST['destination'] ...)
It's also a good idea to sanitise any input from the user.
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
Im working on a simple encryption app that able to encrypt php files inside a folder using this class. My problem is after decryption, all the files are not working like the variables and the functions. When I tried to echo a variable its says undefined.
Hope you help me.
Thanks.
SAMPLE CODE
<?php
require_once('func.php');
require_once('encryptionClass.php');
if(is_array($_FILES)){
$encrypted_dir = "encrypted_files/";
$saveFiles = browseDir($encrypted_dir);
foreach($saveFiles as $file){ // iterate files
if(is_file($encrypted_dir.$file))
unlink($encrypted_dir.$file); // delete file
}
foreach($_FILES['files']['name'] as $key => $value){
$file = explode(".", $_FILES['files']['name'][$key]);
$ext = array("php");
if(in_array($file[1], $ext)){
$file_name = $file[0].'.'.$file[1];
$source = $_FILES['files']['tmp_name'][$key];
$location = $encrypted_dir.$file_name;
$code = file_get_contents($source);
$encryption_key = 'CKXH2U9RPY3EFD70TLS1ZG4N8WQBOVI6AMJ5';
$cryptor = new Cryptor($encryption_key);
$crypted_token = $cryptor->encrypt($code);
$f = fopen($location, 'w');
// DATA BEING SAVE TO THE ENCRYPTED FILE
$data = '
<?php
require_once("../encryptionClass.php");
$encryption_key = "CKXH2U9RPY3EFD70TLS1ZG4N8WQBOVI6AMJ5";
$cryptor = new Cryptor($encryption_key);
$crypted_token = "'. $crypted_token .'";
$token = $cryptor->decrypt($crypted_token);
echo $token;
?>
<!-- trying to display the value of variable from $token -->
<p><?php echo $name; ?></p>
';
fwrite($f, $data);
fclose($f);
unset($code);
}
}
}
?>
After decrypting, your decrypted code is inside $token variable as a string. NOT PHP CODE, but STRING.
So, you need to write the $token content into a temporary file and require that file in order to access it like PHP Code.
Hope you understand.
Also, you can give a try to eval($token) instead of echo $token. This will evaluate the string as PHP code. However, this is very bad practice.
I tried and looked for a solution, but cannot find any definitive.
Basically, I have a txt file that lists usernames and passwords. I want to be able to change the password of a certain user.
Contents of users.txt file:
user1,pass1
user2,pass2
user3,pass3
I've tried the following php code:
// $username = look for this user (no help required)
// $userpwd = new password to be set
$myFile = "./users.txt";
$fh = fopen($myFile,'r+');
while(!feof($fh)) {
$users = explode(',',fgets($fh));
if ($users[0] == $username) {
$users[1]=$userpwd;
fwrite($fh,"$users[0],$users[1]");
}
}
fclose($fh);
This should works! :)
$file = "./users.txt";
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(',',fgets($fh));
// take-off old "\r\n"
$username = trim($user[0]);
$password = trim($user[1]);
// check for empty indexes
if (!empty($username) AND !empty($password)) {
if ($username == 'mahdi') {
$password = 'okay';
}
$users .= $username . ',' . $password;
$users .= "\r\n";
}
}
// using file_put_contents() instead of fwrite()
file_put_contents('./users.txt', $users);
fclose($fh);
I think when you get that file use file_get_contents after that use preg_replace for the particular user name
I have done this in the past some thing like here
$str = "";
$reorder_file = FILE_PATH;
$filecheck = isFileExists($reorder_file);
if($filecheck != "")
{
$reorder_file = $filecheck;
}
else
{
errorLog("$reorder_file :".FILE_NOT_FOUND);
$error = true;
$reorder_file = "";
}
if($reorder_file!= "")
{
$wishlistbuttonhtml="YOUR PASSWORD WHICH YOU WANT TO REPLACE"
$somecontent = $wishlistbuttonhtml;
$Handle = fopen($reorder_file, 'c+');
$bodytag = file_get_contents($reorder_file);
$str=$bodytag;
$pattern = '/(YOUR_REGEX_WILL_GO_HERE_FOR_REPLACING_PWD)/i';
$replacement = $somecontent;
$content = preg_replace($pattern, $replacement, $str,-1, $count);
fwrite($Handle, $content);
fclose($Handle);
}
Hope this helps....
The proper way of doing this is to use a database instead. Databases can do random access easily, doing it with text files less so.
If you can't switch to a database for whatever reason, and you don't expect to have more than about a thousand users for your system, then it would be far simpler to just read the whole file in, convert it to a PHP data structure, make the changes you need to make, convert it back into text and overwrite the original file.
In this case, that would mean file() to load the text file into an array with each element being a username and password as a string, explode all elements on the array at the comma to get the username and password separately, make the changes you need to make, then write the modified data to disc.
You might also find fgetcsv() useful for reading the data. If you SplFileObject and have a recent version of PHP then fputcsv() may also be available to write the data back out.
However, just using a database is a far better solution. Right tool for the job.
$fn = fopen("test.txt","r") or die("fail to open file");
$fp = fopen('output.txt', 'w') or die('fail to open output file');
while($row = fgets($fn))
{
$num = explode("++", $row);
$name = $num[1];
$sex = $num[2];
$blood = $num[3];
$city = $num[4];
fwrite($fp, "Name: $name\n");
fwrite($fp, "Sex: $sex\n");
fwrite($fp, "Blood: $blood\n");
fwrite($fp, "City: $city\n");
}
fclose($fn);
fclose($fp);
If you're on a *nix system you could use sed; I find it neater than playing with file handles etc:
exec("sed -i '/^$username,.\+\$/$username,$userpwd/g' ./users.txt 2>&1", $output, $return);
If not I'd agree with GordonM and parse the file into a PHP data structure, manipulate it, then put it back:
$data = file_get_contents('./users.txt');
$users = array_map(function($line) {
return explode(',', $line);
}, explode("\n", $data));
foreach ( $users as $i => $user ) {
if ( $user[0] == $username ) {
$user[1] = $userpwd;
$users[$i] = $user;
}
}
file_put_contents('./users.txt', implode("\n", array_map(function($line) {
return implode(',', $line);
}, $users)));
There are, of course, an infinite number of ways of doing that!