Cannot view/delete file PHP - php

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>

Related

Trying to save the picture onto another folder by adding random number In front of the picture

In my website there is, 6 digit random numbers known as refno Example 20221234and there is fileupload. Right now, it saves the photos with its own name on to the another filepath examplecat.png. Currently, I tried to add that refnoin front of the picture while saving like20221234cat.png. Is that possible to do?
<?php
$refno = isset ($_GET['refno'])? $_GET['refno']:'';
$file = isset($_FILES["file"]["tmp_name"])? $_FILES["file"]["tmp_name"] : "";
$file_size = isset($_FILES["file"]["size"])? $_FILES["file"]["size"] : "";
$file_name = isset($_FILES["file"]["name"])? $_FILES["file"]["name"] : "";
if(isset($_POST['submit']))
{
$dataDir = "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/";
if ($file_size <= 0)
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('No picture attached!')";
//echo $refno;
echo "</script>";
}
else
{
if(stristr($file_name, ".png")){
$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!");
$dest = $dataDir.$file_name;
if(move_uploaded_file($file,$dest))
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('Visual Defect Report and pictures are successfully submitted!')";
//echo $refno;
echo "</script>";
}
}
else if(stristr($file_name, ".jpg")){
$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!");
$dest = $dataDir.$file_name;
if(move_uploaded_file($file,$dest))
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('Visual Defect Report and pictures are successfully submitted!')";
//echo $refno;
echo "</script>";
}
}
else if(stristr($file_name, ".jpeg")){
$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!");
$dest = $dataDir.$file_name;
if(move_uploaded_file($file,$dest))
{
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo " alert('Visual Defect Report and pictures are successfully submitted!')";
//echo $refno;
echo "</script>";
}
}
}
}
$file_name= "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/" . $refno.$file_name;
flush();
mysqli_close($conn);
?>
Below is how I get the refno.
<script type="text/javascript">
const now = new Date();
let randomNum = '';
randomNum += Math.round(Math.random() * 9);
randomNum += Math.round(Math.random() * 9);
randomNum += now.getTime().toString().slice(-2);
window.onload = function () {
document.getElementById("refno").value = `${new Date().getFullYear()}${randomNum}`;
}
</script>
<label class="control-label col-sm-4" for="refno">REF nos :</label>
<div class="col-sm-4">
<p class="form-control-static" style="margin-top: -6px;">
<input type="text" class="form-control" id="refno" name="refno" value="<?php echo $refno;?>" disabled>
</p>
</div>
<?php
if(isset($_POST['submit']))
{
$refno = isset ($_GET['refno'])? $_GET['refno']:'';
$file_tmp = isset($_FILES["file"]["tmp_name"])? $_FILES["file"]["tmp_name"] : "";
$file_size = isset($_FILES["file"]["size"])? $_FILES["file"]["size"] : "";
$file_name = isset($_FILES["file"]["name"])? $_FILES["file"]["name"] : "";
//Images Directory
$dataDir = "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/";
//New Filename
$new_filename = $dataDir.$refno.$file_name;
//File formats
$file_formats=array("jpeg","jpg","png");
//echo $file_size;
if($file_size>0){
//echo "Good";
$file_info = pathinfo($file_name);
$file_ext= $file_info['extension'];
//check the extension
if(in_array($file_ext,$file_formats))
{
//Database Connection
//$connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd, $database) or die ("Unableeeee to connect!");
if(move_uploaded_file($file_tmp, $new_filename))
{
$message="alert('Visual Defect Report and pictures are successfully submitted!')";
}
else
{
$message= " alert('Error Uploading File!')";
}
}
else
{
$message= " alert('Invalid Picture Format!')";
}
}
else
{
$message= " alert('No picture attached!')";
}
echo "<script language=\"javascript\" type=\"text/javascript\">";
echo $message;
//echo $refno;
echo "</script>";
}
?>
<?php
if(isset($_POST['saveimage']))
{
$directory="images/";
$filename =$_FILES['file']['name'];
$filename_temp =$_FILES['file']['tmp_name'];
$new_filename = $directory.date("YmdHis")."_".$filename;
if(move_uploaded_file($filename_temp,$new_filename))
{
echo "File Uploaded ";
}
else
{
echo "File Upload Error.";
}
}
echo "<hr/>";
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']?>" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="saveimage" value="save" />
</form>

File not being created in PHP?

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');
}

Undefined index: extension in C:\xampp\htdocs\login.php on line 77

I am trying to make a file upload for my website, and it has been working for the past few weeks now until today when i tried to change the upload directory. Now it says Undefined index: extension so i tried changing it back but it still says it. My code is here:
login.php
<!DOCTYPE html>
<head>
<style>
</style>
<body>
<?php
session_start();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
?>
<div class="container">
<?php
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
include 'user.php';
$user = new User();
$conditions['where'] = array(
'id' => $sessData['userID'],
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
?>
<h2>Welcome <?php echo $userData['first_name']; ?>!</h2>
Logout
<div class="regisFrm">
<p><b>Username: </b><?php echo $userData['username']; ?></p>
<p><b>Name: </b><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p>
<p><b>Email: </b><?php echo $userData['email']; ?></p>
<p><b>Phone: </b><?php echo $userData['phone']; ?></p>
</div>
<?php
$user = $userData['username'];
$url = "/Users/makefile.php?uname=$user";
echo 'Your Account';
// echo 'Your Account';
?>
<form action="upload.php?user=$user" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<br>
<input type="submit" value="Upload">
</form>
<?php
$dir_path = "uploads/";
$extensions_array = array('jpg','png','jpeg','PNG','mp3','MP3','mp4','MP4');
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
{
// get file name
// echo "File Name -> $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
// echo "File Extension-> $extension<br>";
$filephp = $files[$i] . '.php';
$filetxt = $files[$i] . '.txt';
$fileimg = $files[$i] . '.jpg';
$filetxtu = $files[$i] . 'uploaded' . '.txt';
// check file extension
if(in_array($extension, $extensions_array))
{
// show image
echo "<center><a href='$filephp?txt=$filetxt&img=$files[$i]&php=$filephp&user=$user&txtu=$filetxtu' target='_blank'>
<img src='$dir_path$files[$i]' style='width:300px;height:300px;align:left;'><br></a>
</center>";
}
}
}
}
?>
<?php }else{ ?>
<h2>Login to Your Account</h2>
<?php echo !empty($statusMsg)?'<p class="'.$statusMsgType.'">'.$statusMsg.'</p>':''; ?>
<div class="regisFrm">
<form action="userAccount.php?uimg=$" method="post">
<input type="email" name="email" placeholder="EMAIL" required="">
<input type="password" name="password" placeholder="PASSWORD" required="">
<div class="send-button">
<input type="submit" name="loginSubmit" value="LOGIN">
</div>
</form>
<p>Don't have an account? Register</p>
<p>Go back home Here</p>
</div>
<?php } ?>
</div>
upload.php
<?php
$uname = $_GET['user'];
define("UPLOAD_DIR", "/uploads");
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$nametxt = $name . ".txt";
$namephp = $name . ".php";
$nametxtu = $name . "uploaded" . ".php";
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
$content = " ";
$fp = fopen($nametxt, "wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}
$text = file_get_contents('comments.php');
$paste = file_put_contents($namephp, $text);
if($paste)
{
echo "File copied correctly\n";
} else {
echo "There was a problem copying the file\n";
}
$file = fopen($nametxtu,"w");
echo fwrite($file, $uname);
fclose($file);
header("Location: login.php");
die();
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
header("Location: uploadyourown.php");
die();
}
Check that upload directory has only files you uploaded, may be directory contains empty file, and be sure all files you uploaded have extensions

uploading files in php using xampp

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;
}
}
}

Images Not Displaying

All I want is that the images are displayed nothing else please.
I have been working on a different script but have the same problem.
I images are deleted but not displayed.
My code is:
<?php
// directory separator
defined("DS")
|| define("DS", DIRECTORY_SEPARATOR);
// root path
defined("ROOT_PATH")
|| define("ROOT_PATH", realpath(dirname(__FILE__)));
// upload folder directory
defined("UPLOAD_DIR")
|| define("UPLOAD_DIR", "../imagefolder");
// path to the upload folder
defined("UPLOAD_PATH")
|| define("UPLOAD_PATH", ROOT_PATH.DS.UPLOAD_DIR);
function getAllFiles($folder = null) {
if(!empty($folder) && is_dir($folder)) {
if($handle = opendir($folder)) {
$out = array();
while($file = readdir($handle)) {
if(is_file($folder.DS.$file)) {
$out[] = $file;
}
}
closedir($handle);
return $out;
}
return false;
}
return false;
}
$files = getAllFiles(UPLOAD_PATH);
if (!empty($_POST['file'])) {
foreach($_POST['file'] as $file) {
unlink(UPLOAD_PATH.DS.$file) or die("Failed to <strong class='highlight'>delete</strong> file");
}
header("location: " . $_SERVER['REQUEST_URI']);
}
?>
<?php if (!empty($files)) { ?>
<form name="form1" method="post">
<?php foreach($files as $key => $file) { ?>
<label for="file_<?php echo $key; ?>">
<input type="checkbox" name="file[]" id="file_<?php echo $key; ?>" value="<?php echo $file; ?>" />
<?php echo UPLOAD_DIR.DS.$file; ?>
</label>
<?php } ?>
<input type="submit" name="delete" value="Delete" />
</form>
<?php } ?>
The question is not clear to me but it appears you want to display the images in the form (beside each "delete" checkbox) so the user can see what they are deleting?
If so, can you try changing
<?php echo UPLOAD_DIR.DS.$file; ?>
to
<img src=<?php echo UPLOAD_DIR.DS.$file; ?> />

Categories