File upload in php not working on remote server - php

Here is the code which I am using
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br><br>
<input type="submit" value="submit" name="submit">
</form>
PHP code :
<?php
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "/var/www/tmp/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo 'File uploaded successfully';
} else {
echo 'You should select a file to upload !!';
}
?>
I checked the permissions of the folder as well as checked the php.ini file but still always I am getting 'You should select a file to upload '
Can anybody please help me out on this issue ?
Thank you so much!

Give the full path of your file here
$location = "var/www/tmp/";
I think it will work. If its ok then store your servername in a variable and pass there.

Your Location should be like this:
// document root will give you the server root then you can add any directory after that (in your case its tmp I guess)
$location = $_SERVER['DOCUMENT_ROOT'] . '/your_preferred_dir/'
note: when you mention your preferred location you will have to make
sure that this location should exists otherwise it will cause error.
And not hardcoded as yours because it can change from server to server.
Hope this helps...

Related

How to let users upload a file to server

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);

PHP move_uploaded_file() failing on host

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.

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

Can I attach data gathered by a form to a file that is being uploaded?

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.

Categories