PHP file upload and rename to specific name to overwrite previous version - php

I'm trying to make it easy to update menus(two PDFs) online for some coworkers by creating a small upload form to upload the PDF into the menus directory and give it a specific name so that it overwrites the previous version.
Here is what I have so far...
Form:
<section>
<form action="menu_uploader.php" method="post" id="menu_upload" name="menu_upload" enctype="multipart/form-data" >
<p><label for="wine_list_menu_upload">Wine List -> </label> <input type="file" name="wine_list_menu_upload" id="wine_list_menu_upload"></p>
<p><label for="food_flight_menu_upload">Food & Flights -> </label> <input type="file" name="food_flight_menu_upload" id="food_flight_menu_upload"></p>
<p><input type="submit" name="submit" value="Upload" id="submit"></p>
</form>
</section>
PHP
<?php
if( ($_FILES["wine_list_menu_upload"]["type"] == "application/pdf") &&
($_FILES["food_flight_menu_upload"]["type"] == "application/pdf") &&
($_FILES["wine_list_menu_upload"]["size"] < 1048576*5) &&
($_FILES["food_flight_menu_upload"]["size"] < 1048576*5))
{
if($_FILES["wine_list_menu_upload"]["error"] > 0 || $_FILES["food_flight_menu_upload"]["error"] > 0)
{echo "Error Code: " . $_FILES["wine_list_menu_upload"]["error"] xor $_FILES["food_flight_menu_upload"]["error"] . "<br>";}
else
{move_uploaded_file($_FILES["wine_list_menu_upload"]["tmp_name"], "tasting-bar/menus/test/SEWC-Wine_Menu.pdf");
move_uploaded_file($_FILES["food_flight_menu_upload"]["tmp_name"], "tasting-bar/menus/test/SEWC-Food_Flight_Menu.pdf");
echo "Menus uploaded successfully!"; }
}
else
{
echo "Invalid file type. Must be a PDF and under 5MB. Sorry!<br/>";
echo "File Type - " . $_FILES["wine_list_menu_upload"]["type"] . "<br/>";
echo "File Name - " . $_FILES["wine_list_menu_upload"]["name"];
}
?>
I need to get "wine_list_menu_upload" renamed to "SEWC-Wine_Menu.pdf" and into "tasting-bar/menus/" and
"food_flight_menu_upload" renamed to "SEWC-Food_Flight_Menu.pdf" and into "tasting-bar/menus/"
What am I doing wrong?

try adding these lines just before move_uploaded_file
chmod('tasting-bar/', 0777);
chmod('tasting-bar/menus', 0777);
chmod('tasting-bar/menus/test/', 0777);
if its permission issue, it should solve with this

Related

PHP File Uploading Issue

I'm currently developing a website where users can upload their music. You can set various genres to display. Now, the problem is that sometimes (no idea why) the upload fails for certain files. An error doesnt get displayed. It's definitely not a permission error, since the uploading works for most files.
I've looked around a lot here already and tried many things, but nothing worked for me.
Here's my code:
HTML
<form method="post" action="musicupload.php" enctype="multipart/form-data">
Choose an MP3 or WAV file<file></file>
<br /><br />
<input type="file" name="fileToUpload" id="fileToUpload" required>
<br /><br />
<fieldset>
Genre
<br />
<input type="radio" id="db" name="Genre" value="Dubstep" required checked>
<label for="db"> Dubstep</label>
<input type="radio" id="trap" name="Genre" value="Trap" required>
<label for="trap"> Trap</label>
<input type="radio" id="BB" name="Genre" value="Bass Boosted" required>
<label for="bb"> Bass Boosted</label>
<input type="radio" id="other" name="Genre" value="Other" required>
<label for="other"> Other</label>
</fieldset>
<br />
<input type="submit" value="Upload Song" name="submit">
</form>
PHP
<?php
/**
* Created by IntelliJ IDEA.
* User: Marc
* Date: 04.12.2017
* Time: 20:07
*/
require 'db.php';
$target_dir = "uploadedmusic/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$filename=$_FILES["fileToUpload"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$genre = $_POST["Genre"];
$successfull = false;
if(isset($_POST["submit"])) {
// Check extensions
if ($ext != "mp3" && $ext != "wav") {
echo "Sorry, only MP3 & WAV files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$hash = md5_file("uploadedmusic/".$filename);
//echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
$sql = "INSERT INTO `music` (`id`, `filename`, `genre`, `uploaded`, `hash`) VALUES (NULL, '$filename', '$genre', CURRENT_TIMESTAMP, '$hash')";
$conn->query($sql);
$successfull = true;
} else {
$successfull = false;
}
}
}
?>
<html>
<head>
<title>Upload Music</title>
</head>
<body>
<div style="text-align: center;">
<img src="logo.png">
<h1>Please wait...</h1>
<p style="font-size: 35px;">
<?php
if ($successfull == true) {
echo "Successfully uploaded ". basename($_FILES["fileToUpload"]["name"])."! Use the search to find it!";
}
else {
echo "Sorry, there was an error uploading your file. Check for potential invalid characters like () or - in your filename!";
}
?>
</p>
<a style="font-size: 35px" href="main.php">Start listening!</a>
</div>
</body>
</html>
You need to see file upload errors to find the exact issue.
echo $_FILES["fileToUpload"]["error"] // this will give you the error code.
Possible errors are. check this link http://php.net/manual/en/features.file-upload.errors.php
$phpFileUploadErrors = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
Also in your code apart from checking extension, you need add condition to check upload errors
if ($uploadOk == 0 || $_FILES["fileToUpload"]["error"]!== UPLOAD_ERR_OK) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}

Issue with updating image info on MYSQL database using PHP

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>

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>";
}
}
?>

Troubleshooting file upload error code 4

I am trying to upload multiple files to my server. If I try to upload a single file, it works fine. but if I try more than one, it gives me an error code 4, even though it does print the name of all the files correctly. Nothing is uploaded. I have the input type set correctly. Can someone help me?
Choose Image: <input name="uploadedfile[]" type="file" multiple="true"/><br /><br /><br />
<input type="submit" value="Upload Image!" style="margin-left:100px;"/>
Below is the code:
$i=0;
foreach($_FILES['uploadedfile']['name'] as $f)
{
$file['name'] = $_FILES['uploadedfile']['name'][$i];
$file['type'] = $_FILES['uploadedfile']['type'][$i];
$file['tmp_name'] = $_FILES['uploadedfile']['tmp_name'][$i];
$file['error'] = $_FILES['uploadedfile']['error'][$i];
$file['size'] = $_FILES['uploadedfile']['size'][$i];
if ($file["error"] > 0)
{
echo "Error Code: " . $file["error"];
}
$target_path = "uploads/".basename($file["name"]);
if(move_uploaded_file($file["tmp_name"], $target_path))
{
echo basename($file['name'])."<br />";
echo basename($file['tmp_name'])."<br />";
echo $target_path;
} else{
echo "There was an error uploading the file, please try again!";
}
$i++;
}
and my HTML form
<div id="album_slider">
<div style="text-align:center;margin:20px auto;font-size:27px;">Upload Image</div>
<br style="clear:both;font-size:0;line-height:0;height:0;"/>
<div style="width:700px;margin:auto;height:250px;text-align:left;">
<form enctype="multipart/form-data" action="uploader.php" method="POST" name="form">
Image Name: <input type="text" name="image_name" id="image_name"/><br /><br /><br />
<input type="hidden" name="a_id" id="a_id" value="<?php echo $a_id; ?>"/>
Choose Image: <input name="uploadedfile[]" type="file" multiple="true"/><br /><br /><br />
<input type="submit" value="Upload Image!" style="margin-left:100px;"/>
</form>
</div>
<br style="clear:both;font-size:0;line-height:0;height:1px;"/>
</div>
Try:
foreach ($_FILES["uploadedfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo "$error_codes[$error]";
move_uploaded_file(
$_FILES["uploadedfile"]["tmp_name"][$key],
$target_path
) or die("Problems with upload");
}
}
Well its going to fail as you want to upload MULTIPLE files, but your code is only designed to handle 1 single file.
Go ahead and read through how to handle multiple files here:
http://php.net/manual/en/features.file-upload.multiple.php
Use the condition check like below code
if(isset($_FILES["qImage"]) && !empty($_FILES["qImage"]["name"])){
$imgSubQuestion = $_FILES["qImage"];
}
if(isset($_FILES["sImage"]) && !empty($_FILES["sImage"]["name"])){
$imgSolution = $_FILES["sImage"];
}

PHP File upload form not working

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.

Categories