Why won't file stay selected after form post? - php

I am trying to allow an image to be uploaded with a form. I have code that makes sure that the user has entered valid information into the form. If invalid information is submitted, the user is asked to correct the errors and submit the form again. I am using the post data to populate the form fields so that the user does not have to enter the information again and is able to just edit the information they have already entered. It seems that the $_POST is receiving the file information but it will change to displaying "No file selected." rather than the name of the file. What is the problem here? Below are some excerpts of my code
//Set field values as posted data.
if ($_FILES["Image"]["error"] > 0)
{
echo "Error: " . $_FILES["Image"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["Image"]["name"] . "<br>";
echo "Type: " . $_FILES["Image"]["type"] . "<br>";
echo "Size: " . ($_FILES["Image"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["Image"]["tmp_name"];
}
$Name = $_POST['Name'];
$Image = $_FILES["Image"];
And the form:
<td><input type="file" name="Image" value="<?php echo($_FILES["Image"]["name"]); ?>"></td>

Related

PHP Form processing algorithm

By way of partial explanation, my mind-set is strongly procedural, since I've been programming that way since the 60s
I'm working in PHP and trying to get my head around form handling starting with an interactive 404 error form. What I want in minimal pseudo-code is:
do {
OK = true;
display_form;
ask for optional name
ask for optional email address
ask for optional comments
on – submit{
sanitise input
validate input (which could be no input since all is optional)
if one or more inputs invalid set OK = false
}
} while (OK == false)
assemble email to webmaster using $_SERVER superglobals as well as input
send using mail function
Someone "helpfully" added curlies after the while AND at the end -- they really don't belong there -- the idea was that I wanted execution to "drop through" to those two statements only after the DO -- WHILE completed
The mail assembly could be in a separate file, or not
While this is a semi-specific problem, I'm working on the assumption that, if I can get this to work, then getting a database update working will be easier.
It seems to me that my whole conceptual algorithm is incorrect, and until I sort that I'm nowhere. I've been banging at this for a a couple of days – Google pointed at a number of semi-relevant answers here, so I'm giving it a go. The W3C examples clearly show the response code running even when there are problems with the input, which is not what I want.
The main switch you need to make here is probably the one to a request-response model of execution. You can't do a literal do..while, since you will need to send a response back to the client. The next iteration of that will be triggered by a new request to PHP, which begins again from the beginning and doesn't remember any previous state.
So, in pseudo code, it works like this:
if is POST request:
validate input, populate error variables
if input is valid:
send email with data
redirect to different page or display "thanks"
form start
for $field in fields:
output HTML for $field
maybe highlight if error
maybe set value to POSTed value to retain data
form end
So, upon the first page visit, it won't be a POST request and falls straight through to the form part. There won't be any errors or existing data, so the plain form will be output. When the form is submitted, the same code runs again and now enters the if is POST branch. If any values are invalid, it will fall through to the form again, which now can also output any error messages and existing submitted values. Only when all values are valid, will the server send an email and exit this "loop" by redirecting to another page, or maybe just outputting a "Thank you" note.
If you properly separate that into an MVC architecture, you'd have these components:
Model
data validation
email sending
View
outputs the form HTML
Controller
one for handling GET requests, just invoking the view
one for handling POST requests, essentially doing:
errors = model.validate(data)
if no errors:
model.send_email(data)
redirect()
else:
view.display_form(data, errors)
some form of router invoking the right controller based on the request URL and method
These could all be separate functions, or classes, or methods, or just files.
Below is the final code for the page. It's a basic 404 error page that may be of use to someone. And it should answer the requests that I supply the code that I was working with
It includes three files that I've not supplied:
top.php and footer.php and functions.php
top produces the HTML head statements including meta codes and also including top level banners and menu, as well as establishing the basic page format.
footer-- using the server superglobal just before the footer include, the page can provide a code update date for the page. And a consistent name and registration number for our organisation
functions.php supplies a bunch of reused functions. There are a couple of little (fairly obvious) functions in used in this code:
spacer outputs code to create an empty cell in a table.
spanCol creates a column spanning cell in a table, with the specified text and
specified tag open and close
The full page is at http://www.vfmc.org.au/notfound.php -- please don't send me too much junk email.
Code for the guts is here - I don't claim that it's brilliant, but it works thanks to help from here:
<?php
$pageTitle = "File Not Found";
$authorName = "Don Gingrich";
$styleSheet = "./css/mainstyle.css";
include_once 'top.php';
require_once "functions.php";
$indicesServer = array(
'PHP_SELF',
'HTTP_REFERER',
'SCRIPT_FILENAME',
'SCRIPT_NAME',
'REQUEST_URI',
'ORIG_PATH_INFO'
);
if (isset($_SERVER['HTTP_REFERER'])) {
$refering = $_SERVER['HTTP_REFERER'];
} else {
$refering = NULL;
}
$requested = $_SERVER['REQUEST_URI'];
// $refering = $_SERVER['HTTP_REFERER'];
if ($refering == NULL || $refering == " ") {
$refering = "referrer field was blank\n - may be due to mis-typing address\n";
}
/* basic "sanitise input" function */
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function send_webmaster_email($name, $email, $comment, $requested, $refering)
{
global $sent;
$subject = "File not Found: $requested";
$txt = "Trying to access $requested from $refering\n" . "Visitor comments follow:\n" . $comment;
if ($name != "") {
$txt .= "\n\tReporting person's name is: $name\n";
}
if ($email != "") {
$txt .= "\n\tReporting person's email is: $email\n";
}
$to = "webmaster#vfmc.org.au";
$additional_headers = "From: webmaster#vfmc.org.au\r\n";
mail($to, $subject, $txt, $additional_headers);
$sent = true;
}
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = $comment = "";
$myError = false;
global $sent;
$sent = false;
/********************************************************
* Processing code follows -- Only executed after POST
*
*******************************************************/
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$requested = $_POST['requested'];
$refering = $_POST['refering'];
$requested = test_input($requested);
$refering = test_input($refering);
$myError = false;
if ($_POST["button"] == "Submit") {
if (empty($_POST["name"])) {
$name = "";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]*$/", $name)) {
$myError = true;
$nameErr = "Only letters, hyphen, and white space allowed";
}
}
if (empty($_POST["email"])) {
$email = "";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$myError = true;
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$comment = "";
} else {
$comment = test_input($_POST["comments"]);
}
if ($myError == false) {
send_webmaster_email($name, $email, $comment, $requested, $refering);
}
}
}
echo "\n";
echo "<h2>File Not Found</h2>\n";
echo "<br>\n";
echo "<br>\n";
if ($sent == true ){
echo "<h5>Email sent to Webmaster, Thank you</h5>\n";
echo "<br>Use the menu to the left or the back button<br>\n";
echo "to return to the VFMC site<br>\n";
} else {
echo " Unfortunately the file that you have asked for is unavailable.\n";
echo "<br>\n";
echo "<br>\n";
echo "This may mean that the Webmaster has forgotten to load it or the link to it is broken in some way.<br>\n";
echo "Or, if you typed a page in the browser address bar, you may have mis-typed, remember that everything<br>\n";
echo "after the <b>www.vfmc.org.au/</b> is CaSeSensitive -- FiresideFiddlers, is spelled as written.<br>\n";
echo " <br>\n";
echo " <br>\n";
echo "<h6>Please tell the webmaster by sending a message:</h6>\n";
echo " <br>\n";
echo " <br>\n";
$myFile = htmlspecialchars($_SERVER['PHP_SELF']);
echo " <form action= \"$myFile\" method=\"post\">\n";
echo "<input type=\"hidden\" name=\"refering\" value=\"$refering\" />\n";
echo "<input type=\"hidden\" name=\"requested\" value=\"$requested\" />\n";
echo " <table border=\"0\" cellpadding=\"8\" cellspacing=\"8\">\n";
echo " <colgroup>\n";
echo " <col width = auto>\n";
echo " <col width = auto>\n";
echo " <col width = auto>\n";
echo " </colgroup>\n";
echo " <tr>\n";
spanCol("3", "Your name and email address are optional,<br> but the webmaster will be unable to respond <br>directly without them", "h5");
echo " <tr>\n";
echo " <td><label for=\"tswname\">Name</label>:</td>\n";
echo " <td><input type=\"text\" name=\"name\" id=\"tswname\" size=\"25\" /></td>\n";
echo " <td>\t";
if ($nameErr == "") {
echo "(Optional)\n";
} else {
echo "<span class=\"error\">*" . $nameErr . "</span>\n";
}
echo "</td></tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " <label for=\"tswemail\">Email address</label>:</td>\n";
echo " <td>\n";
echo " <input type=\"text\" id=\"tswemail\" name=\"email\" size=\"25\" />\n";
echo " </td>\n";
echo " <td>\n";
if ($emailErr == "") {
echo "(Optional)\n";
} else {
echo "<span class=\"error\">*" . $emailErr . "</span>\n";
}
echo "</td></tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " <label for=\"tswcomments\">Comments</label></td>\n";
echo " <td colspan=\"2\">\n";
echo " <textarea rows=\"15\" cols=\"45\" name=\"comments\" id=\"tswcomments\"></textarea>\n";
echo " </td>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <td align=\"center\" colspan=\"2\">\n";
echo " <input type=\"submit\" name=\"button\" value=\"Submit\" /><br>\n";
echo " </td>\n";
echo " </tr>\n";
echo " </table>\n";
echo " </form>\n";
}
echo " <br>\n";
echo " <br>\n";
echo " <br>\n";
echo " <br>\n";
echo "</td>\n";
echo "</tr>\n";
$filename = $_SERVER['SCRIPT_NAME'];
require_once "footer-code.php";
?>
</tbody>
</table> <!--PWK-EDIT END FOOTER-->
</body>
</html>

PHP - Login via form and grab cookie

I'm trying to login to the following URL: pitangui.amazon.com
I have tried using cURL as well as libraries like https://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
However, I'm getting the following error using the webscraper via Amazon:
This is my PHP code:
<?php
require_once "support/http.php";
require_once "support/web_browser.php";
require_once "support/simple_html_dom.php";
$url = "https://pitangui.amazon.com";
$web = new WebBrowser(array("extractforms" => true));
$result = $web->Process($url);
if (!$result["success"]) echo "Error retrieving URL. " . $result["error"] . "\n";
else if ($result["response"]["code"] != 200) echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
else
{
$form = $result["forms"][0];
$form->SetFormValue("email", "myemail#gmail.com");
$form->SetFormValue("password", "mypass");
$result2 = $form->GenerateFormRequest("signIn");
$result = $web->Process($result2["url"], "auto", $result2["options"]);
if (!$result["success"]) echo "Error retrieving URL. " . $result["error"] . "\n";
else if ($result["response"]["code"] != 200) echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
else
{
// Do something with the results page here...
print_r($result);
}
}
?>
I'm first trying to get the login working, then I will grab the cookie via $_SERVER['Cookie']
add
$form->SetFormValue("create","0");

php image upload will not work

I have asked this question before I made changes to my code and my image upload is not working at all I have checked username password, and Root they are all correct. my code will not show any errors I dont know what to do anymore can someone please help me? I have changed my connection for security reasons
<?php
$con = mysqli_connect("localhost", "torcdesi_jone45", "password", "torcdesi_amazing");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_image = 'INSERT INTO shirt_table (images3)
values( "' . $_FILES['file3']['name'] . '")';
?>
<?php
include("configur.php");
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file3"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file3"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("shirtimgs/" . $_FILES["file3"]["name"])) {
} else {
//move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file3"]["tmp_name"],"shirtimgs/" . $_FILES["file3"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into shirt_table";
if(mysqli_query($link, $query_image)) {
echo "Stored in: " . "shirtimgs/" . $_FILES["file3"]["name"];
} else {
echo'';
}
}
}
}
}
?>
As I stated in comments, your form is missing a proper enctype to handle files.
This I know, since I saw your other question that did not contain it in the form.
<form enctype="multipart/form-data" action="__URL__" method="POST">
As per the manual:
http://php.net/manual/en/features.file-upload.post-method.php

File validation error when submitting form with an empty file

I have a form and when i submit it, it will validate if the file exist or not. The Validation works if I choose a file to upload. When I don't need to upload a file, I leave the choose file empty, the validation does not work and the script always shows that the file already exist even though I don't need to upload a file and the input type="file" is not required
Here is my Code:
<form action="../function/add_pre.php" method="post" enctype="multipart/form-data" >
<table class="table table-bordered">
<tr>
<td><label class="form-control">Attach and Upload your Proposal for Purchase Request:</label></td>
<td><input class="form-control" type="file" name="file" title="Click here to select file to upload."></td>
</tr>
</table>
<button name="submit" type="submit" class="btn btn-info"><i class="fa fa-paper-plane"></i> Submit</button>
</form>
This is the add_pre.php
if(isset($_POST['submit'])){
if (file_exists("../employee/" . $_FILES["file"]["name"])){
echo '<script language="javascript">alert(" Sorry!! Filename Already Exists...") </script>';
echo '<script language="javascript">window.history.back();</script>';
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../employee/" . $_FILES["file"]["name"]) ;
$sql = "INSERT INTO purchase_request_file (pr_no,file) VALUES ('" .$pr_no."','" .
$_FILES["file"]["name"] ."');";
if (!mysql_query($sql))
echo('Error : ' . mysql_error());
else
echo"Success!";
}
I need to echo"Success!" even though i submitted the form without a file.
From the documentation of file_exists() function,
file_exists — Checks whether a file or directory exists
So if you don't upload any file, $_FILES["file"]["name"] will be an empty string, and file_exists() function will check whether this directory ../employee/ exists or not, which does exist in your case. And this is the reason why your file validation is failing.
The solution is, use is_uploaded_file() function to check a file has been uploaded or not, like this:
if(isset($_POST['submit'])){
if(is_uploaded_file($_FILES["file"]["tmp_name"])){
if (file_exists("../employee/" . $_FILES["file"]["name"])){
echo '<script language="javascript">alert(" Sorry!! Filename Already Exists...") </script>';
echo '<script language="javascript">window.history.back();</script>';
}else{
move_uploaded_file($_FILES["file"]["tmp_name"],"../employee/" . $_FILES["file"]["name"]);
$sql = "INSERT INTO purchase_request_file (pr_no,file) VALUES ('" .$pr_no."','" . $_FILES["file"]["name"] ."');";
if (!mysql_query($sql))
echo('Error : ' . mysql_error());
else
echo"Success!";
}
}else{
// user hasn't uploaded any file
}
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
first check if you choose file first, then check if file exits. because file_exists also check if directory exits. in your code, when there is no file to upload, your code check if employee directory exits, which is true. for this reason you always show file exits.
if(isset($_POST['submit'])){
if(!isset($_FILES["file"]["name"]))
{
//do what you want
echo "success";
}
else if (file_exists("../employee/" . $_FILES["file"]["name"])){
echo '<script language="javascript">alert(" Sorry!! Filename Already Exists...") </script>';
echo '<script language="javascript">window.history.back();</script>';
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../employee/" . $_FILES["file"]["name"]) ;
$sql = "INSERT INTO purchase_request_file (pr_no,file) VALUES ('" .$pr_no."','" .
$_FILES["file"]["name"] ."');";
if (!mysql_query($sql))
echo('Error : ' . mysql_error());
else
echo"Success!";
}
}

php if else error with form field

My form has a input file type field.
<input type="file" name="file" size="80" value="">
when submitted and this field is empty the file upload part of my php script should be skipped. This does not seem to be happening. What I am getting is the wrong file type message popping. Nothing was populated in the field on the form so why is my if/else statement not being followed? What am I doing wrong?
<?php
// connect to datebase
require "master.db.php";
// this if(empty statement is not working?
// should be checking to see if the form field 'file' is populated if so check file
// type if not skip and update sql database with information in form field 'test'
if(!empty($_FILES))
{
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152))
{
// code here works - function is to upload the file - not part of my current problem
}
// currently this else statement is displayed regardless of 'file' input
// wrong function for its intended purpose
else
{
// wrong file type
echo "Invalid file <br />";
echo "Tryed to upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb Max 2Mb <br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
die;
}
}
else
{
// update other data in mysql database
$sql="UPDATE `characters` SET test='$test' WHERE ID='$id'";
$result=mysql_query($sql);
// if successfully updated mysql.
if($result){
echo "<b>Update successful</b> <br />";
echo "<a href='test.html'>View result</a>";
touch('master.html');
clearstatcache();
}
else
{
echo "Whoops: " . mysql_error(); ;
}
mysql_close();
}
?>
The browser will still send the input value, even though the value is empty. As a consequence, PHP will populate the $_FILES array with something like:
Array
(
[file] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
So instead of checking with isset/empty, I guess you should use PHP's native is_uploaded_file method. See this SO post for more info on checking if an optional file input was provided.
I'll try to clarify my answer. The reference I just gave suggests using file_exists and is_uploaded_file. According to the PHP manual only using is_uploaded_file is sufficient. In fact, I can imagine is_uploaded_file looks up the file anyway (so internally already does something like file_exists).
Please note that you really should use the tmp_name-key instead of the name-key. The 'name' key specifies the name of the file on the client's PC, but the tmp_name specifies the name on the server. There are situations when the server renames the file and therefore differs from the name on the users PC.
please be sure to add
enctype="multipart/form-data"
attribute in you form tag . and follow #Martijn guidelines
check the below code, it must work. be sure to customize .
<?php
// connect to datebase
require "master.db.php";
// this if(empty statement is not working?
// should be checking to see if the form field 'file' is populated if so check file
// type if not skip and update sql database with information in form field 'test'
if(!empty($_FILES)) // MEANS form is valid ( have valid file and other data)
{
$sql="UPDATE `characters` SET test='$test' WHERE ID='$id'";
$result=mysql_query($sql);
if (((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2097152)) && $result ))
{
// code you need to execute
echo "<b>Update successful</b> <br />";
echo "<a href='test.html'>View result</a>";
touch('master.html');
clearstatcache();
}
else
{
// wrong file type
echo "Invalid file <br />";
echo "Tryed to upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb Max 2Mb <br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
die;
}
}
else
{
echo "data is not valid";
}
?>

Categories