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);
Related
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)
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.";
}
I am trying to write a script in Yii for downloading files. view file isecho CHtml::link('Major Oilseeds: World Supply and Distribution.','downloadpdf', array('class'=>'btn btn-darkorange')); and the controller code is $path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/download/Major_Oilseeds.csv';
echo $path;
if(file_exists($path)){
Yii::app()->getRequest()->sendFile( 'Major_Oilseeds.csv' , file_get_contents($path) );
}
else{
echo '<br>File not found';
} the code echo $path dispalys the location as http://localhost/projectv2/download/Major_Oilseeds.csv and the download folder contains the file named "Major_Oilseeds.csv" but its always showing "File Not Found" Error. plz somebody help me to solve this. I have also tried the code $path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/download/Major_Oilseeds.csv';
// $filename = 'Major_Oilseeds.csv';
header('Content-Disposition: attachment; charset=UTF-8; filename="'.$path.'"');
$utf8_content = mb_convert_encoding($content, "SJIS", "UTF-8");
echo $utf8_content;
Yii::app()->end();
return; but its also not working :-(
file_exists can only work with local files. In your case you are trying to use file_exists with a URL.
You can find a workaround here: http://uk1.php.net/file_exists (please search for "http" in this page)
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)
I have a simple script that all I need it to do is create a directory with the name of the GET variable. When I run this script, it doesn't seem to create the directory. I would like this directory to be in the same directory as the PHP file.
$dir = $_GET['dir'];
umask(000);
mkdir($_SERVER['DOCUMENT_ROOT']."/".$dir."/",0777);
Put some error handling in there. Most of the time the error is self evident. The following snippet, lifted from PHP manual, shows you how.
$rs = #mkdir( $dirPath, 0777 );
if( $rs )
{
// success
}else{
// print error information
echo 'an error occurred. Attempting create folder';
echo '<br>dirPath: ' . $dirPath;
echo '<br>php_errormsg: ' . $php_errormsg;
}