ignoring blank file upload field - php

I've a form with upload field, it works fine. it uploads and everything is good, except that when the upload field is empty. the field in the database table goes blank as well, nothing in it, not even the old image entry!
My Form:
<form enctype="multipart/form-data" action="add.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="site_logo"><br>
<input type="submit" value="Add">
</form>
The PHP code:
<?php
$target = "../upload/";
$target = $target . basename($_FILES['site_logo']['name']);?>
<?php
move_uploaded_file($_FILES['site_logo']['tmp_name'], $target);
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
the query:
$site_logo=($_FILES['site_logo']['name']);
$query = "UPDATE ss_settings SET
site_logo = '{$site_logo}'
WHERE id = 1 ";
$result = mysql_query($query, $connection);
I've set the database connection and the update query and everything. just posted the process code so it be clear to you guys. I just want it to do nothing when the field is empty.

Check out the error messages explained http://www.php.net/manual/en/features.file-upload.errors.php
To check if a file wasn't uploaded:
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_NO_FILE)
A better way, is to check if there were no errors.
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)

If your query is an UPDATE statement you should not change it, also you can try with
<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
// do stuff when no file field is set
}else{
// do stuff when file is set
}
// ...
?>

Personally I would not use an un-sanitized name for a file, but all you need to do in your case, is check for a valid file-upload before you do your query.
So something like (in PDO as the mysql_* functions are deprecated):
// first line borrowed from #DaveChen, +1 for that
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
{
$stmt = $db->prepare("UPDATE `ss_settings` SET
`site_logo` = :site_logo
WHERE `id` = :id ";
// bind variables
$stmt->bindValue(':site_logo', $_FILES['site_logo']['name'], PDO::PARAM_STR);
$stmt->bindValue(':id', $the_ID, PDO::PARAM_INT);
// execute query
$stmt->execute();
}

Perhaps try something like this to prevent processing of blank uploads:
if($_FILES['site_logo']['error']==0) {
// process
} else {
// handle the error
}
http://php.net/manual/en/features.file-upload.errors.php

Your problem is that you're simply assuming that a successful upload has taken place. NEVER assume success. ALways check for failure. PHP provides the ['error'] parameter in $_FILES for a reason. use it:
if ($_FILES['site_logo']['error'] == UPLOAD_ERR_OK) {
... upload was successful
} else {
die("Upload failed with error code: " . $_FILES['site_logo']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
You'll wan to check for code 4 (UPLOAD_ERR_NO_FILE), which means the user didn't upload anything at all.

Related

Upload process don't save the right name in database

I have a code in php with validation ok all working properly but my problem is that when I try to save in database I obtain something like this:
img_id img_small img_big
5 /tmp/phpdlYkiG /tmp/phph3dhka
I don't know why php save that name because the images have a diffent names like koala.jpg and horse.jpg
Here is my code in order to see if somebody have any suggestion...
<form enctype="multipart/form-data" action="upload_type_1.php" method="POST" >
<input type="file" name="img_small_1" id="img_small_1">
<input type="file" name="img_big_1" id="img_big_1">
<input type="submit" value="Upload" name="submit">
</form>
and this is my php code:
if ( (move_uploaded_file($_FILES["img_small_1"]["tmp_name"], $target)) && (move_uploaded_file($_FILES["img_big_1"]["tmp_name"], $target2)) ){
$img_title_1 = $_POST['img_title_1'];
$sql = "INSERT INTO press (img_title, img_small, img_big) VALUES ('$img_title_1', '$img_small_1', '$img_big_1')";
$retval = mysql_query( $sql, $conn );
if(!$retval) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
echo "Your files has been uploaded";
} else {
echo "Sorry, there was an error uploading your files.";
exit;
}
This code work properly the only problem is that save into database that strange names and I need to use that names...
Thanks! - Waiting for help!
Your issue is probably not in the code that you are showing but in the code you are not showing, which is your variable declarations for $img_small_1 && $img_big_1. Taking a guess you have
$img_small_1 = $_FILES["img_small_1"]["tmp_name"];
$img_big_1 = $_FILES["img_big_1"]["tmp_name"];
but you want/need
$img_small_1 = $_FILES["img_small_1"]["name"];
$img_big_1 = $_FILES["img_big_1"]["name"];
$img_title_1 = $_POST['img_title_1'];
Should be:
$img_title_1 = $_FILES["img_small_1"]["name"]
A Simple Example of File Uploading
$uploadDir = "Your_upload_dir";
$img_small = $_FILES['img_small_1'];
$img_small_name = $img_small['name']; // get image name
$img_small_tmpName = $img_small['tmp_name'];
$img_small_fileSize = $img_small['size'];
$img_small_fileType = $img_small['type'];
if ($img_small['error'] == 0)
{
$img_small_filePath = $uploadDir . $img_small_name;
$result = move_uploaded_file($img_small_tmpName, img_small_filePath); //return true or false
}

file upload return to upload html page

I'm looking to return to the previous page after a file upload and have "file uploaded successfully" on the upload page.
In upload.php at the top I have placed
sesssion_start();
And at the end of the file upload script I have placed
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
Now I know i need to put some code into the html document but unsure what needs to go in. Below is my html form script
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
I know it is going to be something similar to this but unsure how or where I would place it.
session_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
If someone could walk me through adding the HTML code into the correct place I will be very greatful
After the comments i amend my php code to look like this.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
sesssion_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name'] ). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
exit();
And the syntax inside the stream.php to:
<?phpsession_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
?>
Thanks,
Mark
Nota: You also cannot use echo and header together because that would considered as outputting before header, so we'll just use a session array as the message and the header to redirect to "upload_form.php", then show the respective message on that page afterwards.
Use session_destroy() also to destroy any previous sessions.
Sidenote: Use two seperate files.
HTML form: call this "upload_form.php"
<?php
session_start();
session_destroy();
?>
<form action="stream.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File">
</form>
<?php
if(isset($_SESSION['upload_success'])){
echo $_SESSION['upload_success'];
}
else{
echo "Please select a file.";
}
?>
PHP (file 2): call this "stream.php"
<?php
session_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
$_SESSION['upload_success'] = "File successfully uploaded.";
header("Location: upload_form.php");
exit;
}
else {
$_SESSION['upload_success'] = "Sorry, there was a problem uploading your file.";
header("Location: upload_form.php");
exit;
}
Edit:
Modify and add the following after if(move_uploaded_file...
if(isset($_FILES['uploadedfile']) && !empty($_FILES['uploadedfile'])){
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name']);
}
Your code works fine, but you should remove session['upload_success'] with unset function after you do echo success message.
try
unset( $_SESSION['upload_success'])
in stream.php right after
echo "File uploaded successfully";
update :
if you want to work all these on a single page, You can simply do it like below:
if(isset($_SESSION['upload_success']) and $_SESSION['upload_session'])
{
//echo success message
//remove session
}
if(isset($_POST['file'])){
//upload process , if it was successfull make seesion true...
}
else {
//show form
}
For a quick solution, you could use Ravi Kusuma's jQuery File Upload Plugin or an AJAX solution to do this.
Another alternative, though, to those proposed above is to programmatically construct / output an HTML form with some javascript, and get it to POST a message to stream.php:
CAVEAT: I haven't tried this myself, but I can't think why it wouldn't work. Would someone please confirm my sanity? -- Tested it myself: it works.
<?php
//upload.php
//Do file upload stuff, then:
$out = '
<form id="frmUpOkay" action="stream.php" method="post">
<input name="upMsg" value="Upload Successful" />
</form>
<script type="text/javascript">
$(function(){
$("#frmUpOkay").submit();
});
</script>
';
echo $out;
?>
You must also add this bit to the top of the stream.php file:
<?php
if ( isset($_POST['upMsg']) && isset($_POST['upMsg']) != '' ){
$upMsg = $_POST['upMsg']; //you should sanitize this input
}else{
$upMsg = '';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
Your normal website content is here.<br>
<br>
Upload message: <?php echo $upMsg; ?> <br>
<br>
</div>
</body>
Notes:
Above code uses jQuery, so you would need the jQuery library included on your upload.php page (as shown above).
Placing
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
At the end, I believe, would set true no matter what actually happened with the file's upload the reason being, there is not a condition being checked.
Unless the script has an exit command when it fails, it will eventually get to the part where it says: "Set the upload success as true and then go to stream.php" rather than saying, "If the upload is successful, set the upload success as true and then go to stream.php"
I would try:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if($_FILES['uploadedfile']['size'] == 0)//In other words, if no file was selected.
{
$_SESSION['upload_success'] = 4;//File wasn't selected
header("Location: stream.php");
exit();
}
if(!file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],'upload/' . basename($_FILES['uploadedfile']['name'])) ? 1 : 2);
}
elseif(file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = 3;
}
header("Location: stream.php");
exit();
?>
Now in stream.php where you have your if statement that displays the message do this instead:
<?php
session_start();
switch (#$_SESSION['upload_success']) {
case 1:
echo "File uploaded successfully";
break;
case 2:
echo "Sorry, there was a problem uploading your file.";
break;
case 3:
echo "A file with that name already exists!";
break;
case 4:
echo "You must select a file to upload!";
break;
}
unset($_SESSION['upload_success']);
?>//So if you reload stream.php yet another time no messages will be displayed again for no reason. ie. none of the cases will match an unset variable.
Last, you cannot echo (or do any type of output meant to be viewed by a user) before you header(Location: "somepage.php");
The page will switch before the user can read the output.
The way your code is currently written in your question you could have the following happen:
The server echos "Sorry, there was a problem uploading your file", which will never be seen by the user.
$_SESSION['upload_success'] is then set to TRUE, which is obviously not in agreement with #1.
It then sends the user to stream.php where a success message is
displayed.
An alternate, lazier way with less useful scenario descriptions to also fix your problem would be to do this instead (in upload.php):
else
{
die("Sorry, there was a problem uploading your file.");
}
Hope that helps!

How to stop file being inserted into server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
files get uploaded just before they get cancelled
I have a situation when it comes to cancelling a file upload. What is suppose to happen is that if the user clicks on the "Cancel" button, then it will go to script below and remove the file from the server and delete the file's records from the database:
cancelaudio.php
<?php
session_start();
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
unlink("AudioFiles/" . $_SESSION['AudioFile']); //undefined notice
$delete = $mysqli->prepare('DELETE FROM Audio WHERE AudioId = ?');
$delete->bind_param("i",$_SESSION['lastAudioID']);
$delete->execute();
$deleteaud = $mysqli->prepare('DELETE FROM Audio_Question WHERE AudioId = ?');
$deleteaud->bind_param("i",$_SESSION['lastAudioID']);
$deleteaud->execute();
?>
Now this is the situation I am having:
If I clean my cookies, it means obviously I have no files stored my $_SESSION variable. Now if I try to upload a file (first file) but then cancel it, then I get an undefined index notice for "AudioFile". This is fair as obviously I have no file stored in that $_SESSION variable. But the problem is that it does not perfrom the unlink() and DELETE statement in the code above so it will display the record of the file and still uploads it.
So what is happening is that until I have one file in the server and a file stored in the $_SESSION['AudioFile'], it would not remove the file from the server and and it would delete the record from the database.
So what my question is that what do I need to do so that if there is no file in the $_SESSION['AudioFile'] and the user uploads and then cancels a file, how can I stop it from inserting the file into the server and inserting the database record?
Below is the code where it uploads the files and inserts the data into the database:
audioupload.php
<?php
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
if( file_exists("AudioFiles/".$_FILES['fileAudio']['name'])) {
$parts = explode(".",$_FILES['fileAudio']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("AudioFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileAudio']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
$audiosql = "INSERT INTO Audio (AudioFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($audiosql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$aud);
//Assign the variable
$aud = 'AudioFiles/'.$_FILES['fileAudio']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastAudioID = $mysqli->insert_id;
$_SESSION['lastAudioID'] = $lastAudioID;
$_SESSION['AudioFile'] = $_FILES["fileAudio"]["name"];
$audioquestionsql = "INSERT INTO Audio_Question (AudioId, QuestionId)
VALUES (?, ?)";
if (!$insertaudioquestion = $mysqli->prepare($audioquestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err audioquestion";
}
$qnum = (int)$_POST['numaudio'];
$insertaudioquestion->bind_param("iii",$lastAudioID, $qnum);
$insertaudioquestion->execute();
if ($insertaudioquestion->errno) {
// Handle query error here
}
$insertaudioquestion->close();
?>
Below is the HTML form for the file input:
<form action='audioupload.php' method='post' enctype='multipart/form-data' target='upload_target_audio' onsubmit='return audioClickHandler(this);' class='audiouploadform' >
Audio File: <input name='fileAudio' type='file' class='fileAudio' /></label><br/><br/><label class='audiolbl'>
<input type='submit' name='submitAudioBtn' class='sbtnaudio' value='Upload' /></label>
<input type='hidden' class='numaudio' name='numaudio' value='" + GetFormAudioCount() + "' />
<label><input type='reset' name='audioCancel' class='audioCancel' value='Cancel' /></label>
<iframe class='upload_target_audio' name='upload_target_audio' src='#' style='width:300px;height:300px;border:0px;solid;#fff;'></iframe></form>
Finally below is the jquery function where if the user clicks on the "Cancel" button while the file is uploading, it will simply change the iframe source to "cancelaudio.php":
function startAudioUpload(audiouploadform){
$(audiouploadform).find('.audiof1_upload_process').css('visibility','visible');
$(audiouploadform).find('.audiof1_upload_form').css('visibility','hidden');
sourceAudioForm = audiouploadform;
$(audiouploadform).find(".audioCancel").on("click", function(event) {
$('.upload_target_audio').get(0).contentwindow
$("iframe[name='upload_target_audio']").attr("src", "cancelaudio.php");
return stopAudioUpload();
});
return true;
}
To get rid of your undefined index stuff, plus make your script a lot more robust, you SHOULD add error checking. Even a simple
if ($_FILES['fileAudio']['error'] === UPLOAD_ERR_OK) {
... successful upload ...
}
would reduce a lot of your problems. Right now your code simply assumes a successful upload, without even bothering to check if an upload was event attempted.
The various error codes for failure are defined here: http://php.net/manual/en/features.file-upload.errors.php

Why do I get this error when trying to upload an image?

When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.

Image upload form in PHP does nothing, no error

I have the following PHP code that I am using to upload an image to MySQL. When I click submit nothing happens.
include ("connect.php");
session_start();
$login = $_SESSION['wname'];
if((#$_POST['submit'])&&(isset($_FILES["myfile"]))){
// properties of the uploaded file
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
if($name){
die("Error uploading file! Code $error.");
} else {
$place = "avatars/$name";
move_uploaded_file($tmp_name,$place);
$query = mysql_query("UPDATE page SET pid_image_name = '$place' WHERE wname = '$login' ");
die("upload complete <a href='index.php'>View image</a>");
echo "Upload complete!";
}
} else {
die("select a file");
}
Here's my form:
<form action='up.php' method='POST' enctype='multipart/form'>
<input type='file' name='myfile'>
<p> <input type='submit' name='submit' value="upload">
What am I doing wrong?
Another important parameter to check out in php.ini is post_max_size. If you set upload_max_filesize > post_max_size the result is that no data is written to $_POST nor $_FILES for files which sizes exceed post_max_size but are below upload_max_filesize
Format you're code.
Are you submitting the actual HTML form (not the PHP code) as html/multipart?? I am willing to be you're not. (enctype="multipart/form-data" needs added to your form tag!)
Learn to debug - actually put conditions elsewhere and see where your code is failing!
In your HTML for have you got enctype="multipart/form-data"?
Something like this:
<form action='submit.php' method='post' enctype="multipart/form-data">
Edit 1:
if you do this: if(move_uploaded_file($tmp_name, $place)){
echo "did move file<br />";
}else{
echo "move failed<br />";
}
You will get move failed (Or I do with your code)
Edit 2
I found your problem: you misspelt the temp-dir variable: you defined $temp but in the move_uploaded_file you asked for $tmp_name so here the correct code: move_uploaded_file($temp, $place);
Just in case you can't see any errors activate error reporting by setting error_reporting(E_ALL); right after the php tag.

Categories