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/';
Related
I have a problem loading the file to the server in PHP and HTML using move_uploaded_file () when I put PHP files in this way http://mydomin.com/uploadfile.php succeed the process and if this way http://mydomin.com/uploadfiles/uploadfile.php The the process fails
code php
<?php
if (isset($_FILES['image'])) {
$idApp = uniqid();
$uploadDir = '../images/';
$uploadedFile = $uploadDir . $idApp . ".jpg";
if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadedFile)) {
echo"Success: ".$_FILES['image']['tmp_name']. $uploadedFile;
} else {
echo"error 2";
}
} else {
echo"error 3";
}
?>
code html
<form action="add.php" method="POST" enctype="multipart/form-data">
<input type='file' name='image' id='image'>
<div align='center''><input type='submit' id='myButton' value='add'></div>";
</form>
check your upload path
$uploadDir = '../images/';
Try to use this path './images/' or best use absolute path.
check your script location by using
var_dump(__DIR__)
this will show you where is your .php file is ( also called as absolute path ). Thus simply you can see where you made a mistake to assign a folder for file uploading(image in your case ).
I'm having a little trouble with this. Thought it'd be easier, but turning out to frustrate. All I'm trying to do is have a text field where I can type the name of a new directory, check if that directory exists, and if not create it. I have found about 50 other people with almost the exact same code, so thought I had it correct but I keep getting Directory exists as per the "if" statement.
Eventually I want to tie this into my file upload script.
Here is the insert.php
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="directory">Directory:</label>
<input value="<?php if ($_POST && $errors) {
echo htmlentities($_POST['directory'], ENT_COMPAT, 'UTF-8');
}?>" type="text" name="directory" id="directory" />
</p>
<p>
<input type="submit" name="insert" id="insert" value="insert" />
</p>
</form>
And here is the post.php
try {
if (isset($_POST['insert'])) {
$directory = $_POST['directory'];
$photo_destination = 'image_upload/';
$path = $photo_destination;
$new_path = $path . $directory;
$mode = 0755;
if(!is_dir($new_path)) {
echo "The Directory {$new_path} exists";
} else {
mkdir($new_path , 0777);
echo "The Directory {$new_path} was created";
}
}
}
Change this :
if(!is_dir($new_path)) {
echo "The Directory {$new_path} exists";
}
to this :
if(is_dir($new_path)) {
echo "The Directory {$new_path} exists";
}
Try and tell me the result :)
Instead of using is_dir in the if block you can use file_exists. Because file_exists is the function to check whether file exists or not. For the same you can also refer to http://php.net/manual/en/function.file-exists.php
Try
if( is_dir( $new_path ) ) {
echo "The Directory {$new_path} exists";
}
Let someone wants to create a sub-folder,
with a year name under /uploads folderthen he/she want to create
another sub-folder under an /uploads/<year_name_folder>/,
named project_number.
$yearfolder = date('y');
if (!file_exists('uploads/'.$yearfolder)) {
mkdir("uploads/".$yearfolder);
}
*// Folder named by year has been created.*
$project_number = Any Unique field ,Come from database or anywhere !
$target_directory = mkdir("uploads/".$yearfolder."/".$project_number);
*// project number wise folder also created.
// If project number is not unique do check like year folder. I think every project number is unique.*
$target_dir = "uploads/$yearfolder/$project_number/";
*//my target dir has created where my document or pic whatever will be uploaded.*
Now Upload ! Woo
$target_file = $target_dir.($_FILES["file"]["name"]);
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
I need customers to upload files to my website and I want to gather their name or company name and attach it to the file name or create a folder on the server with that as the name so we can keep the files organized. Using PHP to upload file
PHP:>>
if(isset($_POST['submit'])){
$target = "upload/";
$file_name = $_FILES['file']['name'];
$tmp_dir = $_FILES ['file']['tmp_name'];
try{
if(!preg_match('/(jpe?g|psd|ai|eps|zip|rar|tif?f|pdf)$/i', $file_name))
{
throw new Exception("Wrong File Type");
exit;
}
move_uploaded_file($tmp_dir, $target . $file_name);
$status = true;
}
catch (Exception $e)
{
$fail = true;
}
}
Other PHPw/form:>>
<form enctype="multipart/form-data" action="" method="post">
input type="hidden" name="MAX_FILE_SIZE" value="1073741824" />
label for="file">Choose File to Upload </label> <br />input name="file" type="file" id="file" size="50" maxlength="50" /><br />
input type="submit" name="submit" value="Upload" />
php
if(isset($status)) {
$yay = "alert-success";
echo "<div class=\"$yay\">
<br/>
<h2>Thank You!</h2>
<p>File Upload Successful!</p></div>";
}
if(isset($fail)) {
$boo = "alert-error";
echo "<div class=\"$boo\">
<br/>
<h2>Sorry...</h2>
<p>There was a problem uploading the file.</p><br/><p>Please make sure that you are trying to upload a file that is less than 50mb and an acceptable file type.</p></div>";
}
Look at mkdir(), assuming the user PHP is running as has appropriate permissions, you can simply make a directory inside of uploads/.
After that, you can modify $file_name to contain some of the other posted variables that you mentioned you will add. Just take care to ensure those variables contain only expected characters.
Do your customers need to Log into your site before they upload? If that's the case perhaps you can store/grab $_SESSION information regarding their company and name. You could then append that info to the $file_name or the $target directory.
the mkdir() idea below this looks like it will probably work, but have you considered what would happen if a user entered someone else's name, had someone else's name, or entered someone else's company?
use this code on the top of the page
$path = dirname( __FILE__ );
$slash = '/';
(stristr( $path, $slash )) ? '' : $slash = '\\';
define( 'BASE_DIR', $path . $slash );
& use below code after inside if below exit;}
$folder = $file_name; // folder name
$dirPath = BASE_DIR . $folder; // folder path
$target = #mkdir( $dirPath, 0777 );
move_uploaded_file($tmp_dir, $target . $file_name);
here is your code as it is
I figured it out, I just made a input for the name ant attached it to the file name.
This is the PHP code used for the upload:
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
} else { echo "Error"; }
When I test the script, it says "The file has been uploaded successfully." but when I check the FTP server, it hasn't really...
Also, if you need to know, here's the HTML codes:
Form tag:
<form name="profilestyle" action="account.php?action=profiletheme" method="post" enctype="multipart/form-data">
Input tag:
<input type="file" name="bgimage" />
Extra Information:
Yes, I remembered the CHMod the uploads directory
Odd, the code looks fine as far as I can see.
Can you use file_exists() to check whether the file exists, but maybe is not visible to your FTP user?
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file '$upload' has been uploaded successfully.";
if (file_exists($upload)) echo "And it exists! It is ".filesize($upload)." bytes big.";
else echo "But it doesn't exist.";
} else { echo "Error"; }
You also need to check $_FILES['bgimage']['error'] to make sure it is equal to UPLOAD_ERR_OK and is not an error code.
Please try the following test code
$upload = "uploads/";
$upload = $upload . basename($_FILES['bgimage']['name']);
sprintf('<pre>Debug: moving file from %s to %s</pre>',
$_FILES['bgimage']['tmp_name'],
$upload
);
if (move_uploaded_file($_FILES['bgimage']['tmp_name'], $upload)) {
echo "The file has been uploaded successfully.";
sprintf('<pre>Debug: realpath=%s, filesize=%d</pre>',
realpath($upload),
filesize($upload)
);
}
else {
echo "Error";
}
and esp. keep an eye on the realpath=xyz output.