I post a file by HTML and I want to move it but it always return value false.
here's my code :
$fileName = $_FILES['atc']['name'];
$fileTmp = $_FILES['atc']['tmp_name'];
$newDir = "/home/goes/attachments/" . $fileName;
$a = move_uploaded_file($fileTmp, $newDir);
if ($a==true){
echo "true";
}
else{
echo "false";
}
The destination folder may not be have write permission
Check the content of all of your variables, see if they contain anything (good)
Check if the directory where you want to place the files exists, and is writeable by the webserver (or whoever runs the PHP process).
Is this the script you are calling from your form? Apache only holds the uploaded files for the duration of the called script, after that, the files are deleted if they are not handled by the script.
foreach ($_FILES['atc']['tmp_name'] as $key => $tmp_name){ $path = "home/goes/attachments/" . $fileName";move_uploaded_file($tmp_name, $path);
}
Related
I have a task to do in which i have to list the directories with it's files which i did, but i don't understand how to delete file or edit specific file in the directories any help will be appreciated Thanks.
<?php
error_reporting(0);
if(isset($_GET['dir']))
{
// /$path = 'E:\xampp\\'.$_GET['dir'];
$path = $_GET['dir'];
}
else
{
$path = 'E:\xampp\\';
}
if(is_dir($path))
{
$arrDir = scandir($path);
echo "<ul>";
foreach ($arrDir as $key => $value)
{
echo "<a href='http://localhost/vishrut/FileUpload/filelist.php?
dir=".$path.'/'.$value."'>".$value.'</a><br>';
}
echo "</ul>";
}
else
{
echo "<textarea>";
echo file_get_contents($path);
echo "</textarea>"."<br>";
}
?>
There are lots of PHP's functions to handle files: https://www.php.net/manual/en/ref.filesystem.php
For your needs see these:
file_get_contents to read the entire file contents
file_put_contents to write the content in a file
unlink to delete a file
So, the steps to modify a file may be:
get the complete contents with file_get_contents:
$contents = file_get_contents($filePath);
apply your edits to the $contents content:
$newContents = ...
overwrite the file content:
file_put_contents($filePath, $newContents);
To delete a file is simple:
unlink($filePath);
It's important to note that your code is subjected to injection because you don't check the user data passed with $_GET.
If your script will be used only by you it's ok, instead you must check all user input: the first rule of Web programming is NEVER TRUST YOUR USERS! Also trusted users may write wrong characters in the url and that may have unexpected results (e.g. delete the wrong file!)
Read https://www.php.net/manual/en/mongodb.security.script_injection.php
I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'
So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help
I'm converting an image to a binary file in IOS, which works just fine. This will be handled by my php script which is suppose to upload this image to my ubuntu server. The problem is i keep getting file=unsuccessful. i've tried different directory paths, but cant seem to solve this issue.
This $directory will return this: /var/www/User/core/ios/
<?
if(!empty($_POST))
{
$message = $_POST['message'];
$directory = $_SERVER['DOCUMENT_ROOT'] . '/User/core/ios/';
$file = basename($_FILES['userfle']['upload']);
$uploadfile = $directory . $file;
var_dump($_FILES);
$randomPhotoID = md5(rand() * time());
echo 'file='.$file;
echo $file;
if (move_uploaded_file($_FILES['userfle']['tmp_name'], $uploadfile)) {
echo 'successful';
}
else
{
echo 'unsuccessful';
}
}
else
{
echo('Empty post data');
}
?>
Check the error file of your php(you can make sure if you enabled the error log in php.ini),
if you don't have the permission or for some other reasons it can't move the file ,there will be a record in that file.
Some time you can try the command setenforce 0 if you confirm you(I means the user of apache) have the permission to move the file but it not work.
By the way if the file you want to move is not upload by post, there is no error log and the move function will return false.
Does anyone know how I can check to see if a directory is writeable in PHP?
The function is_writable doesn't work for folders.
Edit: It does work. See the accepted answer.
Yes, it does work for folders....
Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable.
this is the code :)
<?php
$newFileName = '/var/www/your/file.txt';
if ( ! is_writable(dirname($newFileName))) {
echo dirname($newFileName) . ' must writable!!!';
} else {
// blah blah blah
}
to be more specific for owner/group/world
$dir_writable = substr(sprintf('%o', fileperms($folder)), -4) == "0774" ? "true" : "false";
peace...
You may be sending a complete file path to the is_writable() function. is_writable() will return false if the file doesn't already exist in the directory. You need to check the directory itself with the filename removed, if this is the case. If you do that, is_writable will correctly tell you whether the directory is writable or not. If $file contains your file path do this:
$file_directory = dirname($file);
Then use is_writable($file_directory) to determine if the folder is writable.
I hope this helps someone.
According to the documentation for is_writable, it should just work - but you said "folder", so this could be a Windows issue. The comments suggest a workaround.
(A rushed reading earlier made me think that trailing slashes were important, but that turned out to be specific to this work around).
I've written a little script (I call it isWritable.php) that detects all directories in the same directory the script is in and writes to the page whether each directory is writable or not. Hope this helps.
<?php
// isWritable.php detects all directories in the same directory the script is in
// and writes to the page whether each directory is writable or not.
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dir) {
if (is_writable($dir)) {
echo $dir.' is writable.<br>';
} else {
echo $dir.' is not writable. Permissions may have to be adjusted.<br>';
}
}
?>
stat()
Much like a system stat, but in PHP. What you want to check is the mode value, much like you would out of any other call to stat in other languages (I.E. C/C++).
http://us2.php.net/stat
According to the PHP manual is_writable should work fine on directories.
In my case, is_writable returned true, but when tried to write the file - an error was generated.
This code helps to check if the $dir exists and is writable:
<?php
$dir = '/path/to/the/dir';
// try to create this directory if it doesn't exist
$booExists = is_dir($dir) || (mkdir($dir, 0774, true) && is_dir($dir));
$booIsWritable = false;
if ($booExists && is_writable($dir)) {
$tempFile = tempnam($dir, 'tmp');
if ($tempFile !== false) {
$res = file_put_contents($tempFile, 'test');
$booIsWritable = $res !== false;
#unlink($tempFile);
}
}
this is how I do it:
create a file with file_put_contents() and check the return value, if it is positive (number of written in Bytes) then you can go ahead and do what you have to do, if it is FALSE then it is not writable
$is_writable = file_put_contents('directory/dummy.txt', "hello");
if ($is_writable > 0) echo "yes directory it is writable";
else echo "NO directory it is not writable";
then you can delete the dummy file by using unlink()
unlink('directory/dummy.txt');