I have two forms on one page that should give users posibility to load file to server(from URL or from user's PC)
<form method="post" action="bigorder.php" name="photourl">
<label for="photoorig">URL</label>
<input type="url" name="photoorig" placeholder="">
<input type="submit" value="Load" name="photoload">
<br>
</form>
<form method="post" action="bigorder.php" name="photofile" enctype="multipart/form-data">
<label for="photoloc">Load own file</label>
<input type="file" name="photoloc" id="photoloc">
<input type="submit" value="Load" name="photoload2">
</form>
And php
<?php
$tmpname=rand().".jpg";
if ($_POST['photoorig']) {
$file=file_get_contents($_POST['photoorig']);
$fp = fopen("/var/www/html/uploads/tmp/".$tmpname, "w");
fwrite($fp, $file);
fclose($fp);
}
if ($_POST['photoloc']) {
$tmpFile = $_FILES['photoloc']['tmp_name'];
$newFile = "/var/www/html/uploads/tmp/".$_FILES['photoloc']['name'];
$result = move_upload_file($tmpFile, $newFile);
echo $_FILES['photoloc']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
?>
First form loads files fine, but the second one doesn't work at all. I even don't receive any error message.
What am I doing wrong? Or missing something?
Here is the correct code,it is working.In your code curly braces was missing in second form and isset() function should use to check posted data set or not.
<?php
$tmpname=rand().".jpg";
if (isset($_POST['photoload'])) {
echo '1st';
$file=file_get_contents($_POST['photoorig']);
$fp = fopen("/var/www/html/uploads/tmp/".$tmpname, "w");
fwrite($fp, $file);
fclose($fp);
}
if (isset($_POST['photoload2'])) {
echo '2nd';
$tmpFile = $_FILES['photoloc']['tmp_name'];
$newFile = "/var/www/html/uploads/tmp/".$_FILES['photoloc']['name'];
$result = move_upload_file($tmpFile, $newFile);
echo $_FILES['photoloc']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
Related
I've made this code in PHP because I want to practice file handling.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form action = "index.php" method = "get">
Do you want to make a new file (NF), edit a file (EF), or delete a file (DF)?
<input type = "text" name = "FileHandling">
<input type = "submit">
<br/>
</form>
<?php
$FileCommand = $_GET['FileHandling'];
if($FileCommand == 'NF') {
echo "<form action = 'index.php' method = 'get'><br/>";
echo "What is the new file's name?<br/>";
echo "<input type = 'text' name = 'CreateFile' method = 'get'><br/>";
echo "<input type = 'submit'><br/>";
$FileName = $_GET['CreateFile'];
echo $FileName;
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
}
?>
</body>
</html>
However, there is a problem after you choose 'NF' and type in the file name. The file does not get created:
echo $FileName;
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
}
You have a bug in the way you're handling inputs and forms. Currently, you're checking $FileCommand == 'NF', which is true on the first form submission. But then the page reloads and you get a second form with a new input. So when you fill in the second form and resubmit it, now <input name='FileHandling' /> wasn't submitted because it wasn't part of this form (it's part of the first form).
So if you change your PHP to the following, the file will be attempted to be created if $FileName !== null (regardless of the value of $FileCommand) rather than your previous logic which also required $FileCommand == 'NF'. This moves the logic for creating the file outside of the first if.
<?php
$FileCommand = $_GET['FileHandling'];
if ($FileCommand == 'NF') {
echo "<form action='index.php' method='get'><br/>";
echo "What is the new file's name?<br/>";
echo "<input type='text' name = 'CreateFile'><br/>";
echo "<input type='submit'><br/>";
echo "</form>";
}
$FileName = $_GET['CreateFile'];
if (null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
?>
Another way to handle this would be to create only a separate field instead of a completely separate form.
<html>
<body>
<form action="index.php" method="get">
Do you want to make a new file (NF), edit a file (EF), or delete a file (DF)?
<br>
<input type="text" name="FileHandling" />
<br>
<?php
$FileCommand = #$_GET['FileHandling'];
if($FileCommand == 'NF') {
echo "What is the new file's name?<br/>";
echo "<input type='text' name = 'CreateFile' /><br/>";
}
?>
<input type="submit">
</form>
<?php
$FileName = $_GET['CreateFile'];
if(null !== $FileName) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
} else {
echo "No file name chosen. ";
}
?>
</body>
</html>
When you create new form get request blocked because of page reload.
This is working code to solve your problem.
<form method="get" action="index.php">
<input type="text" name="filehandling">
<input type="submit" name="createfile">
</form>
<?php
if ( isset($_GET['createfile']) ) {
$fh = $_GET['filehandling'];
if ($fh == 'NF') {
echo '
<form method="get">
<input type="text" name="filename">
<input type="submit" name="createnewfile">
</form>
';
}
}
if ( isset($_GET['createnewfile']) ) {
$filename = $_GET['filename'];
$f = fopen($filename, "w");
fclose($f);
}
?>
Try to use is_null() PHP function to get the desired result
Change your code to
if(!is_null($FileName)) {
echo $FileName;
echo "yes";
$CreateTheFile = fopen($FileName, 'w');
}
I have little problem with php web form for add link.
I want the form to record the values in:
.$_POST['field2']
But I don't know how to do it to work correctly.
My code is...
HTML form code:
<form action="myprocessingscript.php" method="POST">
<p>Уеб Сайт: </p><input name="field1" type="text" placeholder="https://www.tvoiasait.com/" /><br />
<p>Ключова дума: </p><input name="field2" type="text" placeholder="Моят Личен Блог" /><br />
<p>Описание: </p><input name="field3" type="text" placeholder="Личен Блог за интересни неща" /><br />
<br /><input type="submit" name="submit" value="Добави сайта">
</form>
myprocessingscript.php code is:
<?php
if(isset($_POST['field1']) && isset($_POST['field2']) && isset($_POST['field3'])) {
$data = '<a href='.$_POST["field1"]' target='_blank' rel='nofollow' title='.$_POST["field3"]'>.$_POST["field2"]</a>' . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
and my code for show form records is:
<?php
$myfile = fopen("mydata.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
echo fgets($myfile);
}
fclose($myfile);
?>
I want to use this form on my website so that visitors can add their link to them. I don't understand how to use $_POST['field1'] in HTML row.
Thanks for your time and attention.
<?php echo $_POST['field2'] ?>
or
<?php
echo '<a href="' . $_POST['field1'] . '" target="_blank" rel="nofollow"
title="' . $_POST['field3'] . '"><' . $_POST['field2'] . '</a>':
?>
This below "" string addition could solve your problem.
<?php
if(isset($_POST['field1']) && isset($_POST['field2']) && isset($_POST['field3'])) {
$data = ''.$_POST["field2"].'' . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
I have a form that on submit creates a unique .txt filename and posts form data into that file. That works well. The issue is after it creates the file, I need a way to append it without creating another text file. Because it is a form, when it submits, the code reruns each time submit is called and I'm not sure how to handle it.
Here is the form:
<body>
<form action="write_to_txt_file2.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
Here is the php:
I don't have to use the microtime as the unique variable name so if there is a better way, I'm open to changing it.
<?php
$myDate = round(10*microtime(TRUE));
$filename = "tmp/".$myDate.".txt";
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
Alternatively, you could utilize sessions also to this, set the filename if not set using that same generator, so that you could use it again after the next submissions.
Simple example:
session_start();
if(!isset($_SESSION['file'])) {
$_SESSION['file'] = round(10*microtime(TRUE)); // set a filename on initial load
}
if(isset($_POST['submit'])) { // if submitted
$myDate = $_SESSION['file'];
$filename = "tmp/".$myDate.".txt";
if(isset($_POST['field1'], $_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
}
if(isset($_POST['create'])) {
$_SESSION['file'] = round(10*microtime(TRUE)); // creates another filename
}
?>
<form action="" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data" />
<input type="submit" name="create" value="Create New" />
</form>
Why can't I do a proper strpos function on an uploaded file (I first upload the file, and then do a $site = stream_get_line($f, 4096, "\n")) and it works completely fine when read the same thing into $site from a manually created file on the server.
I have no idea what's causing it... it seems to read the line well in both cases, but strpos just doesn't work the same when it's uploaded via user versus when I create it manually.
Here's the code:
<?php
if(!$_FILES){
?>
<head>
<title>Bulk Index Checker</title>
</head>
<center>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br/>
<input type="submit" value="Check 'em!" />
</form>
</center>
<?php
}
else{
echo("<center> <h1>Checking... please wait.</h1> <br><table border=1> <tr><td>Site</td><td>Indexed</td></tr>");
$target_path = "checkupload/";
$target_path = $target_path . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$f = fopen($target_path, "r") or exit("Unable to open file!");
while (!feof($f))
{
$site = stream_get_line($f, 4096, "\n");
$url = 'http://www.google.com/search?q=info:' . $site;
//sleep(3);
$contents = file_get_contents($url);
if (strpos($contents,'<h3 class="r"><a href="/url?q='.$site)!=FALSE) {
echo("<tr bgcolor=\"Silver\"><td>".$site."</td><td>YES</td></tr>");
echo("<br>");
}
else{
echo("<tr><td>".$site."</td><td>NO</td></tr>");
}
}
?>
</table>
<br/>
<form>
</center>
<?php
}
?>
Edit: Here's another way I tried (using textarea) - same thing basically - it ONLY works properly when you input only 1 URL. As soon as you input another URL below, it shows a FALSE for the first one when it's really TRUE.
WHY IS THIS HAPPENING?
<?php
if(!$_POST){
?>
<head>
<title>Bulk Index Checker</title>
</head>
<center>
<h1>Bulk Index Checker v1.0</h1>
<form method="post" enctype="multipart/form-data">
<textarea id="list" name="list" rows="10" cols="50"></textarea>
<br/>
<input type="submit" value="Check 'em!" />
</form>
</center>
<?php
}
else{
echo("<center> <h1>Checking... please wait.</h1> <br><table border=1> <tr><td>Site</td><td>Indexed</td></tr>");
$lines = explode("\n", $_POST['list']);
foreach($lines as $site) {
echo($site);
$url = 'http://www.google.com/search?q=info:' . $site;
sleep(3);
$contents = file_get_contents($url);
if (strpos($contents,'<h3 class="r"><a href="/url?q='.$site)!=FALSE) {
echo("<tr bgcolor=\"Silver\"><td>".$site."</td><td>YES</td></tr>");
echo("<br>");
}
else{
echo("<tr><td>".$site."</td><td>NO</td></tr>");
}
}
?>
</table>
<br/>
</center>
<?php
}
?>
Try to use '!==' instead of '!='.
I don't have an option to test at this stage. See http://php.net/manual/en/function.strpos.php (example #2)
I have the following HTML:
<form method="post" id="print" action="writefile.php" onsubmit="Javascript:window.print(); return true;">
<div id="non-printable">
Enter First & Last Name:
<input id="who" name="who" type="text" /><br><br>
Enter Taken Date:
<input id="tdate" readonly name="todays_date" onfocus="showCalendarControl(this);" type="text" /><br><br>
<input id="submit" type="button" class="btn" value="Submit" />
<div id="printout" style="text-align:center;display:none;">
<input type=submit value="Print Certificate" />
</div>
</div>
</form>
<div id="parent">
<h1>THIS WILL PRINT WHEN 'PRINT CERTIFICATE' IS PRESSED</h1>
</div>
The following CSS:
#media print {
#non-printable { display: none; }
#parent { display: block; }
}
What I am looking to do is when the PRINT CERTIFICATE is pressed I want to write to a file located in my server and also display the Print window as it is currently doing right now. How can I accomplish that?
I know I can use the following PHP but the incorporation is the issue:
<?php
session_start();
// Clean up the input values
foreach($_POST as $key => $value) {
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
$printfor = $_POST['who'];
$dte = $_POST['todays_date'];
$filename = "writefile.txt"; #Must CHMOD to 666, set folder to 777
if($printfor && $dte) {
$text = "\n" . str_pad($_SESSION['printlogin'], 15) . "" . str_pad($printfor, 30) . "" . str_pad($dte, 15);
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);
#echo ("File written");
}
else {
#echo ("File was not written");
}
}
?>
Append to a file:
Well, if you change your html file, you can incorporate the php into it. You can trigger that php form by making the html button part of a form. When the form submits, the action can be whateveryounamedyourphpfile.php. If you have put hidden input fields on your form (the php you have there is looking for the 'userprint' and 'date' inputs, you can have it write to the file.
The HTML:
<form id="print" method="post" action="whateveryounamedyourphpfile.php" onsubmit="Javascript:window.print(); return true;">
<input type="hidden" name="date" value="yourvaluehere" />
<input type="hidden" name="userprint" value="yourvaluehere" />
<input type="submit" value="Print Certificate" />
</form>
The PHP:
<?php
$printfor = $_post['userprint'];
$date = $_post['date'];
if($printfor && $date) {
$text = "\n" . str_pad($_SESSION['printlogin'], 10) . "" . str_pad($printfor, 25) . "" . str_pad($dte, 15);
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);
#$writeSuccess = "Yes";
#echo ("File written");
}
else {
#$writeSuccess = "No";
#echo ("File was not written");
}
}
//Echo your HTML here
?>
I created this JS Fiddle for you to get you on your way. http://jsfiddle.net/KEHtF/
It uses .ajax to submit the information to your PHP script while also invoking the print command.