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
Related
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!";
}
}
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>
I made a dynamically changing HTML form where I can change the type of input of the form between a file upload or a drop down box that is populated from a remote database. The function that calls which input type to be displayed is in AJAX. When I submit the form using the drop down box, the form submits without any problems and performs the update to the database that I programmed it to do. However, when I try to submit the form while trying to upload the file, my error checking script (which are simple if... statements) tells me that it BOTH doesn't detect any file being uploaded and the file already exists on the database. However, when the "already exists on database" error appears, it doesn't return the name of the file that I'm trying to upload like I programmed it to do, so I suspect that my file isn't being submitted properly.
Can someone tell me what I did wrong?
Here's the script I have so far:
File 1: test.php
<html>
<body>
<head>
<script>
function getInput(value)
{
var xmlhttp;
if (value=="")
{
document.getElementById("display").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("display").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","grabtest.php?q="+value,true);
xmlhttp.send();
}
</script>
<?php
// connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
// if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
</head>
<form enctype="multipart/form-data" action="test2.php" method="POST">
<select id='SelectInput' onchange='getInput(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New File</option>
<option value='E'>Existing File</option>
</select>
<div id="display"></div><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($_POST)){
if ($_FILES["file"]["error"] == 0){
$target = 'PathName/TargetFolder/';
$target = $target . basename($FILES['file']['name']);
if (file_exists('PathName/TargetFolder/' . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists on server. ";
}
else{
$upload = $_FILES["file"]["name"];
$select = mysqli_query($con, "Select Files from DB_Table where Files = '$upload'");
if (mysqli_num_rows($select) > 0){
echo $_FILES["file"]["name"] . " already exists in database. ";
}
else{
//script for moving the uploaded file to the proper storage location on the server and adding it to the database
move_uploaded_file($_FILES["file"]["tmp_name"], $target . $_FILES["file"]["name"]);
echo "Stored in: " . $target . $_FILES["file"]["name"] . "<br>";
$insert="INSERT INTO DB_Table (Files) VALUES ('$upload')";
if (!mysqli_query($con,$insert)){
die('Error: ' . mysqli_error($con));
}
echo "Your data has been added to the database";
}
}
if ($_POST['recipe']=="" and !file_exists($_FILES['file']['tmp_name']) and !is_uploaded_file($_FILES['file']['tmp_name'])){
exit("Please select or add the file.");
}
}
mysqli_close($con);
?>
File 2: grabtest.php
<?php
//connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$q=$_GET["q"];
if ($q==""){
echo "";
}
elseif ($q=="N"){
echo "Select recipe to upload: <input type='file' name='newfile'>";
}
elseif ($q=="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from DB_Table");
echo 'Files: <select name = "Files">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Files"] . '</option>';
}
echo '</select><br>';
echo '</form>';
}
//after script is executed, close connection to database
//this improves security by ensuring the connection to the database does not remain open when there is no activity being done to change the data
mysqli_close($con);
?>
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.
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.