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
Related
I am learning PHP through w3schools and the upload file php code does not seem to work. At first, there are warning shown that said "unable to open stream" but as I refreshed multiple times (trying to debug) the warning stopped showing but it still failed to upload the file.
Thus I decided to simplify the code (omitting all the features) and focus on uploading only. Some basic information, I am using an apache server on my localhost device. Below are the simplified code
<html>
<head><title>File upload test page</title></head>
<body>
<form action="upload_test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadedfile">
<input type="submit" value="Upload File">
</form>
</body>
</html>
<?php
$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]["name"])). " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file. <br>";
}
?>
The error keeps persisting. I am very new to php so any help would be much appreciated. Thank you!
"unable to open stream", means process user of apache have no write permission for dir "uploads/", try to change user of "uploads/" (such as "chown apache.apache uploads") or change permission of the dir (such as "chmod 777 uploads"). And if u can not get useful message next time, try this to catch exception maybe u can get
some useful messages
<?php
$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);
try{
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]. ["name"])). " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file. <br>";
}
}catch(Exception $e){
var_dump($e->getMessage());
}
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 have a script that uploads some files through php's move_uploaded_file().
Tested on my localhost it works fine. The problem arises when trying to do the same thing on a host. I already red all the topics in that matter here - but none of them solved my problem.
CODE:
<?php
$folder = 'img';
if (isset($_FILES['test'])) {
if (is_writable($folder))
echo 'Writable';
else
echo 'IMG is not writable';
$tmp_name = $_FILES['test']['tmp_name'];
$name = $_FILES['test']['name'];
if (move_uploaded_file($tmp_name, $folder . '/' . $name)) {
echo 'File was uploaded';
}
else {
echo 'File was not uploaded';
}
}
else {
echo 'No file - no operation';
}
?>
<html>
<body>
<form action="" enctype="multipart/form-data" method="POST">
<input type="file" name="test" />
<input type="submit" value="Test" />
</form>
</body>
</html>
MESSAGE is as follows:
Writable
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\php9E75.tmp' to 'img/20130113_114901.jpg' in F:\hshome\ctc-ultralife\ultralife.com\new\admin\index_files\function\test2.php on line 11
File was not uploaded
Folder seems writable. Even if the file is not uploaded, it is created with the specified name in the folder (even if it is an empty file).
I do not know the absolute path of the server - it is not mine.
Your help will be much appreciated.
Thanks in advance.
Warning: complete stab in the dark. I don't know if this is the case, as I don't work on Windows servers.
It may be that the / needs to be a \. I don't think Windows handles the slash being the other way. That would explain why it can find your directory, but not the file within it.
I think you have to give an absolute path to the move_uploaded_file function.
EDIT:
If you don't know the absolute path, you can use the __DIR__ constant to make up an absolute path.
Assuming you've the img folder in the function folder, you can write something like this:
$fullPath = __DIR__ . '/img/' . $name;
if (move_uploaded_file($tmp_name, $fullPath)) {
echo 'File was uploaded';
} else { // ... }
In order to understand the real problem, you've to look into the error log.
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/';
I have set up a php script which creates a directory and uploads a file to that directory. My issue is that when I use the script to create the directory, the file will not upload entirely. I ran the exact same script on a different host and the upload process works just fine. Plus, if I manually create the upload directory and apply chmod 777 via ftp then the transfer works just fine. Could there be some sort of a setting with the hosting provider that needs to be altered to allow the function to work just right?
Here is the upload form:
<form action="/uploadFile.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<input type="hidden" name="id" value="newDirectory" />
<input type="submit" name="submit" value="Upload Flyer" />
</form>
Here is my PHP script (uploadFile.php):
$thisdir = getcwd();
$new_dir = $_POST['id'];
$full_dir = $thisdir . "/upload/" . $new_dir;
function chk_dir($full_dir) {
if(is_dir($full_dir)) {
echo 'welcome back';
} else {
return mkdir($full_dir);
}
}
chk_dir($full_dir);
chmod($full_dir, 0777);
?>
<?php
//upload image
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
}
//set image restrictions
?>
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Please only upload an image for previewing (jpg or gif)...<br>
Also, check to make sure the filesize is less than 8MB" . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
//check the image into new directory
if (file_exists("upload/". $new_dir ."/". $_FILES["img_preview"]["name"]))
{
echo "It seems that " . $_FILES["img_preview"]["name"] . " already exists.";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"]);
echo "image file has transferred successfully!";
}
}
}
else
{
echo "Invalid file please contact for assistance.";
}
?>
Also, when I run the script no errors are produced and the file echos "image file has transferred successfully!" but then when I check for the file in the new location it is completely void. Thank you for your time in this issue.
First of all, your script has a security hole. Never use passed $_POST data to create system directories. And never use 0777 for anything.
The move_uploaded_file() returns false on a failure and you would still get your success message even if it failed (in your code)
Turn on display_errors and error logging and try again.
Looks like your question already contains the answer(the upload works when you create the directory via FTP).
I guess the new server has safe_mode enabled, so it will check the UID of the fileowners on file-operations.
What happens:
your script creates a directory, owner will be the webserver
your script(owner of the script usually is the ftp-user) tries to chmod the directory
the script(owner:ftp) cannot chmod the directory(owner:webserver) , because the UIDs are different.
solution: use ftp_mkdir() for creation of directories.
you have used move_uploaded_file() independently. If it returns false then also sucsess message will be printed.
Try
if ( move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"])) {
echo "sucess";
}else{
echo "fail";
}
After that you will get what is the main problem. Also use debugging point by
print_r($_FILES) before move_uploaded_file().
This may not be the answer to your question, but still it's worth your attention, I hope. Don't rely on the type of the file sent via $_FILES, this is just the mime-type sent by the browser as far as I remember, it can be easily compromized. Use getimagesize() function to get true image type as well as height/width.
Same goes for the source file name, but that shouldn't pose a security hole.