Can't copy PDF using PHP copy() function, no error displayed - php

On my server Apache/2.4.37 (Oracle Linux), I am trying to copy a file from one directory to another.
$source = "../dvn/test.pdf";
$destination = "dvn/nglst.pdf";
mkdir(dirname($destination), 0777, true);
if(!copy($source,$destination)){
echo " file_exists source:".file_exists($source);
echo " file_exists destination:".file_exists($destination);
echo " file not copied ".$source." dest:".$destination;
} else {
echo " file copied ";
}
I have root permission on my $souce and $destination files on the server. But when I run the code, I get the following log.
file_exists source:1 file_exists destination:1 file not copied
../dvn/test.pdf dest:dvn/nglst.pdf
I don't get any errors, even if I have display_error = on in my php.ini, and it is not working on my server. I tried the same code in another server, and it worked fine. So it probably has to do with folder/files permission (755 for folder and 644 for file) of the Apache Oracle server.

Related

UploadedFile getPathname is empty

After deployed my Laravel code on Ubuntu server I have following function returning empty string:
$package = $request->file('file');
dd($package->getPathname());
while locally (Windows) it is working and on other hosting (Ubuntu too) it is working too.
What could be the reason for that?
Thank you!
This is most likely due to the web user that the php is running on being denied the access to the temp directory used to store the uploaded files.
You can check it by running the following snippet (that i took directly from the php manual) on the directory that you are uploading your files to:
<?php
$filename = 'test.txt';
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
?>

move_uploaded_file() working on localhost but on server

The following code works perfect on my localhost but it shows the following errors on my live server
Warning: move_uploaded_file(.../uploads/76948893.jpeg): failed to open stream: No such file or directory
Warning: move_uploaded_file(): Unable to move '/tmp/phppxvRs8' to '.../uploads/76948893.jpeg'
What it does is simple, it takes the images on the array ["pictures"] which comes from a html form and save every image on the folder ".../uploads/" using a random numeric name as name of the file and keeping the original extension.
Any one knows how to make it work on my server?
//Image Uploader
$images=[];
$directory = '.../uploads/';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
$new_file_name = rand (10000000,99999999);
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
/* echo '<br>';
echo $directory.$new_file_name.".".substr($_FILES['pictures']['type'][$key],strpos($_FILES['pictures']['type'][$key], "/")+1);*/
if(move_uploaded_file($_FILES['pictures']['tmp_name'][$key],
$directory
.$new_file_name
.".".substr($_FILES['pictures']['type'][$key],strpos($_FILES['pictures']['type'][$key], "/")+1))) {
array_push($images,$new_file_name.".".substr($_FILES['pictures']['type'][$key],strpos($_FILES['pictures']['type'][$key], "/")+1));
$images_validator=true;
}else{
//Error
}
}
}
There could be many reason for this, Check the following
You need WRITE Permission for the uploads directory. I assume your local machine runs windows & your hosting environment is linux
Like #Darren suggests, use absolute path. change the $directory to $directory = getcwd() . 'uploads/';
If this runs on your local machine but not on server there are 2 easy answers I can think off right off the back. 1. The folder doesnt exist on the server, 2. as someone comment you dont have permission to write/read to that folder on the server....I would check the server configuration to make sure your app pool or users have read/write permissions to the folder

Issue with copy() function/ file permissions

So here's the story, im not very experienced with php, and recently moved to a new host and my website worked prefectly on the old host but on the new host there are errors with the code.
The error message says :
Warning: copy() [function.copy]: Unable to access http://i.imgur.com/USlH6p2.jpg in (directory)
Heres the code where it says there is an error
function upload_image_remote($image, $name) {
$upload_dir = APP_PATH . '/image.uploads';
//check for directory rights
if(!is_writable($upload_dir)) {
echo do_error(_('Folder image.uploads is not writeable'));
exit;
}
//check if there's a directory for today uploads
$today = date("d-m-Y");
if(!is_dir($upload_dir .'/' . $today)) {
if(!mkdir($upload_dir .'/' . $today, 0777)) {
echo do_error(_(sprintf('Folder <strong>image.uploads/%s</strong> could not be created. Please check permissions to be 0777.', $today)));
exit;
}
}
$upload_path = $upload_dir .'/' . $today;
(--> this is where) return copy($image, $upload_path .'/'. $name);
}
I think it may be a permissions problem since it worked perfectly on (old host) 000webhost, anyone have any ideas on what can be wrong with the code ?
Thanks
My guess would be that the copy function is trying to access the remote file and cannot due to the PHP settings.
I think most hosting companies, for security reasons, will have allow_url_fopen = 0. This means that you will not be able to read from the remote location (http://www.site.com/foo.gif). However, you will be able to read from the local file system.
From the PHP documentation:
This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.
To check this, view the current PHP settings on the server by creating a file with the following contents in your web root. Your looking for the allow_url_fopen setting.
<?php
echo phpinfo();
?>
Give folder permission 0755 Set correct path of temp folder for file
system.

Can't find tmp folder in php. (Ubuntu 10.10, apache2)

I have a form, which uploads an image.
I try to get it by $_FILES:
$filename = $_FILES['screenshot']['name'];
$source = $_FILES['screenshot']['tmp_name']."/".$filename;
$target = GL_UPLOADPATH.$filename;
echo "TEST0";
if (move_uploaded_file($source, $target)) {
//connect to DB and so on, what I need
echo "TEST1";
}
So I get echoed TEST0 but don't get echoed TEST1.
If I echo every variable - it's normal. I see my $target - it's something like /tmp/phpoLqYdj/test2.jpg
So, I think PHP can't move_uploaded_file because it can't find /tmp/phpoLqYdj/test2.jpg
But where is /tmp/phpoLqYdj/? I am testing on localhost. My document root is /var/www/.
PHP has default settings in php.ini (upload_tmp_dir is commented in php.ini).
In my /tmp/ folder (in system) I don't have such folder like php***. In /var/tmp/ either.
(Ubuntu 10.10, LAMP was installed by "tasksel")
When you uploads files via PHP, it stores them in as a tmp file that's not named anything related to the filename. Appending $filename to $_FILES['screenshot']['tmp_name'] is the incorrect way to handle it... $_FILES['screenshot']['tmp_name'] IS the file.
Also, the tmp file is removed at the end of the request, so you'll never have a chance to actually see it in the file manager. Either you move it in the same request, or it's gone. It's all done in the name of security.
Anyway, just use this instead and you'll be good.
$filename = $_FILES['screenshot']['name'];
$source = $_FILES['screenshot']['tmp_name'];
$target = GL_UPLOADPATH.$filename;
echo "TEST0";
if (move_uploaded_file($source, $target)) {
//connect to DB and so on, what I need
echo "TEST1";
}
I had the exact same problem. What I did to fix it was change the permissions of folder that you are uploading to, to read and write for all.

PHP move_uploaded_file() error?

I using following code and it is successfully uploading files on my local machine. It is showing "Successfully uploaded" on my local machine.
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded";
}
But when I used this code on my online server then it is not uploading file and just showing message "Not uploaded".
How can I know that what is the problem and how can I get the actual problem to display to the user ?
Edit the code to be as follows:
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded because of error #".$_FILES["file"]["error"];
}
It will give you one of the following error code values 1 to 8:
UPLOAD_ERR_INI_SIZE =
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE =
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL =
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE =
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR =
Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE =
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION =
Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.
Try this:
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/images/';
if (is_dir($upload_dir) && is_writable($upload_dir)) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
This will instantly flag any file permission errors.
Check that the web server has permissions to write to the "images/" directory
How can I know that what is the problem
Easy. Refer to the error log of the webserver.
how can I get the actual problem to display to the user ?
NEVER do it.
An average user will unerstand nothing of this error.
A malicious user should get no feedback, especially in a form of very informative error message.
Just show a page with excuses.
If you don't have access to the server's error log, your task become more complicated.
There are several ways to get in touch with error messages.
To display error messages on screen you can add these lines to the code
ini_set('display_errors',1);
error_reporting(E_ALL);
or to make custom error logfile
ini_set('log_errors',1);
ini_set('error_log','/absolute/path/tp/log_file');
and there are some other ways.
but you must understand that without actual error message you can't move. It's hard to be blind in the dark
move_uploaded_file() will return:
FALSE if file name is invalid
FALSE and issue a warning in the error log if the apache process does not have read/write permissions to source or destination directories
PHP Error Log
My php error log was at: /var/log/httpd/error_log and had these errors:
Warning: move_uploaded_file(images/robot.jpg): failed to open stream: Permission denied in /var/www/html/mysite/mohealth.php on line 78
Warning: move_uploaded_file(): Unable to move '/tmp/phpsKD2Qm' to 'images/robot.jpg' in /var/www/html/mysite/mohealth.php on line 78
move_uploaded_file() tries to move files from a temporary directory to a destination directory. When apache process tried to move files, it could not read the temporary or write to the destination dir.
Find which user is running Apache (Web Server)
Check which user is running the apache service by this command: ps aux | grep httpd. The first column is the user name.
Check Read Permission at Temporary Dir: Your can find the path to your temp dir by calling echo sys_get_tmp_dir(); in a php page. Then on the command line, issue ls -ld /tmp/temporary-dir to see if the apache user has access to read here
Check Write Permission at Destination Dir: issue ls -ld /var/www/html/destination-directory to see if the apache user has access to write here
Add permissions as necessary using chown or chgrp
Restart Apache using sudo service httpd restart
Do you checks that file is uploaded ok ? Maybe you exceeded max_post_size, or max_upload_filesize. When login using FileZilla you are copying files as you, when uploading by PHP wiritng this file is from user that runs apache (for exaplme www-data), try to put chmod 755 for images.
or run suexec and never have to change permissions again.
In php.ini search for upload_max_filesize and post_max_size. I had the same problem and the solution was to change these values to a value greater than the file size.
Please check that your form tag have this attribute:
enctype="multipart/form-data"
$uploadfile = $_SERVER['DOCUMENT_ROOT'].'/Thesis/images/';
$profic = uniqid(rand()).$_FILES["pic"]["name"];
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
{
$moved = move_uploaded_file($_FILES["pic"]["tmp_name"], $uploadfile.$profic);
if($moved)
{
echo "sucess";
}
else
{
echo 'failed';
}
}
On virtual hosting check your disk quota.
if quota exceed, move_uploaded_file return error.
PS : I've been looking for this for a long time :)
Please check permission "images/" directory
I ran into a very obscure and annoying cause of error 6.
After goofing around with some NFS mounted volumes, uploads started failing.
Problem resolved by restarting services
systemctl restart php-fpm.service
systemctl restart httpd.service

Categories