File upload using cakephp - php

I just want to upload a single pdf file using cakephp,
here is my view called pdfadd.ctp:
<?php echo $this->Form->create('pdfadd1', array('enctype' => 'multipart/form-data'));?>
<fieldset>
<?php
echo $this->Form->file('Document.submittedfile');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
Here is my conroller:
public function pdfadd(){
if ($this->request->is('post') || $this->request->is('put')) {
//die();
$file = $this->request->data['Document']['submittedfile'];
//$this->pdfadd1->save($this->request->data);
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
}
It gives me this error:
Warning (2): move_uploaded_file(D:/Program Files D/xampp/htdocs/app/webroot/files/Functions Package for email (1).pdf): failed to open stream: No such file or directory [APP\Controller\PagesController.php, line 29]
Warning (2): move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:\Program Files D\xampp\tmp\php862.tmp' to 'D:/Program Files D/xampp/htdocs/app/webroot/files/Functions Package for email (1).pdf' [APP\Controller\PagesController.php, line 29]
And also I want to rename the file to 1.pdf. The file should save in webroot/files.

Replace this:
$_SERVER['DOCUMENT_ROOT'] . '/app/webroot/files/' . $this->data['Document']['submittedfile']['name']
with this:
WWW_ROOT . 'files' . DS . '1.pdf'
However, you really should do more validation, like using PHP's is_uploaded_file function, making sure the file really is a PDF, etc.

move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
1.Change this code according to directory
2.c:xampp/htdocs(its a default location for uploading in cakephp ),then put your upload file location
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . 'cakephp/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
3.You can rename it before uploading

This line get only file name, not file.
$file = $this->request->data['Document']['submittedfile'];
You could use this.
$file = $_FILES ['Document'] ['submittedfile'];

Related

move_uploaded_file(/Advanced Java Programming.pdf): failed to open stream: Permission denied

So, I am working on a system where people working in a company can upload files to a system which will be sorted by departments. I have managed to get the files info(name, size, type), but the problem occurs while trying to upload the file.
I get:
move_uploaded_file(/Advanced Java Programming.pdf): failed to open stream: Permission denied
move_uploaded_file(): Unable to move 'C:\xampp\tmp\php1B99.tmp' to '/Advanced Java Programming.pdf'
I have set the permissions of the folder where the file needs to be uploaded to everybody (777).
Here's my code
<?php
$department = $_POST['department'];
$file = $_FILES['fileToUpload'];
echo "<b>Department: </b>" . $department . "<br>";
echo "<b>Name: </b>" . $file['name']. "<br>";
echo "<b>Size: </b>" . $file['size'] . " bytes<br>";
echo "<b>Type: </b>" . $file['type'];
move_uploaded_file($file['tmp_name'], "/". $file['name']);
?>
Try using an absolute path for your destination or at least start it with the DIR-constant, "/" ist not a valid (Windows)-path.
Also think about using the constant DIRECTORY_SEPARATOR as "/" is a *nix-standard, but as you're running on Windows, it should be "\" - using the constant will hold the right slash for every system.

php rename function is not working

I have written the following Codeigniter function to rename a folder but its not working, the folder also contains 2 sub-folders and that folders contains some CSS and image files.
function _rename_theme_folder($old_name, $new_name){
echo THEMES_BASE_URL . $old_name."<br>";
echo THEMES_BASE_URL . $new_name;
rename(THEMES_BASE_URL . $old_name, THEMES_BASE_URL . $new_name);
exit;
}
Note: I can read and write files to the same directory but renaming is not working.
Output of the above function:
D:\wwwroot\ds_menu\static\front\naveed
D:\wwwroot\ds_menu\static\front\naveedkhan

Having an issue with the fopen() php function

I have a users directory and a child directory for the login/register system. I have a file, testing.php, to try to figure out how to create a directory in the users directory AND create a PHP file within that same directory. Here's my code:
<?php
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = "../" . "ActivationFile";
fopen("$file", "w");
?>
I'm able to get mdkir($directory) to work, but not the fopen("$file", "w").
Try this, this should normally solve your problem.
PHP delivers some functions to manipulate folder & path, it's recommended to use them.
For example to get the current parent folder, you can use dirname function.
$directoryname = dirname(dirname(__FILE__)) . "/SomeDirectory";
if (!is_dir($directoryname)) {
mkdir($directoryname);
}
$file = "ActivationFile";
$handle = fopen($directoryname . '/' . $file, "w");
fputs($handle, 'Your data');
fclose($handle);
This line is equivalent to "../SomeDirectory"
dirname(dirname(__FILE__)) . "/SomeDirectory";
So when you open the file, you open "../SomeDirectory/ActivationFile"
fopen($directoryname . '/' . $file, "w");
You can use the function touch() in order to create a file:
If the file does not exist, it will be created.
You also forgot to re-use $directory when specifying the filepath, so the file was not created in the new directory.
As reported by Fred -ii- in a comment, error reporting should also be enabled. Here is the code with these changes:
<?php
// Enable error output, source: http://php.net/manual/en/function.error-reporting.php#85096
error_reporting(E_ALL);
ini_set("display_errors", 1);
$directoryname = "SomeDirectory";
$directory = "../" . $directoryname;
mkdir($directory);
$file = $directory . "/ActivationFile";
touch($file);
try this:
$dirname = $_POST["DirectoryName"];
$filename = "/folder/{$dirname}/";
if (file_exists($filename)) {
echo "The directory {$dirname} exists";
} else {
mkdir("folder/{$dirname}", 0777);
echo "The directory {$dirname} was successfully created.";
}

Yii2 - finfo_file(/tmp/phpqE6gyD): failed to open stream: No such file or directory on save after file upload

I am getting following error, when I try to save data into db after file upload:
finfo_file(/tmp/phpqE6gyD): failed to open stream: No such file or directory
This is the code:
$userFolderPath = \Yii::getAlias('#webroot') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . \Yii::$app->user->getIdentity()->iduser;
$model = new CsFile();
$files = UploadedFile::getInstances($model, 'files');
$errors = [];
if (!file_exists($userFolderPath))
mkdir($userFolderPath, 0777, true);
foreach($files as $file):
$fileModel = new CsFile();
$fileModel->files = $file;
if($fileModel->validate()):
$filename = str_replace(' ', '_', $file->baseName);
if(file_exists($userFolderPath . DIRECTORY_SEPARATOR . $filename . "." . $file->extension)):
$filename .= "-" .uniqid();
endif;
$fileModel->files
->saveAs($userFolderPath .DIRECTORY_SEPARATOR. $filename . '.' . $fileModel->files->extension);
$fileModel->iduser = Yii::$app->user->getIdentity()->iduser;
$fileModel->name = $filename;
$fileModel->extension = $file->extension;
$fileModel->add_date = date('Y-m-d H:i:s');
$fileModel->save();
else:
endif;
endforeach;
var_dump('<pre>', $errors, '</pre>');
I had the same problem a few weeks ago. Turns out, when we rename the file before upload and try to save the model, this error will appear.
If that attribute it's only for handle your upload and have no field in your table, you can just unset this fields before saving: $files Model->files = null.
Let me know if your scenario is different than mine.
Yii2 use UploadFile class through function $model->upload() to save upload file
To fix this use inside your $model->upload function :
return copy($this->YourAttribute->tempName, $newFileName);
instead
return $model->attribute->saveAs($newFileName)
Clyff is right. But in case you are saving the path of the file in database to read later, setting the attribute to null is not going to work.
The problem is when you try to save the model still with result of UploadedFile::getInstance($model, 'file') in the file field which is already used by $model->file->saveAs();
$model->save() cannot save the path of the saved and already removed temporary files path directly.
So after successful $model->file->saveAs($path) you need to do something like:
$model->file = $path;
It was quite unclear to me and spent a bit of time after fileinfo , so hope the answer helps.
I was having same problem, I solved it with this:
$model->file->saveAs($filepath , false)
then...
$model->save(false)
Important: In the saveAs function pass false parameter.
Using false parameter in $model->save(false) that means you are ignoring model validation, which is not right.
But using false as a second parameter in $file->saveAs($path,false) means you are trying to keep the file in the temp folder after being uploaded and allow the model to access the file during validation when trying to save to the database.
If the model fails to access the file (i.e removed from the temp folder after being uploaded), you will getting an ERROR Fail to open a stream, No such file/folder

PHP move_uploaded_file

I am trying to upload files to a server using PHP move_uploaded_file and I am getting the following error:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /Users/Rick/Sites/upload/upload.php on line 7
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/Applications/XAMPP/xamppfiles/temp/phpDlCZUd' to '/Users/Rick/Sites/upload/uploads/richardgregson' in /Users/Rick/Sites/upload/upload.php on line 7
Below is my code, nothing complicated.
if($_POST["upload"]){
$target_path = "/Users/Rick/Sites/upload/uploads/" . $_POST["name"];
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){
echo "<div class='success'>The file " . "<span class='filename'>" . basename( $_FILES['uploadedfile']['name']) . "</span>" . " has been uploaded</div>";
} else {
echo "<div class='error'>There was an error uploading the file, please try again!</div>";
}
}
The permissions on the folder it is writing to are correct. I dont understand the error "cannot be a directory as the argument is where we are moving the file to so it has to be a directory.."
Thanks
Rick
The error is telling you what's wrong - $target_path (/Users/Rick/Sites/upload/uploads/richardgregson) is a directory
Try adding an extension.
$extension=end(explode('.', $_FILES["uploadedfile"]["name"]));
$target_path = "/Users/Rick/Sites/upload/uploads/" . $_POST["name"] . '.' . $extension;
Or perhaps your putting the file into a folder
$target_path = "/Users/Rick/Sites/upload/uploads/" . $_POST["name"] . '/' . $_FILES["uploadedfile"]["name"];
Note: you should not trust the user to upload only the files you want and you should sanitise $_POST["name"], all too easy to make that '../../' and post a PHP file.

Categories