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');
}
Related
I need to upload an image and add it to my slideshow and give it related newsTitle in front of my uploaded picture. I'm a new in PHP and trying to learn how to send data from my admin.php file to my index.php file and add more image with a <form> in html.
My problem is that I can upload images but can't get my newsTitle printed to my home page which is index.php.
This is my PHP code in index.php:
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
$newsImage = $_POST['newsImage'];
echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
echo'<h2'.'>'.htmlspecialchars($newsImage["newsImage"]).'</h2>';
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
This is my html code in admin.php:
<form action="index.php" method="post" enctype="multipart/form-data">
<br><br>
<tr>
<td> NewsTitle: </td>
<td> <input type="text" name="newsTitle" placeholder="newsTitle"> </td>
</tr>
<br><br>
Select image to upload:
<input type="file" name="image">
<br><br>
<br><br>
NewsText: <textarea name="newsImage" placeholder="newsImage" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" value="Send" name="send_object">
</form>
I'm trying to do this without connection to the database, just to my apache server. I have tried with another global variable $_REQUEST but it didn't work. What I know it can use for $_POST , $_GET and $_COOKIES
Firstly, if you are trying to make each news with a text you collect it separately with the $_POST , but note once you refresh the page the parameters are gone cause the form processes everything so there is no space for output in text but if you use the get the parameters remain because you are not storing both the post method and get method in the database. Try this
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
<?php
$newsImage = $_POST['newsImage'];
//this would give a parse error echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
try
echo <?php echo $newsimage; ?>
?>
I have a problem in uploading files using php in XAMPP
my code is:
include 'header.html';
include 'header.php';
include 'debugging.php';
echo '<br />';
echo '<h1> Upload files</h>';
echo <<<_END
<br/>
<form method='post' action='FileUpload.php' enctype='multipart/form-data'>
Select File: <input type='file' name='filename' size='100' />
<input type='submit' value='Upload' />
<input type='hidden' name='submitted' value='1' />
</form>
<br/>
_END;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (isset($_POST['submitted'])) {
if ($_FILES && $_FILES['filename']['name']) {
$file_info = pathinfo($_FILES['filename']['name']);
$extension = $file_info['extension'];
include 'DO_Files.php';
$valid = DO_File::validExtension($extension);
echo '1';
if ($valid) {
echo '2';
$tmpName = $_FILES['filename']['tmp_name'];
$name = "Files//" . $_FILES['filename']['name'];
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $name)) {
echo '3';
echo "<p>there was an error..</p>";
echo error_get_last();
} else {
echo '4';
$file = new DO_File();
$file->FileName = $name;
$file->FileSize = $_FILES['filename']['size'];
if ($file->save()) {
echo '5';
echo $file->FileName;
} else {
echo '6';
mysqli_error($file->dbc);
}
}
} else {
echo '7';
echo '<p>the file is not prompted</p>';}
} else {
echo '8';
echo 'no filee';
}
}
include 'footer.html';
I don't know why it doesn't upload. it works in remote server but with local server like XAMPP it shows an error on
if (!move_uploaded_file($_FILES['filename']['tmp_name'], $name)) {
any help? because I didn't figure put how to upload files to loacl server
I made a directory and the permissions are fine.
if (is_array($_FILES['filename']) && $_FILES['filename']['error'] == 0) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$sourcePath = $_FILES['filename']['tmp_name'];
$targetPath = "Files//" . $_FILES['filename']['name'];
if (!is_dir('Files//')) {
mkdir('Files/', 0777, true);
}
if (move_uploaded_file($sourcePath, $targetPath)) {
echo $targetPath;
}
}
}
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 />';
}
}
?>
This code is meant to either display or delete a file that has been selected in a dropdown box on the previous page. There are two radio buttons with either "view" or "delete". View has the value of 1. The error reporter just display that there is no file available, even though there is. Can anyone spot an error in my code? Are there possible the syntax anywhere? Many thanks.
<?php
// error handling function
function myErrorHandler($errno, $errstr) {
echo "<b>Error: </b> [$errno] $errstr";
echo "<br>";
echo "End scripting";
error_log("Error: [$errno] $errstr", 3, "error.log");
die();
}
// set error handler
set_error_handler("myErrorHandler");
$option = $_POST['option'];
$filename = $_POST['filename'];
if (file_exists($filename)) {
if ($option == "1") {
$file = fopen($filename, "r");
$line = "";
while (!feof($file)) {
$line .= fgets($file,1024). "<br>";
}
fclose($file);
}
else {
unlink($filename)
or die ("Cannot delete your file");
$line = $filename. " deleted";
}
}
else { trigger_error(date("h:i:sa")." -> "."no file exists...\n");}
?>
<html>
<head><title>RCM Site</title></head>
<div align = center>
<body background="bg.jpg">
<body>
<div class = "rcmsite">RCM Site</div>
<div class = "centre">
<?php echo $line; ?>
</div>
<p> Go Back</p>
</body>
</html>
here is the filunlink.php page (previous page):
<?php
$file_list ="";
$path = "/var/www/rcm/";
$show = array('.txt');
$dir = opendir($path);
while (false != ($file = readdir($dir))) {
$ext=substr($file,-4,4);
if(in_array($ext, $show)){
if (($file != ".") && ($file != "..")) {
$file_list .= "<option value = \"rcm/$file\">Go To $file</option>";
}
}
}
closedir($dir);
?>
<html><head><title>File viewer</title></head>
<div align = center>
<body background="bg.jpg">
<h3><i>File View</i></h3>
<i>Select a file to view:</i> <br>
<form action = "fileunlink.php" method = "post">
Files in <?php echo($path); ?>
<select name = "filename">
<?php echo ($file_list); ?>
</select>
<br><br>
<input type = "radio" name = "option" value = "1">View
<input type = "radio" name = "option" value = "2">Delete<br><br>
<input type = "submit" value = "Submit this form">
<p> Go Back</p>
</form>
</body>
</html>
You could try specifying the path in the first block of code so that it reads:
<?php
// error handling function
function myErrorHandler($errno, $errstr) {
echo "<b>Error: </b> [$errno] $errstr";
echo "<br>";
echo "End scripting";
error_log("Error: [$errno] $errstr", 3, "error.log");
die();
}
// set error handler
set_error_handler("myErrorHandler");
$option = $_POST['option'];
$filename = $_POST['filename'];
$path = "/var/www/rcm/";
if (file_exists($path.$filename)) {
if ($option == "1") {
$file = fopen($path.$filename, "r");
$line = "";
while (!feof($file)) {
$line .= fgets($file,1024). "<br>";
}
fclose($file);
}
else {
unlink($path.$filename)
or die ("Cannot delete your file");
$line = $filename. " deleted";
}
}
else { trigger_error(date("h:i:sa")." -> "."no file exists...\n");}
?>
<html>
<head><title>RCM Site</title></head>
<div align = center>
<body background="bg.jpg">
<body>
<div class = "rcmsite">RCM Site</div>
<div class = "centre">
<?php echo $line; ?>
</div>
<p> Go Back</p>
</body>
</html>
Ok here is what I have going on.
I am listing the contest of a directory so I can edit and delete files.
The code I am using to do that is below (Other then editing as it does not work).
<?php
$directory = ("enctlfiles/");
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) != false) {
$files[] = $file;
}
closedir($dir);
sort($files);
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>File Name</TH><th>Modified Date</th><th>Entries In File</th><th>Delete | Edit</th></TR>\n");
foreach ($files as $file)
{
if (strpos($file, '.jpg',1)||strpos($file, '.ctl',1) ){
echo "<TR><TD><a href=$directory$file>$file</a></td>";
echo "<td>";
echo date("F d Y H:i:s",filemtime($directory. $file));
echo "<td>";
echo count(file($directory. $file));
echo "<td>";
echo "<a href=enctlfiles/dodelete.php?file=$file>Delete</a> | <a href=enctlfiles/editfile.php?file=$file>Edit</a>";
}
}
?>
That lists all of the files in order in a nice pretty table. The delete function works. The edit one not so much . It is due to me not knowing what I am doing I am sure of it.
Here is the contents of the editfile.php
<form action="edit.php" method="post">
<TEXTAREA NAME="save" COLS=150 ROWS=50 wrap="off">
<?php
$dir = ".";
include($dir. '/' .$_GET['file']);
?>
</textarea>
<P><INPUT TYPE="SUBMIT" VALUE="Update File"><INPUT TYPE="RESET">
</FORM>
That populates the textarea with the file contents when you click on the "Edit" link. I don't know if that is the right way to get the data in there to be able to edit the file.
Here is the contents of the edit.php file:
<?php
//I have tried this but it give me that Unable to open file.
//$org = ($_GET['file']) or exit("Unable to open file!");
//This returns me to the prodsh.php page but does not edit the file.
$org = $_POST['save'] or exit("Unable to open file!");
$copy = $org . date("-m-d-Y-His");
copy($org,$copy);
$f = fopen($org, 'w');
fwrite($f, $_POST['save']);
fclose($f);
header('Location: http://somesite.com/GroveTuckey/itemsetup/prodsh.php');
?>
I think the editfile.php and the edit.php file are jacked up but don't know where.
I am trying to learn this and this site has been very helpful when I get stumped on something so I thank you in advance for the help given.
Also I know the danger of editing files via a webpage. This is not public or on a server that is accessible by the world. Right now I don't want to deal with a database.
I have edited files using the below code:
<form action="doedit.php" method="post">
<TEXTAREA NAME="save" COLS=150 ROWS=50 wrap="off">
<?php
include('somefile.ctl');
?>
</textarea>
<P><INPUT TYPE="SUBMIT" VALUE="Update File"><INPUT TYPE="RESET">
</FORM>
With the contents of doedit.php being:
<?php
$org = 'Somefile.ctl';// This is the name of the file in the form above
$copy = $org . date("-m-d-Y-His");
copy($org,$copy);
$f = fopen('somefile.ctl', 'w');//This is the name of said file also.
fwrite($f, $_POST['save']);
fclose($f);
header('Location: http://somesite.com/GroveTickey/editfile.php');
?>
But since the names of the files can be anything I can't put specific names in the script.
This works great other then having to hardcode file names.
You aren't passing the name of the file back to edit.php. Set the form's action to edit.php?file=<?php echo $_GET['file']; ?>.
El codigo para editar lo hice asi:
---Inicio
<? php
$filename = isset($_GET['file']) ? $_GET['file'] : '';
$directory = ("C:\\Linux\\www\\contenido\\"); // Restrict to this directory...
$fn = $directory . $filename;
if (isset($_POST['content']))
{
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
<textarea rows="25" cols="100" name="content"><?php readfile($fn); ?></textarea>
<hr />
<input type="submit" value="Guardar">
</form>
back to list
And work great