PHP File upload form not working - php

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.

Related

PHP Upload system not moving file from temp to specified directory

So I've tried to create a basic PHP/MySQL picture upload system using the W3Schools example as a reference, however I cannot for the life of me work out why the uploaded file is not being copied to the destination specified.
Here is my PHP code:
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$uploads_dir = 'img/houses';
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
$uploads_dir . $_FILES["file"]["name"]);
echo "Stored in: " . $uploads_dir . $_FILES["file"]["name"];
}
} else {
echo "Invalid file";
}
And here is the HTML upload form:
<form action="uploadHousePic.php" method="post" enctype="multipart/form-data">
Image: <input type="file" name="file" id="file"/>
<br><br>
Price: £ <input type="text" name="Price">
<br><br>
Type of house: <input type="text" name="Type">
<br><br>
Location: <input type="text" name="Location">
<br><br>
Description: <textarea rows="6" cols="60" input type="text" name="Description"></textarea>
<br><br>
<input type="submit" value="Submit" />
</form>
Finally, I have the destination code on another php page where the picture + info will be inserted:
<?php
// this is used to connect to the database on the mysql server called houselist
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();// if there is a problem with the connection and it can't connect it will display this error to the user.
}
$result = mysqli_query($con,"SELECT * FROM tbl_house_info");//this setups the query to be used in order to gather the data to be displayed on the page. it will select all the data from the tbl_house_page.
while($row = mysqli_fetch_array($result)) {//this then will run a loop and fetch all the results from the database in an array and display them in order row by row.
echo '<div class="housepost">';//this is used to add the format of the web page that was used.
echo '<img src="img/houses/', $row['Image'],'" width="270px" height="190px" alt="" />';// this line adds the image to the div and adds in the destination of the image, the image will have been placed here from the upload and now adding in the file name from the database it will display the full image on the page.
echo '<h2>' , '£' ,$row['Price'] , '</h2>' , '<p>'. $row['Type'] , '</p>' , '<p>' . $row['Location'] , '</p>' , '<p>' , $row['Description'] , '</p>';// this will then add some more formatting as well as displaying the other columns of data which are the price, type, location and destination on the web page to the user.
echo "</div>";
}
?>
Any help would be greatly appreciated. This is for a College project that I am working on, so I wanted to try and figure it out for myself; but when both you and your teacher cannot find the problem something is wrong...
Thanks :)
Check if max file size and max post size in php.ini are big enough! :)
file_uploads = On
upload_max_filesize = xxxM
post_max_size = xxxM
For 70% it's bad config.
EDIT: Restart server (Xampp, apache, wampp or any other) :)
Change your path from $uploads_dir = 'img/houses'; to $uploads_dir = 'img/houses/';
Also check whether you have the write privileges for this directory.
You can also use is_writable() function to check whether writable.
Refer http://www.php.net/manual/en/function.is-writable.php

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

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

Can not connect to FTP when php on remote server, but connects when php is on localhost

I am pretty new to php, just learning how to upload to server via ftp.
I have a file for connecting to ftp, it displays no error when it is on my localhost, but when i upload the file onto the remote server, it gave me an error straight away that it can't connect to server(would it be because they are the same server?) . At the moment it is displaying, Cannot connect to host
And this is my first time doing FTP in php, so i hope my mistakes aren't too stupid.
P.S. This is just for testing, so i will figure out the SQL injection issue later on with sqli_real_escape string.
As i am also trying to do a form that upload images onto the remote server via ftp_put. But it is not working at the moment. But giving me an error Warning: ftp_put() expects parameter 1 to be resource, boolean given in Please give me some direction to why my errors are occurring.
Thanks for your time, thanks!
Agentftpconnect.php
<?php
$ftp_user_name='name';
$ftp_user_pass='pass';
$connection = 'testing.info';
$ftpconn_id = ftp_connect($connection) or die ("Cannot connect to host");
$login = ftp_login($ftpconn_id, $ftp_user_name, $ftp_user_pass);
if (!$ftpconn_id)
{die ("FTP connection has encountered an error!");}
if (!$login)
{die ("But failed at login Attempted to connect to $connection for user $ftp_user_name....");}
?>
Submitform.php
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
include 'Agentftpconnect.php';
if ($_POST)
{
//get form data
$Listingname = addslashes(strip_tags($_POST['Listingname']));
$Location = addslashes(strip_tags($_POST['Location']));
$nobed = addslashes(strip_tags($_POST['nobed']));
$zip = addslashes(strip_tags($_POST['zip']));
$price = ($_POST['price']);
if (!$Listingname||!$nobed||!$Location||!$zip||!$price)
die ("Please fill out all fields");
else
for($i=0;$i<3;$i++)
{
if ((($_FILES["file"]["type"][$i] !== "image/gif")
|| ($_FILES["file"]["type"][$i] !== "image/jpeg")
|| ($_FILES["file"]["type"][$i] !== "image/jpg")
|| ($_FILES["file"]["type"][$i] !== "image/pjpeg")
|| ($_FILES["file"]["type"][$i] !== "image/x-png")
|| ($_FILES["file"]["type"][$i] !== "image/png"))
&& ($_FILES["file"]["size"][$i] > 400000))
die("File is not correct");
else{
if ($_FILES["file"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"][$i] . "<br>";
echo "Size: " . ($_FILES["file"]["size"][$i] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"][$i] . "<br>";
echo "<br>";
if (file_exists("rentaid.info/rent" . $_FILES["file"]["name"][$i]))
{
die($_FILES["file"]["name"][$i] . " already exists please add another file, or change the name ");
}
else
{
$photo=$_FILES["file"]["name"][$i];
ftp_put($login,"rentaid.info/rent/$photo",$_FILES["file"]["tmp_name"][$i],FTP_ASCII);
echo "Stored in: " . "rentaid.info/rent/" . $_FILES["file"]["name"][$i];
}
}
}
}
{
$photo0=$_FILES["file"]["name"][0];
$photo1=$_FILES["file"]["name"][1];
$photo2=$_FILES["file"]["name"][2];
$username=$_SESSION['username'];
//register into database
mysqli_query($con,"INSERT INTO Listing (username,Listingname,Location,nobed,zip,price,pic1,pic2,pic3) VALUES
('$username','$Listingname','$Location','$nobed','$zip','$price','$photo0','$photo1','$photo2');") or die(mysqli_error());
echo "Listing Added";
}
}
else
{
?>
<form action="Submitlisting8.php" method="post"
enctype="multipart/form-data">
Listing Name:<br />
<input type='text' name='Listingname'><p />
Location:<br />
<input type='text' name='Location'><p />
Number of Beds:<br />
<input type='test' name='nobed'><p />
Zip:<br />
<input type='text' name='zip'><p />
Price:<br />
<input type='text' name='price'><p />
<label for="file">Pic1(File must be exceed 4mb):</label>
<input type="file" name="file[]" id="file[]"><br>
<label for="file">Pic2(File must be exceed 4mb):</label>
<input type="file" name="file[]" id="file[]"><br>
<label for="file">Pic3(File must be exceed 4mb):</label>
<input type="file" name="file[]" id="file[]"><br>
<br>
<input type='submit' name='submit' value='Submit'>
</form>
<FORM METHOD="LINK" ACTION="agentaccount.php">
<INPUT TYPE="submit" VALUE="Back to Account">
</form>
<?php
}
?>

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

Categories