I'm trying to upload files through the PHP function move_uploaded_file and this is what I have so far:
if (move_uploaded_file($file["tmp_name"], iconv("UTF-8","big5",$target_file))) {
return true;
}
else {
echo "Not uploaded because of error #".$file["error"];
exit(0);
return false;
}
As for $target_file, it is the location I'd like to upload my files, which is currently stu_feedback/105502504/feedback_20180910.pdf.
Yet, the files are all failed to be uploaded, which obviously goes to the else part.
But when I wanted to echo the error message, it only shows 0.
I use Filezilla Client. I have tested on my localhost and it could upload files correctly.
Does anyone know what actually happened?
I see some problems on this part :
Add enctype to the form <form enctype="multipart/form-data">;
Be sure that the folder where you want to move files are permissions (chmod -R /folder_name 777)
Try to put in a try catch you code something like :
try{
if (move_uploaded_file($file["tmp_name"], iconv("UTF- 8","big5",$target_file))) {
return true;
}
else {
echo "Not uploaded because of error #".$file["error"];
//exit(0);
return false;
}
}catch (\Exception $e){
var_dump($e->getMessage());
die();
}
Related
I have a folder called uploads inside my root directory (C:\xampp\htdocs). I am trying to implement the php function move_uploaded_file(), to store my image file inside that folder. This is my code:
$folder="/uploads";
try{
$moved=move_uploaded_file($_FILES['file']['tmp_name'][0],$folder.'/'.$_FILES['file']['name'][0]);
}
catch(Exception $e) {
echo $e->getMessage(); //shows nothing
}
if($moved)
echo "Moved to location successfully";
else
echo $folder.'/'.$_FILES['file']['name'][0]; // shows /uploads/business-man.png
I have double checked the file_name, the tmp_name. They are correct. Where am I going wrong?
I am using slim to upload files like the following :
foreach ($files as $file) {
try {
$fileLog = $file->moveTo($location));
}
catch(\Exception $e) {
throw new \Exception($e->getMessage());
}
}
return true;
the problem i that there is probably a runtimeexception when there is no space in the disk and the phph trying to save the file.
I am looking for a way to always catch any exception with saving file :
no sapce, broken file ...etc
for now the issue is I cannot catch the runtime exception
i am trying to download a zip file from server and save it. i get the following error.
the project is in cakePHP
Downloading /server/biruhxml20140925.zip ...
Warning Error: ftp_get(): Transfer complete. in [(pathprefix)/app/Console/Command/Task/ImportUtilityTask.php, line 214]
//server/biruhxml20140925.zip could not be downloaded to (pathprefix)/files/downloaded_files/bild/biruhxml20140925.zip
biruhxml20140925.zip could not be downloaded as the file is not there yet.
this is the function which makes the call.
public function downloadFTPFile ($remoteFile, $localFile) {
$connection = $this->ftpConnection;
ftp_pasv($this->ftpConnection, true);
$this->out(__('Downloading %s ... ', $remoteFile));
try {
if (ftp_get($connection, $localFile, $remoteFile, FTP_BINARY)) {
$this->out(__('Saved %s', $localFile));
return true;
} else {
$this->out(__('%s could not be downloaded to %s', $remoteFile, $localFile));
return false;
}
} catch (Exception $e) {
#unlink($localFile);
$this->out($e->getMessage());
}
$this->nl();
return false;
}
can anyone suggest a work around to get rid of the warning other then setting debug level 0 in core.php
Have you considered, based on the error message, that the file you try to download is not present on the server?
Your code doesn't do a check if the file is there, I would add that and handle that case accordingly.
Error Handling with files in PHP
$path = '/home/test/files/test.csv';
fopen($path, 'w')
Here I want add an error handling by throwing exceptions, on 'No file or directory is found' and 'No permission to create a file'.
I am using Zend Framework.
By using fopen with write mode, I can create a file. But how to handle it when corresponding folder is not there?
i.e if files folder is not present in root structure.
How to throw an exception when no permission is permitted for creating a file?
Something like this should get you started.
function createFile($filePath)
{
$basePath = dirname($filePath);
if (!is_dir($basePath)) {
throw new Exception($basePath.' is an existing directory');
}
if (!is_writeable($filePath) {
throw new Exception('can not write file to '.$filePath);
}
touch($filePath);
}
Then to call
try {
createFile('path/to/file.csv');
} catch(Exception $e) {
echo $e->getMessage();
}
I suggest, you take a look at this link: http://www.w3schools.com/php/php_ref_filesystem.asp
especially the methods file_exists and is_writable
Like this:
try
{
$path = '/home/test/files/test.csv';
fopen($path, 'w')
}
catch (Exception $e)
{
echo $e;
}
PHP will echo whatever error would arise there.
Though you can also use is_dir or is_writable functions to see if folder exists and has permission respectively:
is_dir(dirname($path)) or die('folder doesnt exist');
is_writable(dirname($path)) or die('folder doesnt have write permission set');
// your rest of the code here now...
But how to handle it when corresponding folder is not there?
When a folder does not exist .. try to create it!
$dir = dirname($file);
if (!is_dir($dir)) {
if (false === #mkdir($dir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the %s directory', $dir));
}
} elseif (!is_writable($dir)) {
throw new \RuntimeException(sprintf('Unable to write in the %s directory', $dir));
}
// ... using file_put_contents!
I understand what try-catch statements do, but from reading the documentation on php.net, I would not be able to implement one into my own code. I need a real example to help me understand.
How can I turn this example into a try-catch statement, if the upload was not successful?
$move = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$_FILES['file']['name']);
if (!$move) {
die ('File didn\'t upload');
} else {
//opens the uploaded file for extraction
echo 'Upload Complete!';
}
This may not be a good example to work with, but any help would be appreciated.
You could do it like this.
try {
//throw exception if can't move the file
if (!move_uploaded_file( ... )) {
throw new Exception('Could not move file');
}
//do some more things with the file which may also throw an exception
//...
//ok if got here
echo "Upload Complete!";
} catch (Exception $e) {
die ('File did not upload: ' . $e->getMessage());
}
It is a bit pointless for the above example, but you should get the idea. Note that you can throw the exception(s) from anywhere (e.g. within a function/method that you call from withing the try{}) and they will propagate upwards.
Well, if you want to use exceptions, you could do something like:
function handleUpload() {
$move = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT']."/uploads/".$_FILES['file']['name']);
if (!$move) {
throw new Exception('File Didnt Upload');
}
}
try {
handleUpload();
echo "File Uploaded Successfully";
} catch(Exception $ex) {
die($ex->getMessage);
}
I know this may seem like bloat - but you can call the method from anywhere in the call stack, and catch the exception at any point.
try-catch statements are used to handle exceptions. I don't believe that the function move_uploaded_files can throw and exception, as such I think that you code is written is correct. After the call, you look at the return code. If it's false, you end processing, otherwise you are report success.
According to a similar post in PHPbug, only OO code (Object-Oriented code) throws exceptions. That would mean that functions such as move_uploaded_file won't throw their own exceptions, but some other code will.