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());
}
Related
I have a page, and I want it to allow users to upload a file to my server so that I can see it later. I have already gotten started, but when you click submit, it takes you to 500 error. Here is what code I have so far:
HTML:
<form action="uploadfile.php" enctype="multipart/form-data" method="POST">
Choose File:
<input name="userfile" type="file">
<p></p>
<p class="section-content"><input type="submit" value="Upload File"></p>
</form>
PHP: (named uploadfile.php)
<?php
$path = "files/"; $path = $path . basename( $_FILES['userfile']['name']);
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $path)) {
echo "Success uploading". basename($_FILES['userfile']['name']);
} else{
echo "Error when uploading file.";
}
?>
In HTML, there is a button to choose the file and one to submit. The submit button takes you to uploadfile.php, and that appears as 500 - internal server error. Note that it does not just say 'Error when uploading file' like it should when there is an error.
I am new to PHP, so I don't know if I am doing something completely wrong, or maybe there is a way to do it in Javascript, which I am slightly more experienced in?
Thank you in advance.
Edit: I have tried 2 different browsers (Chrome and Edge)
corrected
use $_SERVER['DOCUMENT_ROOT'] instead of basename()
$path = $_SERVER['DOCUMENT_ROOT'].'/your root file name/files';
$name = $_FILES['userfile']['name'];
$tmp_name = $_FILES['userfile']['tmp_name'];
move_uploaded_file($tmp_name, $path.'/'.$name);
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.
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
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.