How to hide/disable submit button? - php

I have file upload and input fields in my form..I want to hide or disable submit button for the file upload if the file is uploaded successfully...I'm really confused on how to show the error message on the same page and proceed to the 'Thank you' page if there is no error. I'm validating the file upload using php. Any Idea on how to disable submit button if the file upload succeed? or show me how to process the file upload and input fields together while showing the error message on same page for file upload...
Note I want the submit button for file upload to disappear only if the file is successfully uploaded not when the user hits submit.
<html>
<head>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Choose Photo:</label>
<input type="file" name="file" onchange="file_selected = true;">
<input type="hidden" name="submited" value="true" />
<input type="submit" name="submit" value="Submit" >
</form>
<form action="Send.php" method="post">
First Name:<input type="text" name="fname" required><br>
Last Name:<input type="text" name="lname" required><br>
Choose Username:<input type="text" name="username" required><br>
Age:<input type="text" name="age" required><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
Here is the php code which processes the file upload...I have two submit buttons one for the file upload and one for the other input fields..This php code is present on the same page with html form.
<?php
ini_set( "display_errors", 0);
if(isset($_REQUEST['submited'])) {
// your save code goes here
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "";
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo "<font color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
echo "<font color='green'><b> Success! Your photo has been uploaded.</b></font>";
}
}
}
else
{
echo "<font color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>.";
}
}
?>

I would use a Jquery AJAX call to send the data to the PHP script. Then retrieve a boolean value from the response to determine whether the button should be visible or not.

You can do it in a simple way such as.
<html>
<head>
</head>
<body>
<?php
$sub=0;
ini_set( "display_errors", 0);
if(isset($_REQUEST['submited'])) {
// your save code goes here
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "";
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo "<font color='red'><b>We are sorry, the file you trying to upload already exists.</b></font>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
$sub= 1;
echo "<font color='green'><b> Success! Your photo has been uploaded.</b></font>";
}
}
}
else
{
echo "<font color='red'><b>We are sorry, the file you trying to upload is not an image or it exceeds 2MB in size.</b></font><br><font color='blue'><i>Only images under size of 2MB are allowed</i></font>.";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Choose Photo:</label>
<input type="file" name="file" onchange="file_selected = true;">
<input type="hidden" name="submited" value="true" />
<input type="submit" name="submit" value="Submit" >
</form>
<form action="Send.php" method="post">
First Name:<input type="text" name="fname" required><br>
Last Name:<input type="text" name="lname" required><br>
Choose Username:<input type="text" name="username" required><br>
Age:<input type="text" name="age" required><br>
<?php
if($sub==0)
{
?>
<input type="submit" value="Submit" name="submit">
<?php
}
?>
</form>
</body>
</html>
I assume your code is correct. I initialised a variable $sub=0 in begining. If succesfully uploaded it is set to 1.
End, If $sub is not equal to zero, the submit is not showed.
So, if file is uploaded succesfully. The button wont show.

<form action="**somepage.php**" method="post" enctype="multipart/form-data">
<label for="file">Choose Photo:</label>
<input type="file" name="file" onchange="file_selected = true;">
<input type="hidden" name="submited" value="true" />
<input type="submit" name="submit" value="Submit" >
</form>
and from there pass variables which indicates different status back to the main page and based on the variables show the error messages.
if you really need to disable the input type file save the variables in a hidden input and getting the values on page load using Jquery and disable the input type file ....
without jquery its simple just give a condiction before the input type form
if($_GET['status']=successful)
{
<input type=file readonly="readonly" />
}
else
{
<input type=file />
}

Related

pass a text field to be a field in a linked php file in order to create a parameter

I have a form on a page which uploads a file. This form also has a 'ship_id' field to identify which record the file belongs to. Basically I need to pass the 'ship_id' field into 'upload_update.php' so that the link to 'update_ship.php' has two parameters, the name of the ship (which works perfectly well) AND the 'ship_id' which isn't working.... not sure how to achieve this.
Many thanks
Main form:
<form action="upload_update.php" method="post"
enctype="multipart/form-data">
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input name="ship_id" type="text" value="<?php echo $_GET['ship_id']; ?>" />
<input type="submit" name="submit" value="Submit">
</p>
</form>
upload_update.php file:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png"))
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Image succsefuly uploaded. " . "<br>" . "<br>";
?>
Click Hereto return to Add Ship page
<?php
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/ships/" . $_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
?>
with $_GET['ship_id'] you get the field as a GET parameter.
Then you submit it in the form as a POST parameter. So in the upload_update.php you should get it with
$_POST['ship_id']
Also you might consider sending it in the form as a hidden field:
<input name="ship_id" type="hidden" value="<?php echo $_GET['ship_id']; ?>" />

PHP file upload script not uploading

there is a little form on one page which has the code below,
<div class="postcomment">
<form id="comments" action="insertcomment.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment" id="commentfield">
<input type="submit" name="submit" value="Post comment" class="button">
<br>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Image: <input type="file" name="image" />
<br>
</div>
once the user adds the picture by browsing for it the form then goes to the insertcomment.php code which is below
$target_path = "images/";
$file_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $file_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
and for some reason it is displaying the error and not showing in the images directory, the error is: Parse error: syntax error, unexpected T_IF in /homepages/21/d417005970/htdocs/rk8479/htdocs/insertcomment.php on line 18
Try this
HTML
<div class="postcomment">
<form id="comments" action="insertcomment.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment" id="commentfield">
<br>
Image: <input type="file" name="image" />
<br>
<input type="submit" name="submit" value="Post comment" class="button">
</form>
</div>
PHP CODE (you are trying to use it on same page you can check for if(isset($_POST['submit']))
if($_FILES['image']['size'] > 0){
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["image"]["name"]));
if ((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["new_image"]["type"] == "image/png")
|| ($_FILES["image"]["type"] == "image/pjpeg"))
&& ($_FILES["image"]["size"] < 1048576)
&& in_array($extension, $allowedExts))
{
if ($_FILES["image"]["error"] > 0)
{
$error_message = $_FILES["image"]["error"];
}
else
{
if (file_exists("images/" . $_FILES["image"]["name"]))
{
$error_message = $_FILES["image"]["name"] . " " . $LANG['image_exist'];
}
else
{
if(move_uploaded_file($_FILES["image"]["tmp_name"],
"images/" . $_FILES["image"]["name"])) {
// success
$image_name = $_FILES["image"]["name"];
} else {
$error_message = "Upload Failed!";
}
}
}
}
else
{
$error_message = "Error: May be different ext or size";
}
}

PHP File upload, if left blank

I having a bit of an issue with my file upload, it works fine and everything, but I goto update my data and I want to change everything except for the image and hit submit, I get the Invalid Image message, I am not updating the images so there is no file in the file input text box, is there a way to bypass this?
if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
if ($_FILES["image"]["error"] > 0){
echo $_FILES["image"]["error"];
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
$class->update($id, $text, $image);
echo "<div style='padding-left:50px'><strong>Updated!</strong></div>";
}
}else{
echo "<div style='padding-left:50px'><strong>Invalid Image!</strong></div>";
}
What the code above does is take the file, see if its an image and if there are any errors, show them, then it moves the file into the proper folder and updates my database.
Here is the form...
<form action="CV.php?action=updatesubmit" method="post" enctype="multipart/form-data">
<input type="hidden" value="<?php echo $array['id']; ?>" name="id" />
<p>
<label for="text" style="vertical-align:top;">Text</label>
<textarea name="text" id="text" cols="70" rows="20"><?php echo $array['text']; ?></textarea>
</p>
<p>
<label for="image">Image</label>
<input type="file" name="image" id="image" value="<?php echo $array['image']; ?>" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Update" />
</p>
</form>
I hope I made sense, I have a habit of tying something out, it sounds good to me but other people wont know what I am talking about.
Played with my code and this was suggested but its not working, I'm probably doing something wrong.
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
if ($_FILES["image"]["error"] > 0){
echo $_FILES["image"]["error"];
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
}
$class->update($id, $text, $image);
echo "<div style='padding-left:50px'><strong>Updated!</strong></div>";
}
}else{
echo "<div style='padding-left:50px'><strong>Invalid Image!</strong></div>";
}
You need to check for an actual upload before you do ANYTHING ELSE with the upload data:
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
... got an upload ...
}
Just put if(isset($_FILES['image'])) around the whole block. If no image is uploaded, the file entry won't be there.
It will submit if and only if image is uploaded.
<?php
if ($_FILES["image"]["tmp_name"] && $_FILES["file"]["error"] < 0){
if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
if ($_FILES["image"]["error"] > 0){
echo $_FILES["image"]["error"];
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
$class->update($id, $text, $image);
echo "<div style='padding-left:50px'><strong>Updated!</strong></div>";
}
}else{
echo "<div style='padding-left:50px'><strong>Invalid Image!</strong></div>";
}
}
?>

PHP form not uploading file

I have a PHP form that is inserting information into a database. It all works except for the file upload. The filename needs to get placed inside the "image" column in the database table and the file needs to be put in the directory as well. Funny thing is that this uploader was working yesterday. :-S
Please can someone just review my PHP code and see if i am missing something?? Thanks so much!!
FORM CODE:
<form name="upload_announcement" method="post" action="PostAnnouncement.php">
Title: (limit 35 characters)<br />
<input type="text" name="title" maxlength="32" style="width:200px;" /><br /><br />
Message: (limit 500 html characters)<br />
<textarea name="message" cols="60" rows="20"></textarea><br /><br />
Upload Image: (Specs: .jpg format, 255px X 255px, and less than 500kb in size.)<br />
<input type="file" name="image" id="image" style="color:#fff;" />
<br /><br />
Start Date:<br />
<input name="dateStart" type="text" id="dateStartImg" />
<br /><br />
End Date:<br />
<input name="dateEnd" type="text" id="dateEndImg" />
<br /><br />
<input type="hidden" name="customerId" value="<?php echo $_COOKIE['customerId']; ?>" />
<input type="submit" name="upload" value="Upload Announcement" />
</form>`
SUBMIT CODE:<br />
`include('ConfigRead.php');
$customerId = $_COOKIE['customerId'];
$select = mysql_query('select filingName from user where customerId = '.$customerId.' limit 1') or die('Error: ' . mysql_error());
$selectRow = mysql_fetch_array( $select );
$filingName = $selectRow['filingName'];
$imageFileName = $_FILES['image']['name'];
if((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/pjpeg"))
&& ($_FILES["image"]["size"] < 500000))
{
if($_FILES["image"]["error"] > 0){
header("location:Announcements.php?file=error");
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../Admin/CustomerFiles/Announcements/" . $filingName . "/" . $imageFileName);
}
}else{
header("location:Announcements.php?file=error");
}
$sql="INSERT INTO announcements (customerId, filingName, title, message, image, dateStart, dateEnd) VALUES ('$_POST[customerId]','$filingName','$_POST[title]','$_POST[message]','$imageFileName','$_POST[dateStart]','$_POST[dateEnd]')";
if (!mysql_query($sql,$connRead))
{
die('Error: ' . mysql_error());
}
include('CloseConnRead.php');
header("location:ManageAnnouncements.php?add=success");`
Add the multipart/form-data enctype to your form when uploading files
<form name="upload_announcement" method="post" enctype="multipart/form-data" action="PostAnnouncement.php">
Do you have file_uploads enabled in your php.ini (or using ini_set)? Is the filesize larger than the upload_max_filesize configuration option in php.ini?
Look into these others, too:
max_input_time
memory_limit
max_execution_time
post_max_size

PHP can I place a global variable inside a variable sample: $names = $_FILES ["dfile"];

Trying to build a admin panel for uploading text and images here is the html page. The Html page is working fine it's the php page that is broken the html is just here for reference.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<title>Administartor Panel</title>
<head>
<link rel="stylesheet" type="text/css" href="admin.css" />
</head>
<body>
<h1>Heritage House Administartor Panel</h1>
<br/>
<h2>
Event One
Event Two
Event Three
Event Four
Event Five
Event Six
</h2>
<br/>
<table>
<tr>
<td id="eone">
<br/>
<p>Event One</P>
<p> Please name the picture file1 before uploading.</p>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="afile" id="afile" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
<form action="WriteTxt1.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for artical One:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
<tr>
<td id="etwo">
<p >Event Two</P>
<p> Please name the picture file2 before uploading.</p>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="bfile" id="bfile" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
<form action="WriteTxt2.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for artical Two:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
<tr>
<td id="ethree" >
<p >Event Three</P>
<p> Please name the picture file3 before uploading.</p>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="cfile" id="cfile" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
<form action="WriteTxt3.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for artical Three:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
<tr>
<td id="efour" >
<p >Event Four</P>
<p> Please name the picture file4 before uploading.</p>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="dfile" id="dfile" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
<form action="WriteTxt4.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for artical Four:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
<tr>
<td id="efive" >
<p >Event Five</P>
<p> Please name the picture file5 before uploading.</p>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="efile" id="efile" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
<form action="WriteTxt5.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for artical Five:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
<tr>
<td id="esix" >
<p >Event Six</P>
<p> Please name the picture file6 before uploading.</p>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="ffile" id="file6" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
<form action="WriteTxt6.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for artical Six:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
</body>
</html>
trying to rename the files uploaded based on which form they come from on the html page afile,bfile etc.
I have tried this php file a number of different ways. I can get it to work when I eliminate the large IF statement and make 6 separate files for uploading but I was hoping to make it one file
This is what I believe makes it fail moving the global variables in to normal vars?
<?php
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
//This if statement assigns the new file name to a variable and displays a message.
if (file_exists($_FILES["afile"]["tmp_name"]))
{
$new = "file1.";
$type = $_FILES ["afile"] ["type"];
$size = $_FILES ["afile"] ["size"];
$error = $_FILES ["afile"] ["error"];
$name = $_FILES ["afile"] ["name"];
$tmpname = $_FILES["afile"]["tmp_name"];
$names = "afile";
echo "file1 Uploaded <br />";
}
elseif (file_exists($_FILES["bfile"]["tmp_name"]))
{
$new = "file2.";
$type = $_FILES ["bfile"] ["type"];
$size = $_FILES ["bfile"] ["size"];
$error = $_FILES ["bfile"] ["error"];
$name = $_FILES ["bfile"] ["name"];
$tmpname = $_FILES["bfile"]["tmp_name"];
$names = "bfile";
echo "file2 Uploaded <br />";
}
elseif (file_exists($_FILES["cfile"]["tmp_name"]))
{
$new = "file3.";
$type = $_FILES ["cfile"] ["type"];
$size = $_FILES ["cfile"] ["size"];
$error = $_FILES ["cfile"] ["error"];
$name = $_FILES ["cfile"] ["name"];
$tmpname = $_FILES["cfile"]["tmp_name"];
$names = "cfile";
echo "file3 Uploaded <br />";
}
elseif (file_exists($_FILES["dfile"]["tmp_name"]))
{
$new = "file4.";
$type = $_FILES ["dfile"] ["type"];
$size = $_FILES ["dfile"] ["size"];
$error = $_FILES ["dfile"] ["error"];
$name = $_FILES ["dfile"] ["name"];
$tmpname = $_FILES["dfile"]["tmp_name"];
$names = "dfile";
echo "file4 Uploaded <br />";
}
elseif (file_exists($_FILES["efile"]["tmp_name"]))
{
$new = "file5.";
$type = $_FILES ["efile"] ["type"];
$size = $_FILES ["efile"] ["size"];
$error = $_FILES ["efile"] ["error"];
$name = $_FILES ["efile"] ["name"];
$tmpname = $_FILES["efile"]["tmp_name"];
$names = "efile";
echo "file5 Uploaded <br />";
}
elseif (file_exists($_FILES["ffile"]["tmp_name"]))
{
$new = "file6.";
$type = $_FILES ["ffile"] ["type"];
$size = $_FILES ["ffile"] ["size"];
$error = $_FILES ["ffile"] ["error"];
$name = $_FILES ["ffile"] ["name"];
$tmpname = $_FILES["ffile"]["tmp_name"];
$names = "ffile";
echo "file6 Uploaded <br />";
}
//This applies the function to our file
$ext = findexts ($_FILES ['$names'] ['name']) ;
//This assigns the subdirectory you want to save into.
$targett = "forms/upload/";
//This combines the directory, the new file name, and the extension
$target = $targett . $new.$ext;
// makes sure image meets specs
if ((($type == "image/gif")
|| ($type == "image/jpeg")
|| ($type == "image/pjpeg"))
&& ($size < 2000000))
{
if ( $error > 0)
{
echo "Return Code: " . $error . "<br />";
}
else
{
echo "Thank You! <br />";
}
//saves uploaded file
if (file_exists("forms/upload/" . $name))
{
move_uploaded_file( $tmpname, $target);
echo $name . " Old File Over Written. ";
}
else
{
move_uploaded_file( $tmpname, $target);
echo "Stored in: " . "forms/upload/" . $name;
}
?>
Maybe is my elseif statement broken?
I have only been playing with this php stuff for about a week so if I'm way off mark here sorry for wasting your time.
Maybe if I try making 6 functions with the globals move_uploaded_file($_FILES["file"]["tmp_name"], $target); than placeing them in the elseif statement it could work?
this is a copy of the working php page
<?php
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
//This applies the function to our file
$ext = findexts ($_FILES['afile']['name']) ;
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$new = "file1.";
//This assigns the subdirectory you want to save into... make sure it exists!
$targett = "forms/upload/";
//This combines the directory, the random file name, and the extension
$target = $targett . $new.$ext;
if ((($_FILES["afile"]["type"] == "image/gif")
|| ($_FILES["afile"]["type"] == "image/jpeg")
|| ($_FILES["afile"]["type"] == "image/pjpeg"))
&& ($_FILES["afile"]["size"] < 2000000))
{
if ($_FILES["afile"]["error"] > 0)
{
echo "Return Code: " . $_FILES["afile"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["afile"]["name"] . "<br />";
echo "Type: " . $_FILES["afile"]["type"] . "<br />";
echo "Size: " . ($_FILES["afile"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["afile"]["tmp_name"] . "<br />";
if (file_exists("forms/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["afile"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["afile"]["tmp_name"], $target);
echo "Stored in: " . "forms/upload/" . $_FILES["afile"]["name"];
}
else
{
echo "Invalid file";
}
That is a heck of a lot of repeated code! Do you really need 6 separate HTML forms? Why not have one form, with a dropdown for choosing the event?
<select name="event">
<option value="afile">Event One</option>
<option value="bfile">Event Two</option>
...etc
</select>
For the input, use:
<input type="file" name="userfile" id="file" />
Then instead of your lengthy if/else clauses, simply do something like this:
if ( isset($_POST['event']) && file_exists($_FILES['userfile']['tmp_name']) )
{
// base this code on the value of $_POST['event']
}
Maybe you should use
isset($_FILES["afile"])
instead of
file_exists($_FILES["afile"]["tmp_name"])
--edit
to answer your question in the title: it is possible, if, e.g $_FILES["afile"], is set. That way you'll have an array in your new variable.
Very close to working actually.
//Uses $names as a key in $_FILES - no single quotes for variable expansion....
$ext = findexts($_FILES[$names]['name']);
Might I also suggest using some sort of loop instead of a big elseif with a bunch of pasted code. Two improvements used: foreach on the $_FILES array, and extract
foreach ($_FILES as $fileKey => $values)
{
// Sets $type, $size, $name, $tmp_name, $error
extract($values);
//This applies the function to our file
$ext = findexts($name) ;
//This assigns the subdirectory you want to save into.
$targett = "forms/upload/";
//This combines the directory, the new file name, and the extension
$target = $targett . $new.$ext;
// makes sure image meets specs
if ((($type == "image/gif")
|| ($type == "image/jpeg")
|| ($type == "image/pjpeg"))
&& ($size < 2000000))
{
if ($error > 0)
{
echo "Return Code: " . $error . "<br />";
}
else
{
echo "Thank You! <br />";
}
//saves uploaded file
if (file_exists("forms/upload/" . $name))
{
move_uploaded_file( $tmp_name, $target);
echo $name . " Old File Over Written. ";
}
else
{
move_uploaded_file( $tmp_name, $target);
echo "Stored in: " . "forms/upload/" . $name;
}
}
}
I just wanted to thank everyone who left answers to my questions I was quite amazed at the short response time to my question. After trying and testing your answers I was still coming up short of any type of real solution to my problem it wasn't till I discovered that I forgot to end a if statement that I started making progress towards a answer.
if ((($type == "image/gif")
|| ($type == "image/jpeg")
|| ($type == "image/pjpeg"))
&& ($size < 2000000))
{
Now that this if statement has a ending and I have had time to study all of your answers I'm sure I will have this page working to my liking in no time.
It's working now but their are still refinements to be made. Here is my working html and php pages.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<!--
html admin page for HH
-->
<title>Administartor Panel</title>
<head>
<link rel="stylesheet" type="text/css" href="admin.css" />
</head>
<body>
<h1>Heritage House Administartor Panel</h1>
<br/>
<table>
<tr>
<td id="eone">
<br/>
<p>Event Uploader</P>
<form action="formupload.php" method="post"
enctype="multipart/form-data">
<label for="selection">Please select the event you would like to edit.</label>
<select name="selection">
<option value="file1">Event1</option>
<option value="file2">Event2</option>
<option value="file3">Event3</option>
<option value="file4">Event4</option>
<option value="file5">Event5</option>
<option value="file6">Event6</option>
</select>
<br />
<p> Please upload your event picture file here.</p>
<p align="center">
<label for="file">Photo:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Upload" />
</p>
</form>
<form action="WriteTxt1.php" method="post"
enctype="multipart/form-data">
<label for="file">Input Text for the event artical:</label>
<textarea rows="25" cols="100" name="content">
</textarea>
<br />
<input type="submit" name="submit" value="Save" />
</form>
</td>
</tr>
</form>
</td>
</tr>
</body>
</html>
PHP
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
//This if statement assigns the new file name to a variable from the value of the options menu in the html form selection.
$new = $_POST ["selection"] . ".";
//This applies the function to our file
$ext = findexts ($_FILES ["file"] ["name"]) ;
//This assigns the subdirectory you want to save into.
$targett = "forms/upload/";
//This combines the directory, the new file name, and the extension
$target = $targett . $new.$ext;
// makes sure image meets specs
if ((($_FILES ["file"] ["type"] == "image/gif")
|| ($_FILES ["file"] ["type"] == "image/jpeg")
|| ($_FILES ["file"] ["type"] == "image/pjpeg"))
&& ($_FILES ["file"] ["size"]< 2000000))
{
echo "file check pass<br />";
}
//makes an error if file does not meet standards
if ( $_FILES ["file"] ["error"] > 0)
{
echo "Return Code: " . $_FILES ["file"] ["error"] . "<br />";
}
else
{
echo "Thank You! <br />";
}
//saves uploaded file
if (file_exists("forms/upload/" . $_FILES ["file"] ["name"]))
{
move_uploaded_file( $_FILES ["file"]["tmp_name"], $target);
echo $_FILES ["file"] ["name"] . " Old File Over Written. ";
}
else
{
move_uploaded_file( $_FILES["file"]["tmp_name"], $target);
echo "Stored in: " . "forms/upload/" . $_FILES ["file"] ["name"];
}
?>
<html>
<!--
html to return user to admin page
-->
<title>
Upload Result
</title>
<head>
<p>
<br />
Back To Admin Page
</p>
</head>
<body>
<form action="">
<a href="adminarea.html">
<input type="button" value="Back" />
</a>
</form>
</body>
</html>
Note: I have only been using notepad2 and firefox to edit and error check my code. I'm guessing that their are better ways of debugging php out their right?

Categories