I am using pdftk library for modify the pdf files. but i am getting the chmod(): Invalid argument error.
Following is my code :
include('fillpdf/createXFDF.php');
$fdf_file = 'fillpdf/acord.fdf';
$acord = array();
$acord['******'] = 'a';
$acord['******'] = 'a';
$pdf_file_url = 'http://localhost/******/fillpdf/Cancellation.pdf';
$fdf = createXFDF( $pdf_file_url, $acord );
// print_r($fdf); die;
if ($fp = fopen($fdf_file, 'w')) {
chmod($fdf, 777);
fwrite($fp, $fdf, strlen($fdf));
$CREATED = TRUE;
} else {
echo 'Unable to create file: ' . $fdf_file . '<br><br>';
$CREATED = FALSE;
}
// var_dump($CREATED); die;
fclose($fp);
$command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
exec($command);
I have given all the necessary permission to folder and files. but don't know what is wrong??
Thanks in advance!!!
Why you need to give chmod($fdf,0777); to $fdf. It's not even the file. as per your code the $fdf = createXFDF( $pdf_file_url, $acord ); is calling function and it's not file. so just comment the chmod($fdf,0777); line and check your code is working or not??
Hope it helps!!!
Try like this...For chmod() function first number is always zero.
chmod(file,mode);
The mode parameter consists of four numbers:
1.The first number is always zero
2.The second number specifies permissions for the owner
3.The third number specifies permissions for the owner's user group
4.The fourth number specifies permissions for everybody else
include('fillpdf/createXFDF.php');
$fdf_file = 'fillpdf/acord.fdf';
$acord = array();
$acord['******'] = 'a';
$acord['******'] = 'a';
$pdf_file_url = 'http://localhost/******/fillpdf/Cancellation.pdf';
$fdf = createXFDF( $pdf_file_url, $acord );
// print_r($fdf); die;
if ($fp = fopen($fdf_file, 'w')) {
chmod($fdf,0777);
fwrite($fp, $fdf, strlen($fdf));
$CREATED = TRUE;
} else {
echo 'Unable to create file: ' . $fdf_file . '<br><br>';
$CREATED = FALSE;
}
// var_dump($CREATED); die;
fclose($fp);
$command = '"C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe" C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation.pdf fill_form acord.fdf output C:\\xampp\\htdocs\\*******\\fillpdf\\Cancellation_new.pdf';
exec($command);
Related
I face this problem. When i try to open the file list in other server which is 10.200.4.202. The error below appears.
When I try using a local host, the file list can be viewed normally. I think the code is not the error but the server setting is not right.
I used IIS 10.0, PHP 7.3.15
This is what appears on web
status[parsererror] content[SyntaxError: Unexpected token < in JSON at position 0]
and this is the error in f12
Warning:
opendir(\\10.200.4.202\y\1.InspCheckSheet_PDF\log,\\10.200.4.202\y\1.InspCheckSheet_PDF\log): Access is denied. (code: 5) in C:\PGMPIS_Web\public_html\ics_filing\loglist_sub.php on line 68
Warning:
opendir(\\10.200.4.202\y\1.InspCheckSheet_PDF\log): failed to open dir: Bad file descriptor in C:\PGMPIS_Web\public_html\ics_filing\loglist_sub.php
on line 68
{"querytime":"2020-05-14 09:58:50","other_status":"ERR","errmsg":""}
Here's the code
<?php
$dir_log = '\\\\10.200.4.202\\y\\1.InspCheckSheet_PDF\\log';
require_once 'Log.php';
$log = Log::factory('file', 'log/okaspe.log', 'loglist_sub'); //$log->log('teeeeest!');
//$type = $_REQUEST['type'];
try{
// Set query_time
$emsg = "";
$now = new DateTime();
$res['querytime'] = $now->format('Y-m-d H:i:s');
//$res['querytime'] = $now->format('Y-m-d g:i:s A');
// Obtain log file name list → $fn[]
$cnt = $pos = 0;
unset($fn); // clear $fn for safety
if( $dir = opendir($dir_log) ) { // add # infront of opendir by asyraf
while (($file = readdir($dir)) !== false ) {
$pos = strpos ($file, 'main_'); // faster than preg_match() for simple search
if( $pos !== false && $pos == 0) {
$cnt++;
$fn[] = $file;
}
}
closedir($dir);
} else {
throw new Exception("Obtain Log File List failed......");
}
// sort in descending order
rsort($fn); //$log->log( print_r($fn, true) );
//set response
$res['list'] = $fn;
$res['cnt'] = $cnt;
} catch( Exception $e ) {
// Functional Err exception
$res["other_status"] = "ERR";
$res["errmsg" ] = $emsg;
$log->log($e->getMessage(), PEAR_LOG_ERR); // logging
} finally {
//DB disconnect (absolutely and always)
$pdo = null;
// Response in Json
header('Content-Type: application/json; charset=utf-8');
$json = json_encode( $res ); //$log->log($json, PEAR_LOG_ERR);
echo $json;
}
exit;
?>
I want to write a PHP code which write a string line in text file if the line already available in text file then count the requests for example
text file contain:
red.apple:1
big.orange:1
green.banana:1
If some one request to add big.orange in file if its already available in file then count as big.orange:2 if not available then write new line big.orange:1
after execution code text file
red.apple:1
big.orange:2
green.banana:1
I've written the following code but not working.
<?PHP
$name = $_GET['fname']
$file = fopen('request.txt', "r+") or die("Unable to open file!");
if ($file) {
while (!feof($file)) {
$entry_array = explode(":",fgets($file));
if ($entry_array[0] == $name) {
$entry_array[1]==$entry_array[1]+1;
fwrite($file, $entry_array[1]);
}
}
fclose($file);
}
else{
fwrite($file, $name.":1"."\n");
fclose($file);
}
?>
Instead of creating your own format which you need to parse manually, you can simply use json.
Below is a suggestion about how it would work. It will add the requested fname value if it doesn't already exist and will also create the file if it doesn't already exists.
$name = $_GET['fname'] ?? null;
if (is_null($name)) {
// The fname query param is missing so we can't really continue
die('Got no name');
}
$file = 'request.json';
if (is_file($file)) {
// The file exists. Load it's content
$content = file_get_contents($file);
// Convert the contents (stringified json) to an array
$data = json_decode($content, true);
} else {
// The file does not extst. Create an empty array we can use
$data = [];
}
// Get the current value if it exists or start with 0
$currentValue = $data[$name] ?? 0;
// Set the new value
$data[$name] = $currentValue + 1;
// Convert the array to a stringified json object
$content = json_encode($data);
// Save the file
file_put_contents($file, $content);
If you still need to use this format (like, this is some exam test or legacy), try the function:
function touchFile($file, $string) {
if (!file_exists($file)) {
if (is_writable(dirname($file))) {
// create file (later)
$fileData = "";
} else {
throw new ErrorException("File '".$file."' doesn't exist and cannot be created");
}
} else $fileData = file_get_contents($file);
if (preg_match("#^".preg_quote($string).":(\d+)\n#m", $fileData, $args)) {
$fileData = str_replace($args[0], $string.":".(intval($args[1])+1)."\n", $fileData);
} else {
$fileData .= $string.":1\n";
}
if (file_put_contents($file, $fileData)) {
return true;
} else {
return false;
}
}
I'm new to PHP. I planned to create folder, sub folder, into that file depends on user Input.
Folder and sub folders has been created successfully.
Finally I try to create a file its showing bellow error.
fopen(upload/localhost/hrms): failed to open stream: Permission denied
in C:\xampp\htdocs\ssspider\index.php on line 205
My code is:
$dir = "http://localhost:8080/hrms/index.php";
//make directory
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
mkdir($directoryForClient);
$splitePath = explode("/", $folderPath);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>";
mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen($dir,"w");
if($myFile)
{
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}
Please help me to find out my problem?
Edit: Thanks. I got an error. In fopen I didn't mention file name . Now its working fine. Thanks
because you open a directory , fopen function just open file. your code is fill with error , just Refer to the following:
<?php
//make directory
$host = "aa"; //define $host variable
$directoryForServer = "upload";
$directoryForClient = $directoryForServer."/".$host."";
#mkdir($directoryForClient);
$splitePath = explode("/", $directoryForClient);
$folderPath1 = $directoryForClient;
for($x = 1; $x <= (count($splitePath)-1) ; $x++)
{
$folderPath1 = $folderPath1."/".$splitePath[$x];
echo "<br>".$folderPath1." - successfully created<br>2";
#mkdir($folderPath1);
}
writefile($folderPath1);
function writefile($dir)
{
if( is_dir($dir)){
echo $dir;
$myFile = fopen("upload/aa.txt","w");
if($myFile)
{
$returned_content = "hello world"; //define variable and his content before write to file.
fwrite($myFile, $returned_content);
}
fclose($myFile);
}
}
I use newrelic to keep track of anything on my website and I always get this error:
Error message: E_WARNING: fclose() expects parameter 1 to be resource, boolean given
Stack trace: in fclose called at /etc/snmp/bfd-stats.php (68)
This is how /etc/snmp/bfd-stats.php looks like
<?php
$a = 0;
$ptr = 0;
$any = 0;
$mx = 0;
$ns = 0;
$cname = 0;
$soa = 0;
$srv = 0;
$aaaa = 0;
$txt = 0;
$total = 0;
if(file_exists('/etc/snmp/bfd-log-pos.stat')) {
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','r');
$string = fread($lfh,2087);
$res = explode(',',$string);
fclose($lfh);
}
else {
$res = array();
$res[0] = 0;
$res[1] = 0;
}
if(file_exists("/var/log/bfd_log.1")) {
$stats = stat('/var/log/bfd_log.1');
if($stats[10] > $res[0]) {
$res[0] = 0;
$res[1] = 0;
}
}
$fh = fopen('/var/log/bfd_log', 'r');
fseek($fh,$res[1]);
$blocks = 0;
if(!$fh) {
echo "Error! Couldn't open the file.";
} else {
while (!feof($fh)) {
$data = fgets($fh);
if(preg_match('/executed\sban/',$data)) {
$blocks++;
}
}
}
$lfh = fopen('/etc/snmp/bfd-log-pos.stat','w');
$timestamp = time();
$pos = ftell($fh);
fwrite($lfh,"$timestamp,$pos");
fclose($lfh);
if(!fclose($fh)) {
echo "Error! Couldn't close the file.";
}
print("bfd_blocks\n$blocks");
?>
On line 40: $fh = fopen('/var/log/bfd_log', 'r'); I looked at the directory /var/log and there is no file called bfd_log, I dont know if I have to create it by myself or it is automatically created.
Can anyone help me on fixing this error, Thanks in advance.
The error indicates that you are trying to pass a variable with a boolean value (true/false) to a function that needs a resource instead of a boolean value.
Please make sure that before you use resources from variables, the function that returns the resource has not run into trouble. Only on success perform the other functions that use this resource/variable.
$fh = fopen('/var/log/bfd_log', 'r');
// check fh before other functions use this variable
if (!$fh) {
echo "Error! Couldn't open the file.";
} else {
// perform task with resource $fh
fseek($fh, $res[1]);
[...]
$lfh = fopen('/etc/snmp/bfd-log-pos.stat', 'w');
// check before other code block is executed and use this variable
if( $lfh )
{
// perform task with resource $lfh
$pos = ftell($fh);
fwrite($lfh, "$timestamp,$pos");
fclose($lfh);
fclose($fh);
[...]
} else {
// lfh error
}
}
If you always check before using variables, you won't run into this error anymore.
I wrestled with this problem and could not find the answer until I separated my write check (put it first) from the actual file write code. So before I would open the file fopen/fwrite then do the is_writable check and then do the fclose and i would get this error.
To resolve I moved the is_writable and variable declaration before the fopen/fwrite and the error went away. Shown below (former php code position shown in comments) The first comment did help me realize this... Thank you.
$myfile = "/var/www/html/newfile.txt";
if (is_writable($myfile)) {
echo "The file is writable";
}
else {
echo "The file is not writable";
}
$txt = "$name, $email, $command, $searchtype, $keyword \n";
$myfile = fopen('/var/www/html/newfile.txt', 'w') or die("Unable to open file!");
fwrite($myfile, $txt);
// $myfile = "/var/www/html/newfile.txt";
// if (is_writable($myfile)) {
// echo "The file is writable";
// }
// else {
// echo "The file is not writable";
// }
fclose($myfile);
Try
$fh = fopen('/var/log/bfd_log', 'a+');
a+ mode will create the file if it does not exists
I need a script that is finding and then replacing a sertain line in a CSV like file.
The file looks like this:
18:110327,98414,127500,114185,121701,89379,89385,89382,92223,89388,89366,89362,89372,89369
21:82297,79292,89359,89382,83486,99100
98:110327,98414,127500,114185,121701
24:82297,79292,89359,89382,83486,99100
Now i need to change the line 21.
This is wat i got so far.
The first 2 to 4 digits folowed by : ar a catergory number. Every number after this(followed by a ,) is a id of a page.
I acces te id's i want (i.e. 82297 and so on) from database.
//test 2
$sQry = "SELECT * FROM artikelen WHERE adviesprijs <>''";
$rQuery = mysql_query ($sQry);
if ( $rQuery === false )
{
echo mysql_error ();
exit ;
}
$aResult = array ();
while ( $r = mysql_fetch_assoc ($rQuery) )
{
$aResult[] = $r['artikelid'];
}
$replace_val_dirty = join(",",$aResult);
$replace_val= "21:".$replace_val_dirty;
// file location
$file='../../data/articles/index.lst';
// read the file index.lst
$file1 = file_get_contents($file);
//strip eerde artikel id van index.lst
$file3='../../data/articles/index_grp21.lst';
$file3_contents = file_get_contents($file3);
$file2 = str_replace($file3_contents, $replace_val, $file1);
if (file_exists($file)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
if (file_exists($file3)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
// replace the data
$file_val = $file2;
// write the file
file_put_contents($file, $file_val);
//write index_grp98.lst
file_put_contents($file3, $replace_val);
mail('info#', 'Aanbieding catergorie geupdate', 'Aanbieding catergorie geupdate');
Can anyone point me in the right direction to do this?
Any help would be appreciated.
You need to open the original file and go through each line. When you find the line to be changed, change that line.
As you can not edit the file while you do that, you write a temporary file while doing this, so you copy over line-by-line and in case the line needs a change, you change that line.
When you're done with the whole file, you copy over the temporary file to the original file.
Example Code:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
This part is just setting up the basics: The category, the IDs of the articles and then building the related strings.
Now opening the file to change the line in:
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
The file is locked so that no other process can edit the file while it gets changed. Next to that file, the temporary file is needed, too:
$temp = new SplTempFileObject(4096);
After setting up the two files, let's go over each line in $file and compare if it needs to be replaced:
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
Now the $temporary file contains already the changed line. Take note that I used UNIX type of EOF (End Of Line) character (\n), depending on your concrete file-type this may vary.
So now, the temporary file needs to be copied over to the original file. Let's rewind the file, truncate it and then write all lines again:
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
And finally you need to lift the lock:
$file->flock(LOCK_UN);
And that's it, in $file, the line has been replaced.
Example at once:
$path = 'file';
$category = 21;
$articles = [111182297, 79292, 89359, 89382, 83486, 99100];
$prefix = $category . ':';
$prefixLen = strlen($prefix);
$newLine = $prefix . implode(',', $articles);
$file = new SplFileObject($path, 'r+');
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->flock(LOCK_EX);
$temp = new SplTempFileObject(4096);
foreach ($file as $line) {
$isCategoryLine = substr($line, 0, $prefixLen) === $prefix;
if ($isCategoryLine) {
$line = $newLine;
}
$temp->fwrite($line."\n");
}
$file->seek(0);
$file->ftruncate(0);
foreach ($temp as $line) {
$file->fwrite($line);
}
$file->flock(LOCK_UN);
Should work with PHP 5.2 and above, I use PHP 5.4 array syntax, you can replace [111182297, ...] with array(111182297, ...) in case you're using PHP 5.2 / 5.3.