Issue with copy() function/ file permissions - php

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.

Related

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

Cannot write create file using PHP file_put_contents

I'm new at the whole php thing, and I need to write a file in the server (my own computer where I am developing a web app) with some config info. Here is the code I'm using:
$filename = "config.conf";
$db_info = $db_user . "<-*->" . $db_passwd . "<-*->" . $db_name;
if (file_put_contents($filename,$db_info) === false){
$ret["error"] = "Can't create/write: $filename.";
mysqli_close($con);
echo json_encode($ret);
return;
}
When I test my web app I get the create/write error I wrote. I checked and the file is not created. My working directory is in /var/www/tests however I've checked tests and my user has read and write permissions and is owner of that folder. If I create a file with a ordinary file explorer I have no problems whatsoever. Since the function is so simple, I am at a loss. Please help!
does web server has read/write permissions (e.g. nginx uses www-data user)? try setting permissions to 777 for folder where you want to create that file.

Uploading a local file to remote server with PHP and FTP

I've been trying to make a system that can upload large files, originally i used HTTP but this had a number of problems with settings that needed to be changed. So i thought i'd give it a go with FTP.
Now i have a ftp connection in PHP and it works find, i can view folders and files as well as make directories, what i can't seem to figure out though is how to get hold of a local file and upload it.
I have been reading lots of information and tutorials such as the PHP manual and a tutorial i found on nettuts But i'm struggling to do it. The tutorial says you can upload a local file but i must be missing something.
Here is the upload method i'm using:
public function uploadFile ($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$extension = end(explode('.', $fileFrom));
if (in_array($extension, $asciiArray))
$mode = FTP_ASCII;
else
$mode = FTP_BINARY;
// *** Upload the file
$upload = ftp_put($this->connectionId, $fileTo, $fileFrom, $mode);
// *** Check upload status
if (!$upload) {
$this->logMessage('FTP upload has failed!');
return false;
} else {
$this->logMessage('Uploaded "' . $fileFrom . '" as "' . $fileTo);
return true;
}
}
When trying to upload a file i use this:
$fileFrom = 'c:\test_pic.jpg';
$fileTo = $dir . '/test_pic.jpg';
$ftpObj -> uploadFile($fileFrom, $fileTo);
I thought this would get the file from my machine that is stored in the c: and upload it to the destination but it fails (Don't know why). So i changed it a little, changed the $fileFrom = test_pic.jpg and up the picture in the same folder on the remote server. When i ran this code the script copied the file from the one location to the other.
So how would i go about getting the file from my local machine to be sent up to the server?
Thanks in advance.
Using this you would upload a file from your PHP server to your FTP server, what actually not seems to be your target.
Create an upload form which submits to this PHP file. Store this file temporarily on your server and then upload it to your FTP server from there.
If your try would actually work, this would be a major security issue, because a PHP file would have access to any files on my local machine.

tempnam() not working on client server

I did a script, which has to load a file from a ftp-server then parses it. The code relies on tempname to store the temporarily store the ftp-file. On my developement server (with php 5.3.10), this works flawlessly, however on the client machine (with php 5.2.17) it does not and gives me:
Warning: ftp_rawlist() [function.ftp-rawlist]: Unable to create temporary file. Check permissions in temporary files directory.
Can someone give me a clue what i could do?
(I am a little weak on the possibiities of php)
I used this code:
define ("LOCALFILE",tempnam('/tmp', 'data-'));
define ("USER","myusername");
define ("PASS","mypassword");
define('SERVER', "ftpserver.com");
define ("DIR","/path/");
function getFTPFile(){
// connect
if(!($conn_id = #ftp_connect(SERVER))){
Error::throwOne("Could not connect to ".SERVER);
};
// login
if(!($login_result = #ftp_login($conn_id, USER, PASS))){
Error::throwOne("LOGIN INCORRECT! user:".USER." pass:".PASS);
};
// try to change the directory to somedir
if (!ftp_chdir($conn_id, DIR)) {
Error::throwOne("Couldn't change directory\n");
};
if(!($a = ftp_rawlist($conn_id, '-1t'))){
Error::throwOne("Couldn't get ftp_rawlist\n");
};
$server_file=($a[0]);
if (!ftp_get($conn_id, LOCALFILE, $server_file, FTP_BINARY)) {
Error::throwOne("Couldn't get file\n");
};
ftp_close($conn_id);
};
The error looks to me like system-generated and have nothing to do with your tmpname. Internally, FTP stores the file in its own temp file in temp filename in standard temp directory up to the point when it's downloaded - then moves it to the location you specified.
Try putting this code before your download code:
$tmpdir = sys_get_temp_dir();
echo "Temp dir: $tmpdir\n";
echo is_writable($tmpdir) ? "Temp dir is writable" : "Temp dir is not writable";
This will tell you if you have permissions to write to the system temp dir. I further suggest that you use this $tmpdir variable instead of hardcoding "/tmp" in your code.
I found the issue.
Since my hoster does not like the /tmp directory ( who would blame them )
i need to first set
putenv('TMPDIR=/the tmp-dir my provider gave me');
which then works with tempname
I found this occurred on Windows Server 2016 - and it was because my %TEMP% environment variable pointed to a subdirectory that didn't exist for whatever reason.
It did point to the correct one when I ran it as Administrator, though.

Why would is_readable & is_writable & file_exists fail for URL path and not for a file in the same directory?

I've been googling this question for two days and really haven't found anyone who can give me a solid answer. Maybe the geniuses at stackoverflow can help?
My conundrum: I'm trying to read and write to a file using a URL syntax for a URL pointing to a file on my server. (See code below) The code works fine so long as the filename is in the same directory as the php file and I'm not using any URL socket on it. (i.e. $filename = "test.xml") But as soon as I try to add a URL socket (i.e. http://127.0.0.1/site_folder/text.xml) I get failures on all three tests (is_readable, is_writable, file_exists). Why would this be? Is there a way to correct it so that I can read and write this file?
My Setup: PHP 5.3.2 on Microsoft IIS 7.0.6000.16386 on a Microsoft Vista machine
PHP directory: c:\Program Files (x86)\php\
Security: I have set the permissions for the directory of the file and the file itself for IUSR account to read, write, execute, list directory. This php file resides in the same directory as the test.xml file for now. But I want to get this URL to work so that I can adjust a file in a different directory in the future.
php.ini config: I've tried these settings among others:
open_basedir=Off;
fastcgi.impersonate = 1;
display_errors = On;
error_reporting = E_ALL & ~E_STRICT;
safe_mode = Off;
allow_url_fopen = Off; (and tried On, neither works);
allow_url_include = Off; (and tried On, neither works);
Here is my simple code sample:
<?php
$filename = "http://127.0.0.1/sitename/admin/interface/test.xml"; // this one fails
// $filename = "text.xml" // this one works fine
echo $filename;
if (is_readable($filename)) {
echo "<br />The file is readable...<br />";
} else {
echo "<br />The file is not readable...<br />";
}
if (is_writable($filename)) {
echo "The file is writable...<br />";
} else {
echo "The file is not writable...<br />";
}
if (file_exists($filename)) {
echo "File exists...<br />";
} else {
echo "File cannot be found...<br />";
}
?>
And the output I'm getting:
http://127.0.0.1/sitename/admin/interface/test.xml
The file is not readable...
The file is not writable...
File cannot be found...
Any idea why this is happening?
As a side note, same thing is happening with PHP 5.3.2 on my Macbook Pro with Apache Server on it.
The http:// protocol wrapper does not support the stat() family of functions (see: http://php.net/manual/wrappers.http.php to see what is supported). stat() support is necessary for file_exists, is_writable, and is_readable.
The file:// protocol wrapper (the default one, used in your working example) does support stat(): http://php.net/manual/wrappers.file.php
You can read more about protocols and wrappers here:
http://php.net/manual/wrappers.php
$filename = "//127.0.0.1/sitename/admin/interface/test.xml";
you can try to change this path like ../../test.xml or in same directory use test.xml
i tried and the same problem is solved
If you want to perform File I/O, then pass in actual paths (using $_SERVER['DOCUMENT_ROOT'] may be helpful to specify those). PHP's fopen supports special handling for URLs, but the wrappers for other file I/O functions do not.

Categories