How To Upload two files in PHP - php

I'm trying to upload two file in one submit button using the following code:
<label>Logo Image *</label>
<input type="file" name="ufile[]"/>
<label>Banner Image *</label>
<input type="file" name="ufile[]"/>
PHP
$logo = $_FILES['ufile']['name'][0];
$block_img = $_FILES['ufile']['name'][1];
if ($_FILES['ufile']['name']["error"] > 0) {
echo "error<br>";
}
else {
if (file_exists("small-image/" . $_FILES['ufile']['name'][0])){
echo $_FILES['ufile']['name'][1] . "File already exists in server. ";
}
else {
move_uploaded_file($_FILES['ufile']['name'][0], "small-image/" . $_FILES['ufile']['name'][0]);
move_uploaded_file($_FILES['ufile']['name'][1], "small-image/" . $_FILES['ufile']['name'][1]);
}
}
$sql_query = "UPDATE header_img SET logo_img = '$logo', block_img = '$block_img' WHERE banner_id = 1";
My database is updating correctly but the file is not uploaded. Yes there is a 777 directory call 'small-image'.
Any idea?
Thanks.

When you use move_uploaded_file, you want to use $_FILES['ufile']['tmp_name'], that's where the file is currently located.
move_uploaded_file($_FILES['ufile']['tmp_name'][0], "small-image/" . $_FILES['ufile']['name'][0]);
move_uploaded_file($_FILES['ufile']['tmp_name'][1], "small-image/" . $_FILES['ufile']['name'][1]);
Check the example in the docs: http://php.net/manual/en/function.move-uploaded-file.php

Related

Upload file path no display

I have a problem with uploading path in my sql database. Not displaying all path.
This is the php code:
$rd2 = mt_rand(1000, 9999) . "_File";
if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0))
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"));
$newname = "uploads/" . $rd2 . "_" . $filename;
if (!file_exists($newname));
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newname)));
$query = "insert into files (file_id,floc,subid,fname,fdesc,tcid)
values ($newstd,'$newname',
'".htmlspecialchars($_REQUEST['subid'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fname'], ENT_QUOTES)."',
'".htmlspecialchars($_REQUEST['fdesc'], ENT_QUOTES)."',
'".$_SESSION['tcid']."')";
if (!#executeQuery($query)) {
if (mysql_errno () == 1062) //duplicate value
$_GLOBALS['message'] = "Given Subject Name voilates some constraints,
please try with some other name.";
else
$_GLOBALS['message'] = mysql_error ();
}
else
$_GLOBALS['message'] = "Successfully New Subject is Created.";
}
closedb();
The code is working and shows like this in database: http://i.stack.imgur.com/Z5jmb.png
It suppose to display uploads/2654_File_filename.docx
And the file is not uploaded.
The form is in a table:
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
</tr>
I used this:http://www.w3schools.com/php/php_file_upload.asp but same no working
I'm using xampp 5.6.8 and php.ini and file_uploads directive is set to On.
EDIT - newstd is:
$result = executeQuery("select max(file_id) as fid from files");
$r = mysql_fetch_array($result);
if (is_null($r['fid']))
$newstd = 1;
else
$newstd=$r['fid'] + 1;
$result = executeQuery("select fname as fid from files where
fname='" . htmlspecialchars($_REQUEST['fname'], ENT_QUOTES) . "'
and tcid=" . $_SESSION['tcid'] . ";");
// $_GLOBALS['message']=$newstd;
if (empty($_REQUEST['fname']) || empty($_REQUEST['fdesc'])) {
$_GLOBALS['message'] = "Some of the required Fields are Empty";
} else if (mysql_num_rows($result) > 0) {
$_GLOBALS['message'] = "Sorry Subject Already Exists.";
} else {
}
$rd2 = mt_rand(1000, 9999) . "_File";
...
...
EDIT: I forgot to mention that when i dont use a path he upload it in database.
I had a "global" form and i putted enctype="multipart/form-data" in it and it worked with saving the path in table.
Before was in form below and dont recognise it.
<tr>
<td> File</td>
<td>
<form action="cursuri.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file" id="uploaded_file"></form>
</td>
But still no uploading files...
Can you check if the file is not too large and exceeds the limitations of these two configurations:
post_max_size
upload_max_filesize
You can see the values from a file with:
<?php
phpinfo();
?>
Edit:
Another suggestion is to put the body brackets of the if's because the single line execution if the statement is valid, cant be trusted. I think the problem can be the :
if (!file_exists($newname));
Also the way you insert into the DB you take the name from the $_REQUEST and not the new name and where do you store the path ?

Name cannot be updated and picture is deleted after editing

I have two problems:
Name cannot be updated
Profile picture is deleted (the exist one) even though I did not upload a new one. I have no problem in uploading image though.
Below is the code
if(isset($_POST['submit'])){
$target_dir = "images/staff/";
$target_dir = $target_dir . basename($_FILES["new_profilepicture"]["name"]);
$uploadOk=1;
if (file_exists($target_dir . $_FILES["new_profilepicture"]["name"])) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
$imageup = $target_dir;
echo "<img src='" . $imageup . "' />";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$_var1 = $_POST['new_name'];
$_var2 = $_POST['new_email'];
$_var3 = $_POST['new_password'];
$_var4 = $_POST['new_contactno'];
$_var5 = $_POST['new_icno'];
$_var6 = $_POST['new_address'];
$_var7 = $_POST['new_status'];
$_var8 = $imageup;
$query1 = "UPDATE staff
SET StaffName='$_var1', StaffEmail='$_var2', StaffPassword='$_var3', StaffContactNo='$_var4', StaffICNo='$_var5', StaffAddress='$_var6', StaffStatus='$_var7', StaffProfilePicture='$_var8'
WHERE StaffID='$staffID'";
$success = mysql_query($query1);//is mysql query working?
if($success){
$oldprofilepicture = $staff['StaffProfilePicture'];
if(file_exists($oldprofilepicture)){
unlink($oldprofilepicture);//delete now
}
header('location:staff_profile.php');
}
}
Below is the line where a new name is entered.
<tr>
<td width="170">Full Name:</td>
<td><input type="text" name="new_name" size="30" value="<?php echo $staffname ?>" /></td>
</tr>
Regarding the image, create a hidden input field with the same value as from the database, e.g.:
<input type="hidden" value="/path/to/img.ext" name="old-image" />
Before this line:
if (move_uploaded_file($_FILES["new_profilepicture"]["tmp_name"], $target_dir)) {
Add:
$imageup = $_POST['old-image'];
Of course you need to do validation on the $_POST data. I've left it out of the above example.
This will set the default value for the image as the saved version. If you upload a new image, then that will override $imageup with the name path details :)
Regarding the name not changing, I cannot see where the value for $staffId is being set?

php image upload checking size of photo uploaded not working

<?php
include 'dbconnect.php';
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=1;
$name=$_POST['name'];
$champname=$_POST['champname'];
$cat=$_POST['category'];
$username=$_POST['username'];
$pic=($_FILES['photo']['name']);
if ($photo_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
mysql_query("INSERT INTO `submissions` VALUES ('$fake','$name','$champname', '$cat', '$username', '$pic')") ;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been succesfully uploaded to return click below.";
echo '<a href='';
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
My add.php
bottom of my form which triggers the php above:
Username: <input type="text" name = "username"><br>
Image: <input name="photo" type="file"><br>
<input type="submit" value="Add">
</form>
Im uploading images over 350kb and it's not stopping them from being uploaded.
I need to also get image formats & changing the name when uploaded and checking for duplicates but need this working first.
There were a few issues with your code.
This was breaking your code echo '<a href=''; a missing quote which should rather look like:
echo "<a href='page.php'>Click here</a>";
$photo_size was a stray variable, that has now been assigned, read further down for more details.
You should specify which column(s) should receive which VALUES, which I changed.
Using if ($photo_size > 350000) to check for a file size is not the correct method to use.
Use:
$photo_size=$_FILES["photo"]["size"]; if ($photo_size > 350000){...}
I am unsure as to how you're using these $ok=0; and $ok=1; see comments in code.
You have some missing variables for your DB insertion.
The following using mysqli_* based functions worked for me, where I am using the entire code inside one file; you can change it to suit.
Sidenotes: There are comments throughout the code for you to read also.
I added an exit; for echo "Your file is too large.<br>"; otherwise the code will continue executing.
Here is the full code: (which I tested and working on my server)
<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$mysqli = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
if(isset($_POST['submit'])){
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=1; // I don't know what you're using this for.
// modify to suit
$fake=mysqli_real_escape_string($mysqli,$_POST['fake']);
$name=mysqli_real_escape_string($mysqli,$_POST['name']);
$champname=mysqli_real_escape_string($mysqli,$_POST['champname']);
$cat=mysqli_real_escape_string($mysqli,$_POST['category']);
$username=mysqli_real_escape_string($mysqli,$_POST['username']);
$pic=($_FILES['photo']['name']);
$photo_size=$_FILES["photo"]["size"];
if ($photo_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0; // I don't know what you're using this for.
echo "<a href='upload.php'>Click here to try again.</a>";
exit;
}
mysqli_query($mysqli,"INSERT INTO `submissions` (fake, name, champname, cat, username, pic) VALUES ('$fake','$name','$champname', '$cat', '$username', '$pic')");
if($mysqli != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been succesfully uploaded to return click below.";
// I don't know what you want to do here, but it's not correct. There's a missing quote.
// echo '<a href='';
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
} // if(isset($_POST['submit'])){
?>
<form action="" method="post" enctype='multipart/form-data'>
Name: <input type="text" name = "name"><br>
Username: <input type="text" name = "username"><br>
Champ name: <input type="text" name = "champname"><br>
Category: <input type="text" name = "category"><br>
Fake: <input type="text" name = "fake"><br>
Image: <input name="photo" type="file"><br>
<input type="submit" value="Add" name="submit">
</form>
"I need to also get image formats & changing the name when uploaded and checking for duplicates but need this working first."
You can open a new question after this one. I believe my answer has covered the overlying issues with your original question.
you might have to double check your http.conf file that is bundled with your wamp server, check your upload limit

move_uploaded_file() showing successful but not working

I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';

upload image in php by its url

i have this form to upload images:
<form method="post" action="upld.php" name="insertForm" enctype="multipart/form-data">
Image name:<br />
<input type="text" name="iname" /><br />
<input type="file" name="file" />
<input type="submit" name="upload" value="Upload" />
</form>
and here is the upld.php
<?php
$db_name = "DB_name";
$table_name = "tble";
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = mysql_select_db($db_name, $connection) or die(mysql_error());
if(isset($_POST['upload'])){
if (($_FILES["file"]["error"] > 0))
{
echo "<h3> Error in File! </h3>";
}
else
{
if ((file_exists("images/" . $_FILES["file"]["name"])) )
{
echo "<h3> file not exsists!</h3>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
//$id=mysql_insert_id();
$time=strftime("%Y-%m-%d %H:%M:%S", time());
$img_name=$_POST['iname'];
$img=$_FILES["file"]["name"];
$sql="INSERT INTO $table_name VALUES('{$img}','{$time}','{$img_name}')";
$result=mysql_query($sql,$connection);
mysql_close($connection);
echo "<h3>uploaded successfully</h3>";
}
}
}
echo "<br><br><a href='GalleryAdmin.php'>GO back to Admin Gallery</a>
";
?>
the problem is:
when i run it always say me file not exsist, acording to this if
if ((file_exists("images/" . $_FILES["file"]["name"])) )
{
echo "<h3> file not exsists!</h3>";
i have the images folder with upld.php in the same folder
what would you guess is the problem?
I think you have a slight logical error
file_exists("images/" . $_FILES["file"]["name"])
Will return true if the file exists in the images folder (my guess would me if somebody already uploaded it). But, based on your log statement, what you want is
!file_exists("images/" . $_FILES["file"]["name"])
OK so you uploaded your file. But, what you checked was if it was in say "images/my.jpg". At this point its in tmp_name, in your tmp directory, most likely so, no it would always not exist at this point as the file is only in a temporary name, you need to check its in your temp location, move it, and then check if its in images surely?
First:
PHP uploads the file to a temp directory. This is the file you need to move to your images/ folder. You find the file in this location on your server:
$_FILES['file']['tmp_name']
This is the file on which you want to run file_exists to make sure the upload completed successfully. So:
if (file_exists($_FILES['file']['tmp_name']) {
// File upload successful. Now move file to your directory.
move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]);
// Now do the database stuff here.
// ...
} else {
// Nothing was uploaded and something is wrong!
}
Secondary:
Your code
file_exists("images/" . $_FILES["file"]["name"])
will return TRUE, and therefore (in your code) it will say that there are no file. That's a logical error on your part.
Try:
!file_exists("images/" . $_FILES["file"]["name"])
instead.
Third:
Make sure that the file to which you move the file (images/) have the proper chmod. It needs 775 for it to be possible to create files into. This is made via the ftp program.
Read more here: CHMOD tutorial
You will also need to move the file from the tmp dir to images before checking if it's there with file_exists.
Please use move_uploaded_file before you check if the file exists;)
Otherwise try this:
1.) error_reporting(E_ALL);
2.) chmod the images directory (775), right mouse click on directory

Categories