php save textarea to file - php

I'm trying to remake the script to save the phone configurations to the server. I have a script that generates configs and displays their name and code on the page.
It looks like this:
<br>File:112233445566.cfg<br><textarea rows="50" cols="100">#!version:1.0.0.1
#File header "#!version:1.0.0.1" can not be edited or deleted.#
account.1.enable = 1
account.1.label = 123
account.1.display_name = 123
account.1.auth_name = 123
</textarea>
<br>File:112233445566.xml<br/><textarea rows="50" cols="100"><xxxIPPhoneDirectory>
</xxxIPPhoneDirectory>
</textarea><br/>`
How do I save the information I received in textarea in two different files with different names (File:xxxxxx.xxx) in the folder on the server?
https://pastebin.com/wSrfQGCt Code of original file
https://pastebin.com/9uqkRPmv Result page in html

Try submitting the form with textarea and then:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['name_you_give_to_first_textarea']) && isset($_POST['name_you_give_to_second_textarea'])){
#First file
$handler = fopen('path/to/folder/file1.txt', 'w+'); #this creates the file if it doesn't exist
$file1 = fwrite($handler, $_POST['name_you_give_to_first_textarea']);
fclose($handler);
#Second file
$handler = fopen('path/to/folder/file2.txt', 'w+'); #this creates the file if it doesn't exist
$file2 = fwrite($handler, $_POST['name_you_give_to_second_textarea']);
fclose($handler);
}
}

Related

Converting files to binary code using php and saving it in database

I am creating something like google drive or some cloud using PHP and HTML where you can save your files but i have problem with saving files to binary code and uploading it to database. I mean i want to do something like that:
User is uploading file by form in html -> converting file to binary -> saving it in database.
User can download his file by some button or smh like that -> file is converting from binary to file.
I tried with doing a script what will save bin code in my database but when i am trying to send some files i am getting error like that:
Fatal error: Uncaught TypeError: fopen(): Argument #1 ($filename) must be of type string, array given in C:\xampp\htdocs\fileshub\src\send_file.php:12 Stack trace: #0 C:\xampp\htdocs\fileshub\src\send_file.php(12): fopen(Array, 'rb') #1 {main} thrown in C:\xampp\htdocs\fileshub\src\send_file.php on line 12
This is my form in html:
<form class="upload-form" action="./src/send_file.php" method="post" enctype="multipart/form-data"><br>
<input type="text" name="filename" id="filename" placeholder="File name">
<input type="file" name="file" id="file"><br>
<button type="sumbit" class="submit">Submit</button>
</form>
And this is my script in php:
<?php
session_start();
include "../src/db_conn.php";
if(isset($_SESSION['id'])) {
$id = $_SESSION['id']; // id usera
$filename = $_POST['filename']; // nazwa pliku
$file = $_FILES['file'];
$data = fopen ($file, 'rb');
$size = filesize ($file);
$contents = fread ($data, $size);
fclose ($data);
$binfile = base64_encode($contents);
if(!$filename|| !$file) {
header("Location: ../index.php?error=Enter your data!");
exit();
} else {
$check = "SELECT bin_code FROM files WHERE user_id = '$id' AND bin_code = '$binfile' AND file_name = '$filename'";
$result = mysqli_query($conn, $check);
if(mysqli_num_rows($result) === 1){
header("Location: ../index.php?error=Your file exsist.");
exit();
}else {
$save = "INSERT INTO files (user_id, file_name, bin_code) values('$id', '$filename', $binfile)";
$saveresult = mysqli_query($conn, $save);
$saveresult;
header("Location: ../index.php?error=Your file has been saved");
exit();
}
}
}
?>
db_conn:
<?php
$server = "localhost";
$user ="root";
$password = "";
$db = "fileshub";
$conn = mysqli_connect($server, $user, $password, $db);
?>
If you know any solutions for my problem please help :)
Files table
Users table and example user
I believe you know that uploading an image to a directory is a more efficient way to store it.
Please note that $_FILES['file'] is an array containing all sorts of information of the uploaded file, for your case you have to use the filename of the uploaded file. (which is "tmp_name")
So change
$file = $_FILES['file'];
$data = fopen ($file, 'rb');
to
$file = $_FILES['file']["tmp_name"];
$data = fopen ($file, 'rb');
On the other hand, an alternative way is to use file_get_contents instead of fopen, fread, etc.
$contents = file_get_contents($_FILES['file']["tmp_name"]);
So firstly you need to ensure you have a directory that PHP has access and has permissions on but that is not publicly accessible. Usually, on web hosts the web root folder is a sub folder of the home directory, so you can create a new folder there for file storage. Eg:
/home/myuser/public_html/ <-- might be the web root (some installations differ eg: htdocs or html or httpdocs)
/home/myuser/files/ <-- Create this folder for storing files.
Alternatively, if youre web server is Apache, you can create a folder inside your web root, and protect that folder using a .htaccess file
The easiest way then to store an uploaded file on the file server is to use the move_uploaded_file command that PHP provides, here is how I would achieve this:
$postname = 'file';
$root = '/home/myuser/files';
//cleanse the filename to prevent SQL injections when saving to DB
$filename = preg_replace("/[^a-zA-Z0-9\.]/","_",$_FILES[$postname]['name']);
$path = "$root/$filename";
//Create the files folder if it doesnt already exist...
if(!file_exists($root)) if(!mkdir($root,0775,true)) die("Failed to create root folder $root");
//Store the uploaded file in the files folder
if(!move_uploaded_file($_FILES[$postname]['tmp_name'],$path)) die('Failed to move uploaded file into asset storage');
//Store the file location in the database...
$saveresult = mysqli_query($conn,"INSERT INTO `files` (`filename`,`path`) VALUES ('$filename','$path')");

How to save file in subfolder using php

I have a script with a mysql query which saves a file called invoice.xml every day automatically by running a cron job. In case no data is found a no_orders.txt is saved.
I would like this file not be saved to the same folder as the script.php file is in but to a subfolder called invoices.
The renaming of the old invoice.xml is done with the following code
// rename old file
$nowshort = date("Y-m-d");
if(file_exists('invoice.xml')) {
rename('invoice.xml','invoice_'.$nowshort.'.xml');
}
The saving is done with the following code:
if($xml1 !='') {
$File = "invoice.xml";
$Handle = fopen($File, 'w');
fwrite($Handle, $xml1);
print "Data Written - ".$nowMysql;
fclose($Handle);
#print $xml;
die();
} else {
print "No new orders - ".$nowMysql;
$File = "no_orders_".$nowshort.".txt";
$Handle = fopen($File, 'w');
fclose($Handle);
die();
}
Could I please get assistance how to save this file to a subfolder. Also the renaming of the existing file would need to be within the subfolder then. I have already tried with possibilities like ../invoice/invoice.xml but unfortunately without any success.
Thank you
Just give the path of file 'invoice.xml' to $File.
Otherwise create some $Dir object which will point to Folder named 'invoice', then use accordingly
Use __DIR__ magic constant to retrieve your script.php directory, then you can append /invoice/invoice.xml .
Example if path to your script php something like this:
/var/www/path/to/script.php
$currentDir = __DIR__; //this wil return /var/www/path/to
$invoicePath = $currentDir.'/invoice/invoice.xml';

PHP Input & file_get_contents

Can someone explain me why when i POST RAW Data for example "test.txt" in the below script
<?php
echo file_get_contents("php://input");
?>
it only prints the text "test.txt" instead of the file contents of that file?
Thank you
Your code reads the contents of the raw POST data and echoes it back.
Whereas what you want is this:
// retrieve the requested filename
$fileName = file_get_contents("php://input");
// echo the contents of the requested file
echo file_get_contents($fileName);
Depending on what you're trying to, you may wish to sanitize the $fileName input (not shown: too broad) and restrict access to a specific local directory:
$path = $myLocalDirectory . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($path) {
echo file_get_conents($path);
}
Try like this ..
$input = "abc.txt";
echo file_get_contents($input);
It gives the content of the text file abc.txt

using a text file to determine subdomain includes php

Ok i have 2 files - index.php that has and if statement that is as follows:
$sub = array_shift(explode(".",$_SERVER['HTTP_HOST']));
if ($sub == 'localhost') include 'home.php';
if ($sub == 'whateversubdomain') include 'correspondingphpfile .php';
I also have a text file that has:
subdomain = subdomain.php
nextsub = nextsub.php
.... and so on
The question being how would I make it so that when I add a new line to the text file say nextsub, and someone visits nextsub.sitename.com that they are directed to the correct php file.
I was thinking of opening the text file and creating a variable in the index.php file then saying if $sub == $newVar include $subName . .php .
is this possible - something like -
//open file
$fp = #fopen ($some_file, "r");
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$this_line = fgets($fp);
array_push($some_array,$this_line);
}
//close file
fclose($fp);
}
(you have to handle non-existing manually)
For example, a directory "subdomains":
$sub = array_shift(explode(".",$_SERVER['HTTP_HOST']));
include 'subdomains/'.basename($sub).'.php';
I don't know, what's the point in additional writing into file.
If you are insisting on having subdomains with pages that don’t have an easy to parse name scheme the best bet is the following:
// Create an array that maps subdomains to pages.
$sub_page_map = array();
$sub_page_map['localhost'] = 'home.php';
$sub_page_map['whateversubdomain'] = 'correspondingphpfile.php';
// Get the subdomain.
$sub = array_shift(explode(".",$_SERVER['HTTP_HOST']));
// If the `$sub` exists in `$sub_page_map` then include the corresponding file.
if (array_key_exists($sub, $sub_page_map)) {
include $sub_page_map[$sub];
}
else {
include 'default.php';
}
If you want to store it in an external text file, just adapt your file parsing code to generate the values in $sub_page_map. But to me the biggest flaw in your setup is the lack of a default page, which is why I included an else to load a proposed `default.php.

How to give a .php file unique name at top of page, and display unique name on index.php file

I have a question and it's probably a simple one. What I would like to do is be able to place a unique name at the top of each .php file in a folder in the php code area. I would then like a script on the index.php file to look in that folder, pull out the unique names of each .php file found at the top of each page in the php code, and display them in a list on the index.php page.
Would I have to do something like this at the top of the page:
< ?
{{{{{uniquenamehere}}}}}
? >
And If so, what would the code look like for grabbing uniquenamehere and displaying in on the index.php page?
Thanks in advance, let me know if I need to be any more clear in my question. Sorry if it's a really simple question, I'm stumped!
EDIT
Getting this warning when using answer below:
Warning: file_get_contents(test.php) [function.file-get-contents]: failed to open stream: No such file or directory in /path/index.php
Here's the code I am using,
<?php
// Scan directory for files
$dir = "path/";
$files = scandir($dir);
// Iterate through the list of files
foreach($files as $file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] === "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrence of opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrence of ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}
?>
Not tested, but it should be roughly something like this.
<?php
// Scan directory for files
$fileInfo = pathinfo(__FILE__);
$dir = $fileInfo['dirname'];
$files = scandir($dir);
// Iterate through the list of files
foreach($files as file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] == "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrenceof opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrenceof ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}

Categories