PHP fopen() with command line - php

ANSWER I WENT WITH BELOW!
So I have a PHP script that works prefect via the web. I would like to set it up on a scheduled task on the server that is running the web hosting. It is a windows 2008 R2 server. I seems to run fine minus the fact it won't make the output files. Do I need to have the full path name? Ex C:\logs.... or will below work? I would like to keep the script working both in web and command line.
$File3 = "" . $log_dir . "/" . date('m-d-Y') . ".txt";
$Handle3 = fopen($File3, 'a+');
$Data3 = "blah";
fwrite($Handle3, $Data3);
more info:
here are the errors from the log file:
fwrite() expects parameter 1 to be resource, boolean given in C:\Websites\wordpress\win\import.php on line 686
PHP Warning: file_get_contents(bins/bins-10-09-2013.txt): failed to open stream: No such file or directory in C:\Websites\wordpress\win\import.php on line 692
PHP Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\Websites\wordpress\win\import.php on line 699
PHP Warning: fclose() expects parameter 1 to be resource, boolean given in C:\Websites\wordpress\win\import.php on line 709
WORKING!! Well, this is what I went with and it seems to work prefect.
$File = "" . $uploads_dir . "/import-" . date('m-d-Y-g-ia') . ".txt";
$Handle = fopen($file1, 'a+');
if ( $Handle === false ) {
$File = "C:\Websites\wordpress\win\\".$uploads_dir."\import-" . date('m-d-Y-g-ia') . ".txt";
$Handle = fopen($File, 'a+');
}
This way I can Use the php script both via web and on a scheduled task via windows.

It seems fopen is failing to open the file . Make sure the file is successfully opened :
$Handle3 = fopen($File3, 'a+');
if( $Handle3 === false ) echo 'Unable to open file';
If it fails , check below items one at a time :
Check file / folder permissions .
Check with different slashes "/" , "\" in the path .
Check if it works with absolute path ( full path ) .
Check by changing directory before fopen : chdir('path\to\php\script')
etc .
If the issue is with the path , one way make it work both cases is :
// First try with the path that works from web
$File3 = "" . $log_dir . "/" . date('m-d-Y') . ".txt";
$Handle3 = fopen( $File3, 'a+' );
if( $Handle3 === false )
{
// It failed so may be scheduled task invoked the script
// So use the path that works in invoked by scheduled task
$File3 = "path\that\works\from\command\line";
$Handle3 = fopen( $File3 ,'a+' );
}
if( $Handle3 === false )
{
echo 'Failed to open file';
exit;
}
else
{
// What ever
}

I've never used the full url for an fopen or fwrite. These are the things I would look at first:
What is the output when you echo $log_dir?
Does the directory exist?
Are permissions set correctly?
If you create the file before running the script, does it then successfully write to the file?
What is the value of $Handle3 after the fopen?
What is the return value of the fwrite that you call on the last line?
Is error handling set to all? (it should be for debugging)

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)

Permission of CSV-file in PHP

My php file has multiple errors. The first one has to do something with permissions. Normally there's nothing wrong with it it, but now I use a csv-file. I think that's the problem. But I don't understand the other warnings.
Which permission do I have to add?
$filename = "menuitems.csv";
$fp = fopen($filename, "r");
while ($data = fgetcsv($fp, filesize($filename), ",")) {
if (trim($data[0]) == '') break;
$href = strtolower(substr($data[1], 0, 7));
if ($href == "http://")
print "<li> " . $data[0] . "</li>\n";
else
print "<li> <a href=\"" . data[1] . "\" >" . $data[0] . "</a></li>\n";
}
fclose($fp);
echo "</ul>\n";
echo "</div>\n";
Warning: fopen(menuitems.csv): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/basis/php/index.php on line 10
Warning: fgetcsv() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/basis/php/index.php on line 11
Warning: fclose() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/basis/php/index.php on line 21
the csv file that was moved into the document root does not have permissions set correctly. You can do this several ways, including changing permission in the file properties dialog (via right click menu) or use the php command:
chmod("/somedir/somefile", 0644);
but installing xampp in its own folder off the root directory instead of Program Files directory will fix this issue in most XAMPP versions.

file_get_contents doesn't write to a log file

I am trying to write content to a log file using form input data. This doesn't seem to work on a server that's is using php version 5.3.14 but when i put the same code on a server that uses 5.3.27 its working. Does any one have an idea on how to fix this?
Below is my code that i am using for my form action. incoming.log is the file that i am trying to write to and is found in the folder path live/lms on the server. Please not that i am not getting any errors.
<?php
$system_path = '/live/lms/';
$fh = fopen($system_path . "incoming.log", "a");
fwrite($fh, "\nReceived:\n" . date("Y-m-d H:i:s") . "\n" . file_get_contents("php://input"));
fclose($fh);
?>
Not exactly an answer, but advise:
You should add more error handling ...and structure the script in a way so you can add more error handling.
For starters (work in progress):
<?php
$system_path = '/live/lms/';
$fhSource = fopen('php://input', 'rb');
if (!$fhSource) {
trigger_error('fopen input: '. print_r(error_get_last(), true), E_USER_ERROR );
}
$fhTarget = fopen($system_path . "incoming.log", 'a');
if (!$fhTarget) {
trigger_error('fopen output: '. print_r(error_get_last(), true), E_USER_ERROR );
}
$cb = stream_copy_to_stream($fhSource, $fhTarget);
var_dump($cb);
fclose($fhSource);
fclose($fhTarget);

PHP Script fopen failed to open stream: > Invalid argument Error

I am getting a warning.
Warning: fopen(76561197992146126 .txt): failed to open stream:
Invalid argument in C:\wamp\www\Download\t3.php on line 6
For anyone wondering, this is the contents of main.txt below (http://pastebin.com/53chSRRz)
<?php
$APIkey = 'APIKeyHere';
$file = file('C:\wamp\www\Download\main.txt');
foreach ($file as $link) {
$link2 = "http://api.steampowered.com/ITFItems_440/GetPlayerItems/v0001/?key=" . $APIkey . "&SteamID=" . $link . "&format=json";
$downloaded = file_get_contents($link2);
$fh = fopen($link . ".txt", "a"); //or die("can't open file");
fwrite($fh, $downloaded);
}
echo "Finished";
?>
If I replace "fopen($link . ".txt", "a")" with a static file-name it works. But I need $link to be the filename. It is imperative to my setup.
I am running Windows 7 x64 using WAMP 2.2 with PHP 5.4.3
Your link IDs have whitespace in them. Try adding $link = trim($link); before creating $link2.

fopen Permission denied on a file with 777 permissions

Since the title of this post is pretty much self-explanatory, I'll just jump to the code :
echo sprintf('%o', fileperms('test.txt'))."<br/>";
fopen("test.txt", "w");
And with this I get :
100777
fopen(test.txt): failed to open stream: Permission denied
Any ideas ?
Edit : Problem solved : there were access control lists on the server that were not configured correctly.
Thanks !
I think its possible that you have write/read permissions on the file but not on the folder. Try this in the public root of your website and see if you can read or write the file.
For safe mode (http://php.net/manual/en/function.fopen.php), php doc's say the following:
Note: When safe mode is enabled, PHP checks whether the directory in
which the script is operating has the same UID (owner) as the script
that is being executed.
Last you also need to be sure that php has access to the folder you are trying to write to.
I had same issue: folder was 777, but fopen does not worked. fopen said permission deny. Make sure your script have a 'good' permissions. maybe it will help you:
echo $dst, file_exists($dst) ? ' exists' : ' does not exist', "\n";
echo $dst, is_readable($dst) ? ' is readable' : ' is NOT readable', "\n";
echo $dst, is_writable($dst) ? ' is writable' : ' is NOT writable', "\n";
$fh = fopen($dst, 'w');
if ( !$fh ) {
echo ' last error: ';
var_dump(error_get_last());
}
I think the problem you are having is file ownership issue ... you can use this to find out the problem
error_reporting(E_ALL);
ini_set('display_errors','On');
$file = "a.jpg";
echo sprintf ( '%o', fileperms ( $file ) ), PHP_EOL;
echo posix_getpwuid ( fileowner ( $file ) ), PHP_EOL; // Get Owner
echo posix_getpwuid ( posix_getuid () ), PHP_EOL; // Get User
if (is_file ( $file )) {
echo "is_file", PHP_EOL;
;
}
if (is_readable ( $file )) {
echo "is_readable", PHP_EOL;
;
}
if (is_writable ( $file )) {
echo "is_readable", PHP_EOL;
}
fopen ( $file, "w" );
I just ran into this issue, and unfortunately the error message provided no clue to the actual reason. I had to give 777 to the file of the class included in the file that gave the error message. The error message only said the php file that calls that class, which already had 777.
So, check the file that is mentioned in the error message (let's say index.php), and then check which classes are instantiated within that file (class-file.php, class-writer.php, etc). Then check the permissions of those files (class-file.php, class-writer.php).
Once I gave permissions for the class file, it worked normally. Perhaps the webhost changed something in their config, since everything worked until a few days ago.

Categories