fopen is not working on elastic beanstalk php - php

I am using the following code in elastic beanstalk php to generate log file but I am getting this error.But the same code is working on another server. How can I make it work ?
Error:
Error opening file in write mode!
Code :
$path="/var/www/html/aws";
$fileName =$path.'/logs/data'.date('Y-m-d_H-i-s'). '_' . uniqid() . '.txt';
$file = fopen($fileName,'w') or die('Could not create report file: ' . $fileName);
foreach($_POST as $key => $value) {
$reportLine = $key." = ".$value."\n";
fwrite($file, $reportLine) or die ('Could not write to report file ' . $reportLine);
}
fputs($file,"log aws");
fclose($file);

Make sure your php user www-data have permission to write in $path.'/logs/ folder or just chmod that logs folder to 0777 permisson

Related

php file saved via move_file_upload works when called directly not via exec()

This is the dilemma. I have a script that works perfectly for writing small video files into S3 bucket and local docker.
I need to update the script so it can handle larger files. In order to do that I am using the exec() method in which I run a php script to upload the file so it runs it in the background. This is the code I'm using:
$tempFile = $_FILES['form-file-input']['tmp_name'][$i];
$directory = $config['content_directory'];
echo (is_file($tempFile) ? 'Tempfile is a file' : 'Tempfile is not a file');
echo (is_readable($tempFile) ? ' and tempfile is readable.' : ' and tempfile is not readable.');
echo '<br>'.'This is the file name: '.$newFileName.'<br>';//already defined
chdir('/var/www/webApp/_apps/training_videos/');//required to find i-did-it.php - tested and doesn't affect saving functionality
exec("php i-did-it.php $tempFile $directory $newFileName 2>&1", $out);
var_dump($out);
//$resultado = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);
//var_dump($resultado);
exit;
BELOW ARE THE CONTENTS OF i-did-it.php
Note that the code reviews before and after executing if the the param is a readable file and that the other params have a valid value. Also note that I set all errors, set a log file and try to catch the last error.
//Set all errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors',1);
ini_set('error_log','/var/www/siteContent/logs/log.txt');//verified that log file can be written to
//Get the params
$tempFile = $argv[1];
$directory = $argv[2];
$newFileName = $argv[3];
//Verify that it arrives as a readable file
echo (is_file($tempFile) ? 'Tempfile is a file' : 'Tempfile is not a file');
echo (is_readable($tempFile) ? ' and tempfile is readable.' : ' and tempfile is not readable.');
//Display the params
echo ' Temp file name: '.$tempFile;
echo ', the directory: '.$directory;
echo ' and new file name: '.$newFileName.' *** ';
//Move the file and dump results
$putResult = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);//original
var_dump($putResult);
print_r(error_get_last());
So what is the problem?
move_uploaded_file commmand is not working when called via exec().
Note that if I replace this line
exec("php i-did-it.php $tempFile $directory $newFileName 2>&1", $out);
with this one
$resultado = move_uploaded_file($tempFile, $directory . '/_' . 'videos' . '/' . $newFileName);
it works!
Note that it is commented in the first snippet.
Those are the results I get
In order to troubleshoot I need to know why the move_uploaded_file command is not working since it only throws true or false. It's known it is false since it doesn't work. I would like to get more errors than that. The method recommended for the task I cannot use since my file is not set like this: $_FILES['file'] but as a variable (It has to be done that way since I'm passing it as a param) so I cannot check errors towards: $_FILES['file']['error']
Reference for the error obtaining approach
https://www.php.net/manual/en/features.file-upload.errors.php
Following the previous example I tried applying it to the var that holds the file to no avail:
if ($tempFile === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($tempFile);
}
What do I need to continue?
At this point it would be helpful to know these 2 things:
How can I get the error/warning from move_uploaded_file that is coming back as false?
Any ideas why move_file_upload will work perfectly fine when called directly but fails when called via exec("php myfile.php $param1 $param2 $param3 2>&1", $output)

ftp_size returns -1 after a file is uploaded using curl

My script packs some files with ZIP then uploads this ZIP to another server. After the upload it checks size of the ZIP on the FTP and locally. If sizes are the same- the local ZIP is deleted.
The problem is ftp_size() returns -1. But only in the real script. In my test script it works fine.
Test script works like this:
$f = ftp_connect(HOST);
$res = ftp_login($f, USER, PASS);
$fname = 'archive_2018-09-18_13-39';
$fsize = ftp_size($f, "$fname-img.zip").'';
$fsize2 = filesize("backup/$fname-img.zip").'';
echo $fsize . '<br>' . $fsize2;
and it returns:
22907946995
22907946995
The real script works like this:
$f = ftp_connect(HOST);
$res = ftp_login($f, USER, PASS);
$fname = 'archive_' . date('Y-m-d_H-i');
exec("zip -r -0 backup/$fname-img.zip \"website\" 2>&1");
exec('curl -T "' . "backup/$fname-img.zip" . '" ftp://' . HOST . ' --user ' . USER . ':' . PASS . ' 2>&1');
$fsize = ftp_size($f, "$fname-img.zip").'';
$fsize2 = filesize("backup/$fname-img.zip").'';
echo $fsize . '<br>' . $fsize2;
and it shows:
-1
22907946995
Real script uploads file just fine. It just doesn't show correct size on the FTP server.
So it's not a problem with size of the file and not a problem with FTP connection.
Try moving ftp_connect only after the call to curl. There is possibly some caching involved that prevents the FTP server from returning correct size immediately, if the file is uploaded using a different connection.
Though I'd strongly suggest you to use PHP functions to upload the file.

PHP - FTP Server - Unable to switch to newly created directory (sometimes!)

What I am trying to do
Connect to FTP server
Create new directories
Upload file into one of those new directories
What's going wrong?
Ok, so there is nothing wrong with the ftp connection, I am logging in with the credentials, switching to the relevant starting directory, which in this case is a directory on the server called "test".
At the start, this "test" directory is empty, as I just created it.
What I am then doing is taking a file from my local machine and attempting to upload that the remote path test/Folder1/Sub1/Sub2/Myfile.txt on the server.
To do this, I first split the path by "/" and check to see if I can switch to each of those directories, and if I can't, then I create them:
(You'll have to excuse the debugging dumps in the code)
// Split the path by directories and try and create all of them if they don't exist
$workingDir = $this->dir;
$newPath = str_replace($this->dir, "", $path);
$split = array_filter( explode("/", $newPath) );
if ($split)
{
foreach($split as $dir)
{
// Can we change to it?
if (!#ftp_chdir($this->conn, $workingDir . '/' . $dir)){
// Try and make the directory
if (!#ftp_mkdir($this->conn, $workingDir . '/' . $dir)){
var_dump("failed to make: " .$workingDir . '/' . $dir );
return false;
}
// Set the permissions to the default
$this->chmod = 0777;
ftp_chmod($this->conn, $this->chmod, $workingDir . '/' . $dir);
var_dump("Successfully made directory: " . $workingDir . '/' . $dir . " with permissions: " . $this->chmod);
}
$workingDir .= '/' . $dir;
}
}
This works fine, and I get the output of:
'Successfully made directory: /home/conn/test/Folder1 with permissions: 511' (length=74)
'Successfully made directory: /home/conn/test/Folder1/Sub1 with permissions: 511' (length=79)
'Successfully made directory: /home/conn/test/Folder1/Sub1/Sub2 with permissions: 511' (length=84)
If i exit at this point I can confirm the directories now exist on the remote server, with permissions of 0777
Next bit is to do the file upload into the new directory:
var_dump("Use this new name: {$newName}");
$filename = (($newName) ? $newName : $file->getFileName());
var_dump("working in remote directory: {$this->dir}");
var_dump("upload to remote: {$filename}, from: {$file->getFullPath()}");
// Change to that directory?
$split = explode("/", $filename);
$realFileName = array_pop($split);
$filedir = implode("/", $split);
var_dump("calling ftp_chdir() to : {$filedir}");
if (!#ftp_chdir($this->conn, $filedir)){
var_dump("couldn't change to {$filedir}");
return false;
};
var_dump( ftp_pwd($this->conn) );
var_dump("actual file name: " . $realFileName);
return ftp_put($this->conn, $realFileName, $file->getFullPath(), FTP_BINARY);
And again, this works fine. I get all the expected dumps:
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:121:string 'Use this new name: Folder1/Sub1/Sub2/Myfile.txt' (length=47)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:124:string 'working in remote directory: /home/conn/test' (length=44)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:125:string 'upload to remote: Folder1/Sub1/Sub2/Myfile.txt, from: C:\Ampps\www\duckfusioncore\app\lotto\tmp\tmp-nsEMH1RsDX' (length=110)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:131:string 'calling ftp_chdir() to : Folder1/Sub1/Sub2' (length=42)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:139:string '/home/conn/test/Folder1/Sub1/Sub2' (length=33)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:140:string 'actual file name: Myfile.txt' (length=28)
C:\Ampps\www\duckfusioncore\app\lotto\controllers\IndexController.php:28:boolean true
All the directories exist. The file is uploaded. All is well.
Except, if I now change the path I want to upload to and change toa new sub directory, which doesn't yet exist, e.g: Folder1/Sub1/NewSub/Myfile.txt
This is where it all goes wrong.
So the script runs through the create directory part again, and it successfully creates the new directory "NewSub", with the exact same permissions as before, and I can confirm that the directory exists on the remote server.
Except now when we get to the upload part, even though the directory exists, and this worked previously as we saw, it is unable to change to that new directory:
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:121:string 'Use this new name: Folder1/Sub1/NewSub/Myfile.txt' (length=49)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:124:string 'working in remote directory: /home/conn/test' (length=44)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:125:string 'upload to remote: Folder1/Sub1/NewSub/Myfile.txt, from: C:\Ampps\www\duckfusioncore\app\lotto\tmp\tmp-XJYdx8eduL' (length=112)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:131:string 'calling ftp_chdir() to : Folder1/Sub1/NewSub' (length=44)
C:\Ampps\www\duckfusioncore\sys\lib\helpers\datastore\stores\FTPStore.php:135:string 'couldn't change to Folder1/Sub1/NewSub' (length=38)
C:\Ampps\www\duckfusioncore\app\lotto\controllers\IndexController.php:28:boolean false
The directory 100% exists. And it has the same 0777 permissions as the other ones.
I'm just very confused as to why it is unable to switch to the directory, when it defintely exists and it has the same permissions as the other directories, which it had no problem switching to before...
Has anyone got any clue what might be the problem? Is there any extra debugging I can do on the ftp_chdir() function call to see if it gives me a reason?
Thanks.

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.";
}

Connect to remote afp server using PHP

I'm trying to make a php script to connect to an afp server and get a directory listing (with each file size). The server is local in our office, but I'm unable to just make a script on the afp server side. On my machine, I use something like this:
$filesInDir = array();
$filesInMySQL = array();
if (is_dir($uploadDir)) {
$dh = opendir($uploadDir);
if ($dh) {
$file = readdir($dh);
while ($file != false) {
$path = $uploadDir . "/" . $file;
$type = filetype($path);
if ($type == "file" && $file != ".DS_Store" && $file != "index.php") {
$filesInDir[] = $file;
}
$file = readdir($dh);
}
closedir($dh);
} else {
echo "Can't open dir " . $uploadDir;
}
} else {
echo $uploadDir . " is not a folder";
}
But I can't connect to the afp server. I've looked into fopen it doesn't allow afp, and I don't think it'd allow directory listing:
opendir("afp://ServerName/path/to/dir/");
Warning: opendir() [function.opendir]: Unable to find the wrapper "afp" - did you forget to enable it when you configured PHP? in...
Warning: opendir(afp://ServerName/path/to/dir/) [function.opendir]: failed to open dir: No such file or directory in...`
I'm not looking to see if a file exists, but to get the entire directory listing. Eventually I'll also have to remotely copy files into an output directory.
eg.
mkdir afp://ServerName/output/output001/
cp afp://ServerName/path/to/dir/neededfile.txt afp://ServerName/output/output001/
Maybe use http://sourceforge.net/projects/afpfs-ng/ to mount it...
I'm developing on an Mac Mini, so I realised I could just mount the afp share, and use readdir. I had to mount the drive using the following:
sudo -u _www mkdir /Volumes/idisk
sudo -u _www mount_afp -i afp://<IP>/sharename/ /Volumes/idisk/
Further details here

Categories