I'm trying to create an idea that I thought of.
I thought to create a page where you write in an HTML form your FTP server, username, password, folder and choose an option from a dropdown menu and then itll upload certain files to that folder,
Currently I'm having some issues [ maybe cuz I never got to finish learning PHP, I just can't sit infront of a PC and study something , idk why ]
I do know some basis and I read in PHP Documentary.
My current code: [ HTML ]
<form name="ftpupload" action="" method="post">
Server: <input type="text" name="server" ><br>
Username: <input type="text" name="user"><br>
Password: <input type="password" name="pass"><br>
Folder: <input type="folder" name="folder"><br>
System: <select name ="sys"><br>
<option value="check">Check</option>
<option value="2ndcheck">2nd Check</option>
</select><br>
<input type="submit" value="Submit">
</form>
PHP:
$ftpServer = $_POST['server'];
$ftpUser = $_POST['user'];
$ftpPass = $_POST['pass'];
$ftpFolder = $_POST['folder'];
$ftpSys = $_POST['sys'];
if($ftpSys == 'check') { $fileName = "test.txt"; $remoteFile ="2ndindex.txt"; }
elseif($ftpSys =='2ndcheck') { $fileName = "2ndtest.txt"; $remoteFile ="2ndindex.txt"; }
//FTP Connection
$conn = ftp_connect($ftpServer) ;
//
if (#ftp_login($conn, $ftpUser, $ftpPass)) {
//echo "Connected as $ftpUser#$ftpServer\n";
?>
<div class="working">
Connected as <? echo "$ftpUser#$ftpServer" ?>
</div>
<?
ftp_put($conn, $ftpFolder, $fileName, FTP_ASCII);
} else {
?>
<div class="working">
Could not connect as <? echo "$ftpUser#$ftpServer" ?>
</div>
<?
}
Because of the limited ftp_put function, I don't know how to put the fileName and ftpFolder together, so itll put it there with that name,
after this test will work I want to get it to upload all the files and folders that are in a certain folder, is that possible?
EDIT: Oh and another small thing : How can I get the PHP acting only after the form was submitted?
Thanks in advance
This doesn't require anything special. When you log in with the user, you are assigned a certain directory that you start in. on Shared hosting packages on a linux environment.
This is generally:
/home/username/
then from there, you can choose whatever directory, like:
'/public_html/'.$ftpFolder.'/.'$fileName;
If you only want the PHP to execute after the form has been submit, then you need to perform a conditional. You can check as many or as little posted variables as you want.
if(isset($_POST['server'])):
//your logic.
endif;
If you need to know what directory you're set into by default, you can use
ftp_pwd();
which returns the present working directory for the FTP connection.
Related
I am totally new in PHP and i have problem with posting data. I try to post data and write it in txt file. I already increase my post max size in php.ini. I use XAMPP
<form action="forms/save_news.php" method="post" role="form">
<div class="form-group">
<input type="text" name="date" class="form-control" id="date" placeholder="Дата" data-rule="minlen:10" data-msg="Моля въведете дата" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="title" id="title" placeholder="Заглавние"/>
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="data" rows="5" data-rule="required" data-msg="Моля въведете съдържание" placeholder="Новина"></textarea>
<div class="validate"></div>
</div>
<div class="text-center"><button type="submit">Запиши</button></div>
</form>
And my PHP code is:
<?php
if(isset($_POST['date'])) {
$date = $_POST['date'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $date);
fclose($fp);
}
?>
My first guess would be a permission issue. What I would do to troubleshoot this is to turn on error reporting in your PHP script. Try the following code:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (isset($_POST('date')) {
$date = filter_var($$_POST['date'], FILTER_SANITIZE_STRING);
$fp = fopen('data.txt', 'a');
fwrite($fp, $date);
fclose($fp);
}
?>
Post another request from your form and see what appears in the browser. The errors that are reported should tell you where the problem is, but if you aren't positive how to fix the errors.
Now, all that said, be sure to never trust data sent from a web form. For simply testing purposes, you can do what you are doing, but I would not recommend getting into the habit since it can breed complacency. Note the change I made to the line that assigns the value of the form field to the $date variable. It uses a filter_var function to sanitize the string. There are plenty of combinations, and it is best to understand exactly how you are going to use the data, eventually to choose the correct filter(s).
You may consider an extra check. For example, if $_POST['date'] contained an empty string, it would pass isset() and would still append this to the Text file.
PHP Version is also a consideration here.
Try:
<?php
if(isset($_POST['date']) && !empty($_POST['date'])) {
$date = $_POST['date'];
if (is_writable('date.txt'){
$fp = fopen('date.txt', 'a');
if(fwrite($fp, $date) === FALSE){
echo "Cannot write to file";
exit;
}
fclose($fp);
} else {
echo "The file is not writable.";
}
}
?>
Also, this script assumes that date.txt and save_news.php reside in the same folder path. Is date.txt in forms folder? If it is not you will want to ensure that the script can reach the file and there are proper permissions for XAMPP and PHP to Read, Write to this file.
If date.txt is elsewhere, maybe in the parent, use:
$fp = fopen('../date.txt', 'a');
If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.
https://www.php.net/manual/en/function.fopen.php
PHP noob here. I'm trying to create a login file. Here's my code:
HTML:
<body>
<div class="login">
<h2 class="login-header">Log in</h2>
<form action="practice.php" method="POST" class="login-container">
<p>
<label>Username: </label>
<input type="text" id="user" name="user" placeholder="Enter Username" required/>
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass" placeholder="Enter Password" required/>
</p>
<p>
<input type="submit" id="btn" value="Login" />
</p>
</form>
</div>
PHP:
<?php
$usernameIn = $_POST['user'];
$passwordIn = $_POST['pass'];
$usernameIn = stripcslashes($usernameIn);
$passwordIn = stripcslashes($passwordIn);
$usernameIn = mysql_real_escape_string($usernameIn);
$passwordIn = mysql_real_escape_string($passwordIn);
$host = 'localhost';
$user = 'root';
$password = '';
$db ='practice';
$connection = mysqli_connect($host,$user,$password,$db);// you can select db separately as you did already
if($connection){
$ret = mysqli_query($connection,"SELECT `userName`, `password`, `clearacne` FROM
`users_table` WHERE `userName`='$usernameIn' AND `password`='$passwordIn'");
global $to_encode = array();
while($row = mysqli_fetch_assoc($ret)) {
$to_encode[] = $row;
}
//user doesn't exist redirect to error page
if(empty($to_encode)) header("Location: http://localhost/practiceLogin/loginErrorIndex.html");
//user exist continue
else{
$to_encode = json_encode($to_encode);
header("Location: http://localhost/practiceLogin/loginOkIndex.php");
}
}else{
echo "db connection error because of".mysqli_connect_error();
}
?>
Two questions:
1)Is there a way to process the info the user puts in and redirect him to a new file ONLY if the info exists in the database?
2)How can I pass the variable $to_encode from the practice.php to other .php files without including/requiring the practice.php file?
Basically what I'm trying to do is to not allow access if the user isn't registered, and if he is then allow access to another file and use a JSON object that represents different parameters associated with the user.
Thank you!
First question: You are already making redirects:
header("Location: http://localhost/practiceLogin/loginOkIndex.php");
Second question: Yes, there is a way. It is called session. You can read more here: http://php.net/manual/en/book.session.php
The basic explanation - once you check if username/password match you start a session, put some temp variables in it, a file has been written in your server's HDD and a cookie has been sent to your user's browser. Next time the user sends request to some of your pages, you check for the cookie, check if session is still active an not expired and you can get your temp variables from the session's file.
The heavy stuff is already written and automated. Just put some time on reading the link I gave you and also I am sure you will find many example resources over the Internet.
I am using the following script to edit text based files on my server (TXT,HTML,PHP,etc..)
<?php
$filename = "test.php";
function make_content_file($filename,$content,$opentype="w")
{
$fp_file = fopen($filename, $opentype);
fputs($fp_file, $content);
fclose($fp_file);
}
if($_POST)
{
$newcontents=$_POST[newcontents];
make_content_file($filename,$newcontents);
}
$filecontents = file_get_contents($filename);
?>
<?php
if($_POST)
{
echo '<p><span style="font-weight: 700; background-color: #CCFFCC">You have successfully posted to your txt file!</span></p>
Download';
}
?>
<form method="post">
<textarea name="newcontents" cols="70" rows="25"><?=$filecontents?></textarea>
<br>
<input type="submit" value="Save">
</form>
The script works fine with most of PHP files Example:
But if a file includes some form with textarea the code just get messed up
Example:
Another Example: http://i.imgur.com/P9O34Y8.png
Would like to know why this happen and how to fix it, Thanks
The first comment sums it all
Fun fact: I have a similar tool myself, with the ability to edit files from a bookmark, an emptying files feature, and sha1 password protection. (insecure crc32 is still used in the original code)
Hope it's actually useful
if (sha1($_POST['pass']) != $pass) {
echo "<style>input{padding:0.1em; font-size:1.1em}body{background:$bg; color:$fg; font-family:corbel;font-size:1.4vw;padding:0.4em}a{color:$fg}</style><body><h2>$nick<mark>:)</mark></h2>";
echo '
<form action="writer.php" method="post">
Code: <input type="password" name="pass" autofocus>
<input type="hidden" name="f" value="'.$_GET['f'].'"><br><br>';
if ($_POST['pass'] != ""){
echo 'Incorrect code.';
}
}
https://pastebin.com/krMrA783
To empty a file, type "empty".
To set the password before using, go through the first 5 lines of code, and modify $pass.
Make sure that the password is secure and unique (14+ characters)
I write the php to upload file and scan the directory to show them as links, the scaning directoy works well I can see the text files I created in the directory, but I just can not move the local file to the desired directory .No file shows up after execution.
I think the problem may contain in this line:
move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/BlueTapeLogin/upload".$_FILES["file"]["name"]);
What I really want is to upload the image to the directory in /var/www/BlueTapeLogin/upload
and my php file lives in /var/www/BlueTapeLogin/upload_image.php
How can I change the code to make things work? Thanks in advance.
Please see my full code:
<html>
<head>
<?php
try
{
if (!empty($_POST["delete"])){
$delete=$_POST["delete"];
echo"we have the command delete this file:";
echo $delete;
$file = "upload/".$delete;
echo "/n***************";
echo "you want delete :";
echo $file;
echo "***************";
if (!unlink($file))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $file");
}
}else{}
}catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>
<?php
move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/BlueTapeLogin/upload".$_FILES["file"]["name"]);
?>
<?php
$dir=scandir("/var/www/BlueTapeLogin/upload") ;
for($j=0;$j<count($dir);$j++){
echo $dir[$j];
echo"\n";
$target = $dir[$j]; // This is the file that already exists
$link = $dir[$j]; // This the filename that you want to link it to
echo "".$link."";
}
?>
</head>
<body>
<form action="upload_image.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit"><br>
<label for="file">Delete</label>
<input type="text" name="delete" id="delete"><br>
<input type="submit" name="submit" value="Submit">
</form>
logout
</body>
</html>
You're missing a directory separator between upload and the filename, it should be:
move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/BlueTapeLogin/upload/".$_FILES["file"]["name"]);
The permissions you show say that only root can write into that directory, and but the webserver is probably using a userid like www-user. You need to change the ownership of the directory to the webserver userid. This will have to be done by the server administrator.
More likely, there's another directory that the webserver is already allowed to write into. The server administrator should be able to tell you what directory to use.
Check user permission to upload in that directory and try to make it simple. Just simply upload a file to other directory see it is working or not than check your code go one by one step.
Check return values check whether a warning is issued
Return Values
Returns TRUE on success.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
I have developed a site for a client and he wants to be able to edit a small part of the main page in a backend type of solution. So as a solution, I want to add a very basic editor (domain.com/backend/editor.php) that when you visit it, it will have a textfield with the code and a save button. The code that it will edit will be set to a TXT file.
I would presume that such thing would be easy to code in PHP but google didn't assist me this time so I am hoping that there might be someone here that would point me to the right direction. Note that I have no experience in PHP programming, only HTML and basic javascript so please be thorough in any reply that you provide.
You create a HTML form to edit the text-file's content. In case it get's submitted, you update the text-file (and redirect to the form again to prevent F5/Refresh warnings):
<?php
// configuration
$url = 'http://example.com/backend/editor.php';
$file = '/path/to/txt/file';
// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);
// redirect to form again
header(sprintf('Location: %s', $url));
printf('Moved.', htmlspecialchars($url));
exit();
}
// read the textfile
$text = file_get_contents($file);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text); ?></textarea>
<input type="submit" />
<input type="reset" />
</form>
To read the file:
<?php
$file = "pages/file.txt";
if(isset($_POST))
{
$postedHTML = $_POST['html']; // You want to make this more secure!
file_put_contents($file, $postedHTML);
}
?>
<form action="" method="post">
<?php
$content = file_get_contents($file);
echo "<textarea name='html'>" . htmlspecialchars($content) . "</textarea>";
?>
<input type="submit" value="Edit page" />
</form>
You're basically looking for a similar concept to that of a contact-form or alike.
Apply the same principles from a tutorial like this one and instead of emailing using mail check out the file functions from PHP.net.
What did you Google on then? php write file gives me a few million hits.
As in the manual for fwrite():
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
But to be honest, you should first pick up a PHP book and start trying. You have posted no single requirement, other than that you want to post a textfield (textarea I mean?) to a TXT file. This will do:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$handle = fopen("home.txt", 'w') or die("Can't open file for writing.");
fwrite($fh, $_POST['textfield']);
fclose($fh);
echo "Content saved.";
}
else
{
// Print the form
?>
<form method="post">
<textarea name="textfield"></textarea>
<input type="submit" />
</form>
<?php
}
Note that this exactly matches your description. It doesn't read the file when printing the form (so every time you want to edit the text, you have to start from scratch), it does not check the input for anything (do you want the user to be able to post HTML?), it has no security check (everyone can access it and alter the file), and in no way it reads the file for display on the page you want.
First thing to do is capture the information, the simplest way to do this would be the use of a HTML Form with a TEXTAREA:
<form method='post' action='save.php'>
<textarea name='myTextArea'></textarea>
<button type='submit'>Go</button>
</form>
On 'save.php' (or wherever) you can easily see the information sent from the form:
<?php
echo $_POST['myTextArea']
?>
To actually create a file, take a look at the fopen/fwrite commands in PHP, another simplistic example:
<?php
$handle = fopen("myFile.txt","w");
fwrite($handle,$_POST['myTextArea'];
fclose($handle);
?>
WARNING: This is an extremely simplistic answer! You will perhaps want to protect your form and your file, or do some different things.... All the above will do is write EXACTLY what was posted in the form to a file. If you want to specify different filenames, overwrite, append, check for bad content/spam etc then you'll need to do more work.
If you have an editor that is publicly accessible and publishes content to a web page then spam protection is a DEFINITE requirement or you will come to regret it!
If you aren't interested in learning PHP then you should think about getting a professional developer to take care of any coding work for you!
I had a similar need so we created a client-friendly solution called stringmanager.com we use on all our projects and places where CMS is not effective.
From your side, you just need to tag string in the code, i.e. from:
echo "Text he wants to edit";
to:
echo _t("S_Texthewantstoedit");
stringmanager.com takes care about the rest. Your client can manage that particular text area in our online application and sync wherever he wants. Almost forgot to mention, it is completely free.
Can use this line of code :
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
<?php
$file = "127.0.0.1/test.html";
$test = file_get_contents('1.jpg', 'a');
if (isset($_POST['test'])) {
file_put_contents($file, $_POST["test"]);
};
?>
<form action="" method="post">
<textarea id="test" name="test" style="width:100%; height:50%;"><? echo "$test"; ?></textarea>
<input type="submit" value="submit">
</form>
Haven't had time to finish it, simplest possible, will add more if wanted.