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>";
}
}
?>
Related
Sorry if this question is really long winded but i want to be as detailed as i can in hope of getting an answer to my problem.
Basically i have a multipart form that i want to add file upload capabilities to. I have the form created, a function to handle saving the image to a directory and also a script to handle posting the form values to the database. My problem is that the i have the image storing where i want it to now on submit of the form but none of the form values are being sent to the database. I think my problem is that i am trying to store the new path name as a variable which i then call in the POST script but i think this is wrong?
The error that is thrown up is:
Notice: Undefined index: image in C:\xampp\htdocs\web_design_cms\create_wireframe.php on line 13
Here's the code for the form:
<form action="create_wireframe.php" method="post" enctype="multipart/form-data">
<!-- page_title -->
<p>
<label>Title:</label><br/>
<input type="text" class="text small" name="wireframe_title" id="wireframe_title" value="" />
<span class="note">*required</span>
</p>
<!-- page_meta_title -->
<p>
<label>Browser Title:</label><br/>
<input type="text" class="text small" name="browser_title" id="browser_title" value="" >
<span class="note">*required</span>
</p>
<!-- url_key -->
<p>
<label>Permanent Link:</label><br/>
<input type="text" class="text small" name="url_key" id="url_key" value=""/>
</p>
<!-- page_image -->
<div style="float:left" >
<!-- wireframe_type -->
<p>
<label>Type:</label><br/>
<select name="wireframe_type" id="wireframe_type" class="styled" style="width:240px">
<option value="design" > Design Draft</option>
<option value="wireframe" selected > Wireframe</option>
</select>
<span class="note">*required</span>
</p>
</div>
<div style="clear:both"></div>
<div class="message info"><p>
Allowed file types for upload: jpg,jpeg,gif,png.<br/>
Max file size: 10Mb<br/>
Picture size: 4096x4096 px
</p></div>
<p>
<label>Upload Image:</label><br/>
<input type="file" name="page_main_image" id="page_main_image" value="" />
</p>
<!-- page_bg_color -->
<p>
<label>Color:</label><br/>
<input type="text" class="text small" maxlength="6" size="6" style="width:60px" id="colorpickerField" name="page_bg_color" value="ffffff" />
<span id="colorSelector" style="background-color:#ffffff;padding:7px 10px;"> </span>
<span class="note">*required</span>
</p>
<p>
<input type="submit" class="submit small" value="Save" name="submit" />
</p>
</form>
Here's the php script 'create_wireframe.php' handling the form data:
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (isset($_POST['submit'])) {
//Process the form
$image = upload_file();
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
$image = $_POST["page_main_image"];
$page_bg_color = $_POST ["page_bg_color"];
$query = "INSERT INTO wireframes (";
$query .= " wireframe_title, browser_title, url_key, wireframe_type, page_main_image, page_bg_color";
$query .= " ) VALUES (";
$query .= " '{$wireframe_title}', '{$browser_title}', '{$url_key}', '{$wireframe_type}', '{$image}', '{$page_bg_color}' ";
$query .= ")";
echo $query;
try { $result = mysqli_query($connection, $query);
} catch (Exception $e) {
return 'Caught exception: '+ $e->getMessage()+ "\n";
}
//Test if there was a query error
if ($result) {
//Success
// would normally use a redirect ie redirect_to("somepage.php");
//$message = "Subject created.";
redirect_to("wireframes.php");
}else {
//failure
//$message = "Subject creation failed.";
//redirect_to("add_project.php");
echo $query;
}
} else {
// This is probably a GET request
redirect_to("add_edit_wireframe.php");
}
?>
<?php
// Close database connection
if(isset($connection)){ mysqli_close($connection); }
?>
And finally the function i created for handling the storing of my images in the directory:
function upload_file(){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["page_main_image"]["name"]);
$extension = end($temp);
if ((($_FILES["page_main_image"]["type"] == "image/gif")
|| ($_FILES["page_main_image"]["type"] == "image/jpeg")
|| ($_FILES["page_main_image"]["type"] == "image/jpg")
|| ($_FILES["page_main_image"]["type"] == "image/pjpeg")
|| ($_FILES["page_main_image"]["type"] == "image/x-png")
|| ($_FILES["page_main_image"]["type"] == "image/png"))
&& ($_FILES["page_main_image"]["size"] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["page_main_image"]["error"] > 0) {
echo "Return Code: " . $_FILES["page_main_image"]["error"] . "<br>";;
}
else {
echo "Upload: " . $_FILES["page_main_image"]["name"] . "<br>";
echo "Type: " . $_FILES["page_main_image"]["type"] . "<br>";
echo "Size: " . ($_FILES["page_main_image"]["size"] / 1024) . " kb<br>";
if (file_exists("uploads/" . $_FILES["page_main_image"]["name"]))
{
echo $_FILES["page_main_image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["page_main_image"]["tmp_name"],
"uploads/" . $_FILES["page_main_image"]["name"]);
echo "Stored in: " . "uploads/" . $_FILES["page_main_image"]["name"];
$image="{$_FILES['page_main_image']['name']}";
}
}
}
else {
echo "Invalid file";
}
return $image;
}
I'm not entirely sure but i think the problem is something to do with the variable $image that im trying to store the path name in? At the end of the function i return the variable and in the post script then try to take this value and post it into the 'page_main_image' field in the database but clearly i'm doing something wrong?
Sorry again for long post but any help you can give me will really be appreciated! Thanks
When dealing with uploaded files, such as images, you need to use $_FILES instead of $_POST to access the data.
Check out this documentation.
Edit
You need to change the main logic.
$image = upload_file(); //Good
$wireframe_title = mysql_prep($_POST["wireframe_title"]);
$browser_title = $_POST["browser_title"];
$url_key = $_POST["url_key"];
$wireframe_type = $_POST["wireframe_type"];
//Delete this, you're throwing out the value from upload_file()
$image = $_POST["page_main_image"];
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']; ?>" />
I'm having problem with my code. I can't update my image.
Here is my full code:
index.php
//this link will post my data to next page
update
updatepage.php
//this page will get all data that want to update...
<?php
include("config.php");
$name=$_GET['code'];
$sql1 = "select * from imagename where name='$name'";
$result = mysql_query($sql1) or die(mysql_error());
$row=mysql_fetch_array($result);?>
<form name="form1" method="post" action="processupdatepage.php" class="formposition" enctype="multipart/form-data" >
<table>
<tr><td>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" /></td></tr>
<tr><td width="98">Image</td><td width="288">
//This is where I have problem, I can't get my image value but other data value work very well.....
<input type="file" name="image" value="<?php echo $row['image'];?>" /></td></tr><br/>
<tr><td>nane</td><td><input type="text" name="name" value="<?php echo $row['name']; ?>"/></td></tr><br/>
<tr><td></td> <td colspan="2">
<input type="submit" name="submit" value="Save" /> </td></tr>
</table>
</form>
OK. Now this my process file:
processupdatepage.php
<?php
include("config.php");
$id=$_POST['id'];
$image=$_FILES['image']['name'];
$name=$_POST['name'];
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
$query = "UPDATE imagename SET name='$name', image='$image' WHERE id='$id'";
$bb = mysql_query($query) or die(mysql_error());
if($bb)
{
//Writes the photo to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
$sql001="UPDATE imagename SET image='$image' WHERE image='$image'";
mysql_query($sql001);
} else { }
header("Location:index.php");
}
else
{
echo "Could not be updated";
}
?>
I can update BUT must select image. If I'm not selecting an image, my image field in database will be empty BUT other data updates are OK...
The value of an <input type="file"> cannot be programatically changed. Only by triggering its default behaviour that pops up the select file dialogue.
What I see from you example code is that you want to associate the value to the file form control element straight as it was retrieved from the database. So why saving the same back. Still, if you want to do this, you can use a hidden element with the value, that will be saved. But if you don't want the user to change it, just don't render it into the form and leave it out from your update query so it will remain unchanged.
Also, you could add some logic when you process the post and leave the field 'image' out of your update query if no file was selected.
I think the problem is here:
<input type="file" name="image" value="<?php echo $row['image'];?>" />
You can upload the image by clicking the browse button. so what do you trying to do like that?
If you want to show the image already uploaded you can use :
$img_path = 'get image path from database entry';
<img src= "<?php echo $img_path; ?>"/>
Here is full code to upload an Image, this is tested and works but you need to have a directory called 'upload' (this code does not create the folder).
It is advisable to only store image path on database.
<?php
if(isset($_POST['submit'])){
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
// HERE YOU CAN WRITE YOU INSERT INTO MYSQL CODE
//SOMETHING LIKE THIS:
$path = 'assets/article_images/'.$article_id.'/'.$_FILES["image_file"]["name"];
$statement1 = "INSERT INTO image_article (article_id, image_path) values ('$article_id', '$path') ";
$query_result = mysql_query($statement1) or die($statement1."mysql error<br/><br/>".mysql_error());
if($query_result==1){
echo 'Image uploaded';
}
}
}
}
else
{
echo "Invalid file";
}
}
?>
<html>
<body>
<form action="index.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
I've used this code in another site I've made and it works absolutely fine so I'm really confused as to why this isn't working properly. The only things I have changed are the directories for the file to be moved to, but the files never get uploaded. I've triple checked everything and it all seems fine. The code all executes without errors and all of the info gets entered into the database correctly, the only problem is the file not uploading. I'm going mad trying to get this to work! please help!
HTML FORM:
<p>
<h2>Add News</h2><br />
REQUIRED *<br /><br />
<form enctype="multipart/form-data" action='addnews2.php' method='post' onsubmit="chose.value = uploadForm()" name="newsform">
<p>Headline: *
<br>
<input name="title" type="text" size="75">
<br />
<br/>
News: *<br>
<textarea name="text" cols="75" rows="10" width="200"></textarea><br /><br />
Image File:
<br>
<input type="file" name="filetoupload" id="filetoupload"><br/><br />
<input type="submit" name="choose" value="Submit" />
</p>
</form>
</p>
Processing Page:
$date=date("l F d, Y");
$title=stripslashes($_POST['title']);
$text=stripslashes($_POST['text']);
if (($_FILES["filetoupload"]["type"] == "image/gif")
|| ($_FILES["filetoupload"]["type"] == "image/jpeg")
|| ($_FILES["filetoupload"]["type"] == "image/pjpeg")
|| ($_FILES["filetoupload"]["type"] == "image/png")
|| ($_FILES["filetoupload"]["type"] == "image/jpg"))
{
if ($_FILES["filetoupload"]["error"] > 0)
{
echo "Return Code: " . $_FILES["filetoupload"]["error"] . "<br />";
}
else
{
if (file_exists("images/news/" . $_FILES["filetoupload"]["name"]))
{
echo $_FILES["filetoupload"]["name"] . " already exists. ";
}
move_uploaded_file($_FILES["filetoupload"]["tmp_name"],
"images/news/" . $_FILES["filetoupload"]["name"]);
}
}
$image = "images/news/".$_FILES['filetoupload']['name'];
if($title==""||$text==""){
die("You need to fill in all details");
}
connect_to_db();
$query="insert into news (date, title, text, image) values ('".$date."','".mysql_real_escape_string($title)."','".mysql_real_escape_string($text)."','".$image."')";
$result=mysql_query($query);
if(mysql_affected_rows()==1){
header("Location:index.php?page=Admin&news=added");
}
else{
die("there was a problem");
}
mysql_close();
Looks like you are missing an else statement possibly, the code formatting is off and causes confusion:
if (file_exists("images/news/" . $_FILES["filetoupload"]["name"]))
{
echo $_FILES["filetoupload"]["name"] . " already exists. ";
}else {
move_uploaded_file($_FILES["filetoupload"]["tmp_name"],
"images/news/" . $_FILES["filetoupload"]["name"]);
}
Give that a shot. If not that, check your permissions etc. And make sure that the file isn't being uploaded, just not in the spot you expected it to be.
Just a bit of information, I would do the $title and $text check before you do the image check. As you probably do not want to upload the image to the site if both of those are null. You should also escape the file name in the image path prior to inserting:
$image = "images/news/".mysql_real_escape_string($_FILES['filetoupload']['name']);
As that could also be prone to injection.
<?php
if(isset($_POST['pic'])){
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 300000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
echo "<h1>Done! Looks Great!</h1>";
}
}
else
{
echo "Invalid file";
}
}
?>
<form action="editprofile.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<p>Image format should be png or jpg.</p>
<center><p class="submit"><input type="submit" name="pic" value="Upload Picture" /></p></center>
</form>
</div>
<p style="text-align:center; font-size:18px;">Current Picture</p>
<?php
$filename = $_FILES['file']['tmp_name'];
?>
<img src="/path/to/the/upload/folder/<?php echo $filename; ?>"/>
<img src="../../upload/foto.PNG" class="picture"/>
I am getting an error like undefined index - file.
Error is in the last few lines.
I basically have a folder which has an image. I want it to display the only image in the folder.
If you open the page for the first time, no form has been sent yet and $_FILES is therefore empty. You try to access $_FILES even in case of first load. This is the faulty line:
$filename = $_FILES['file']['tmp_name'];
You should check that $_POST["pic"] is set before accessing the $_FILES variable (just as you have done on the top of the code).