PHP create and write form - php

I have a form with two fields. The first textbox the users enter information into is what I would like to name the file that is being saved, and the second textarea is for what I would like written into the file. I am able to write to a file I have already created using php coding below which I did simply to test the function:
<?php
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST CodeDescription';
// Get current working directory
echo getcwd();
// This should output /home/revo/public_html/evo/users
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( is_file( $FILENAME ) ):
// Open the text file
$f = fopen($FILENAME, "w");
// Write text
file_put_contents($FILENAME, $_POST['Code']);
// Close the text file
fclose($f);
// Open file for reading, and read the line
$f = fopen($FILENAME, "r");
else:
echo 'Filename already exists';
endif;
?>
However I am unsure how to check to see if a file with the name they enter into the first box exists, and then if not create it, then write the information from the second box into the file.

<?php
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// Get current working directoty
//echo getcwd(); // Debugging output
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)) mkdir($USER_DIRECTORY);
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
//echo $FILENAME; // Debugging output
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
// Use file_get_contents() to read the file.
// $read_contents = file_get_contents($FILENAME);
else:
echo 'Filename already exists';
endif;
?>

you can use $_POST to get the contents of the textarea and input field.
$file_name = $_POST['filename'];
$contents = $_POST['code'];
$file = '../evo/avsave/'.$file_name . '.txt';
//writing the file
if(!file_exists($file)){
file_put_contents($file,$contents);
}else{
echo 'File exists';
}

Related

PHP editing text file on remote server not working

I have multiple sites, and have a text file on our main site with a list of domains to whitelist. I want to be able to edit this global file from each of the websites.
I have a couple of problems that I'm running into:
file_exists() and ftp_delete() are not finding the file even though it exists on the remote server.
ftp_fput() is adding a blank text file in the correct place with a zero filesize.
Here is my code:
// Check if we are updating the whitelist
if(isset($_POST['Submit'])){
// Make sure we have something to add or remove
if (isset($_POST['update']) && $_POST['update'] != '') {
// Get the text we need to add or remove
$add_or_remove_this = $_POST['update'];
eri_update_global_whitelist( $add_or_remove_this, 'add' );
// Say it was done
echo '<br>Script Completed...<br>';
}
}
echo '<form method="post">
<textarea name="update" cols="50" rows="10"></textarea><br><br>
<input name="Submit" type="submit" value="Update"/>
</form>';
function eri_update_global_whitelist( $string, $add_or_remove = 'add' ) {
// Validate the string
$domains = explode( ',', str_replace(' ', '', strtolower($string)) );
print_r($domains); // <-- WORKS AS EXPECTED
// Add invalid domains here
$invalid = [];
// Cycle
foreach ($domains as $key => $domain) {
// Check if it contains a dot
if (strpos($domain, '.') === false) {
// If not, remove it
unset($domains[$key]);
// Add it to invalid array'
$invalid[] = $domain;
}
}
print_r($domains); // <-- WORKS AS EXPECTED
// Only continue if we have domains to work with
if (!empty($domains)) {
// The whitelist filename
$filename = 'email_domain_whitelist.txt';
// File path on remote server
$file_url = 'https://example.com/eri-webtools-plugin/data/'.$filename;
// Get the file content
$file_contents = file_get_contents( $file_url );
// Only continue if we found the file
if ($file_contents) {
// Explode the old domains
$old_domains = explode( ',', str_replace(' ', '', $file_contents) );
print_r($old_domains); // <-- WORKS AS EXPECTED
// Are we adding or removing
if ($add_or_remove == 'add') {
// Merge the arrays without duplicates
$new_domains = array_unique (array_merge ($old_domains, $domains));
} else {
// Loop through them
foreach ($old_domains as $key => $old_domain) {
// Check if it matches one of the new domains
if (in_array($old_domain, $domains)) {
// If so, remove it
unset($old_domains[$key]);
}
}
// Change var
$new_domains = $old_domains;
}
print_r($new_domains); // <-- WORKS AS EXPECTED
// Include the ftp configuration file
require_once $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/eri-webtools-plugin/ftp_config.php';
// Establishing ftp connection
$ftp_connection = ftp_connect($ftp_server)
or die("<br>Could not connect to $ftp_server");
// If connected
if ( $ftp_connection ) {
// Log in to established connection with ftp username password
$login = ftp_login( $ftp_connection, $ftp_username, $ftp_userpass );
// If we are logged in
if ( $login ){
echo '<br>Logged in successfully!'; // <-- WORKS AS EXPECTED
// Make passive
ftp_pasv($ftp_connection, true);
// File path to delete
$file_to_delete = 'https://example.com/eri-webtools-plugin/data/'.$filename; // <-- NOT SURE HOW TO USE ABSOLUTE PATH ON REMOTE SERVER ??
// Delete the old file
if (file_exists($file_to_delete)) {
if (ftp_delete($ftp_connection, $file_to_delete)) {
echo '<br>Successfully deleted '.$filename;
} else {
echo '<br>There was a problem while deleting '.$filename;
}
} else {
echo '<br>File does not exist at: '.$file_to_delete; // <-- RETURNS
}
// Create a new file
$open = fopen($filename, 'r+');
// If we didn't die, let's implode it
$new_domain_string = implode(', ', $new_domains);
print_r('<br>'.$new_domain_string); // <-- WORKS AS EXPECTED
// Write to the new text file
if (fwrite( $open, $new_domain_string )) {
echo '<br>Successfully wrote to file.'; // <-- RETURNS
} else {
echo '<br>Cannot write to file.';
}
// Add the new file
if (ftp_fput($ftp_connection, '/eri-webtools-plugin/data/2'.$filename, $open, FTP_ASCII)) {
echo '<br>Successfully uploaded '.$filename; // <-- RETURNS
} else {
echo '<br>There was a problem while uploading '.$filename;
}
} else {
echo '<br>Could not login...';
}
// Close the FTP connection
if(ftp_close($ftp_connection)) {
echo '<br>Connection closed Successfully!'; // <-- RETURNS
} else {
echo '<br>Connection could not close...';
}
} else {
echo '<br>Could not connect...';
}
} else {
echo '<br>Could not find the file...';
}
} else {
echo '<br>No valid domains to add or remove...';
}
// Check for invalid domains
if (!empty($invalid)) {
echo '<br>Invalid domains found: '.implode(', ', $invalid);
}
}
Finally figured it out. I ditched ftp_fput() and replaced it with ftp_put(). Then I referred to the temporary file location on the local server instead of the fopen() like so:
ftp_put($ftp_connection, '/eri-webtools-plugin/data/'.$filename, $filename, FTP_ASCII)
So to explain what's going on (in case someone else runs into this):
// Name the temporary path and file, preferably the same name as what you want to call it.
// The path doesn't need to be specified. It just gets temporarily stored at the root and then deleted afterwards.
$filename = 'filename.txt';
// Create a new file by opening one that doesn't exist
// This will be temporarily stored on the local server as noted above
$fp = fopen($filename, 'w+');
// Write to the new file
fwrite( $fp, 'Text content in the file' );
// Add the file where you want it
ftp_put($ftp_connection, '/desination_folder/'.$filename, $filename, FTP_ASCII);
// Close the file
fclose($fp);
I ended up finding out that using ftp_put() will replace a file if it already exists, so there is no need to delete the old one like I was trying to.

trying to append bandname to mp3 upload using $_SESSION['bandname'];

Trying to append $_SESSION['bandname']; to an mp3 file upload, The concept
is when someone uploads a song it append the band name to mp3 bandname_songname.mp3 if that makes sense. here is my code so far.
the problem is with this line i think $aditionalnewFileName = $bandname.="_".$aditionofileName; this strange part is when I use the var_dump($bandname); well instead of the band name its the song I'm testing with string(88) "_police.ogg_police.ogg_police.ogg_police.ogg_police.mp3_police.mp3_police.mp3_police.wav". maybe mysqli would be more simple?
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
var_dump($_SESSION['bandname']);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution
time of this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client
//side file tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/',
'',$_FILES['song_name']['name']); // get client side file name remove
the special character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = $bandname.="_".$aditionofileName; //filename
changed with current time
if ( move_uploaded_file($aditiontmp_name,
"$uploads_dir/$aditionalnewFileName")) //Move uploadedfile
{
$uploadFile = $uploads_dir."/".$aditionalnewFileName; //Uploaded file
path
$ext = pathinfo($uploads_dir."/".$aditionalnewFileName,
PATHINFO_EXTENSION); //Get the file extesion.
$uploadFilebasename = basename($uploads_dir."/".$aditionalnewFileName,
".".$ext); //Get the basename of the file without extesion.
$exName = ".mp3";
$finalFile = $uploads_dir."/".$uploadFilebasename.$exName; //Uploaded
file name changed with extesion .mp3
$encode_cmd = "/usr/bin/ffmpeg -i $uploadFile -b:a 256000 $finalFile
2>&1"; // -i means input file -b:a means bitrate 2>&1 is use for debug
command.
exec($encode_cmd,$output); //Execute an external program.
echo "<pre>";
// will echo success , for debugging we can uncomment echo
print_r($output);
// also want to add redirect to this script to send back to profile
after upload
echo "The file was uploaded";
//echo print_r($output); // Report of command excution process.
echo "</pre>";
if($ext !== 'mp3'){ // If the uploaded file mp3 which is not remove
from uploaded directory because we need to convert in to .mp3
unlink( $uploadFile );
}
//0644 vs 0777
chmod( $finalFile, 0777 ); // Set uploaded file the permission.
}
else
{
echo "Uploading failed"; //If uploding failed.
}
?>
so after a while, I decided to go about it a different way. I used mysqli,i quarried the user name and bandname, then used the while loop used var_dump noticed bandname after staring at my code i saw i was editing the wrong line so i change $aditionofileName = preg_replace('/[^A-Za-z0-9-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); and change the line i thought was the problem to $aditionalnewFileName = "_".$aditionofileName; revmoed variable and removed the .
new code below.
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
if (isset ($_GET ['band_id']))
{ // Yes
$showband = $_GET ['band_id'];
}
else
{ // No
echo "ID not set"; // Just show the member
}
include 'connect.php';
$sql = "SELECT * from members WHERE band_id=$showband";
$result = mysqli_query ($dbhandle, $sql);
while ($row = mysqli_fetch_array ($result))
{
$username = $row ["username" ];
$bandname = $row ["bandname" ];
}
var_dump($bandname);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution time of
this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client side file
tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); // get client side file name remove the special
character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = "_".$aditionofileName; //filename changed with current
time

PHP file_exists returns false with existing files

I'm having a little problem with my PHP-code. I want to create a site which has different directories. Every directories has a file named pass (not .txt or something) with the value of the directories password. So if the pass-file doesn't exist the group will not exist. But even if the group exists it still says the group doesn't exist and I can't fopen the file either, but I can locate to it. Here's my code:
<?php
$name = $_POST['name'];
$group = $_POST['group'];
$pass = $_POST['pass'];
$filename = '/groups/' . $group . '/pass';
if(file_exists($filename)){
$handle = fopen($filename) or die("can't open file");
$hoi = fread($handle, filesize($filename));
fclose($handle);
if ($pass === $hoi){
session_start();
$_SESSION['name'] = $name;
header('Location: http://www.google.com');
}
else{
echo 'Password is wrong!';
}
}
else{
echo 'Group does not exist!';
}
?>
All POST-data is correct btw. Thanks for your help!
I think, that file pass must have ending. eg. .php or .html or something File name '/groups/' . $group . '/pass'; is wrong.
PHP function is named file_exist() and files must have endings!
If it is folder it has sometimes slash at the end. But it can be file. With .htaccess redirect, on index.html or index.php could be slash at the end of the file.

PHP - Renaming a file to disallow duplicates

So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help

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