Creating a function in PHP - php

I use this often and would like to turn it into a function:
$f = fopen('../images/snotel/'. $name .'.pdf','w+');
fwrite($f, $pdf);
fclose($f);
$conv='/usr/bin/convert../images/snotel/'. $name .'.pdf ../images/snotel/'. $name .'.jpg';
system ($conv);
This is what I've tried but it doesn't seem to work:
function pdf2jpg($name)
{
$f = fopen('../images/snotel/'. $name .'.pdf','w+');
fwrite($f, $pdf);
fclose($f);
$conv='/usr/bin/convert../images/snotel/'. $name .'.pdf ../images/snotel/'. $name .'.jpg';
system ($conv);
}
...
pdf2jpg('wsr');

As it is, your function tries to write the file with no data in the $pdf variable, because you did not pass it in.
You need to do one of two things:
This version takes the PDF data as an argument and creates the file in the function:
function pdf2jpg ($pdf, $name) {
$f = fopen('../images/snotel/'.$name.'.pdf','w');
fwrite($f,$pdf);
fclose($f);
$conv = '/usr/bin/convert ../images/snotel/'.$name.'.pdf ../images/snotel/'.$name.'.jpg';
//run
system($conv);
}
// Usage
pdf2jpg($pdf, 'wsr');
This version just takes the name, assuming that the file already exists:
function pdf2jpg ($name) {
$conv = '/usr/bin/convert ../images/snotel/'.$name.'.pdf ../images/snotel/'.$name.'.jpg';
//run
system ($conv);
}
// Usage
$name = 'wsr';
$f = fopen('../images/snotel/'.$name.'.pdf','w');
fwrite($f,$pdf);
fclose($f);
pdf2jpg($name);

Related

PHP - How to write a line in text file if line already available in file then count the request

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

fopen multiple files in php

I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php

Create dynamic text file with php function

So I need to create a dynamic text file based on the name of a variable in php (ex: dynamicName.txt). I then need to write other variables in the file.
$testVar = "test.txt";
function sendCalc(){
global $testVar;
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$testVar");
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
When I do the above, the file is created with no problem, and all the data is written successfully. However, this is not a dynamic file name.
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc(){
global $objName;
global $ext;
global $dynamicNameTxt;
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
When I try to concatenate the variable that contains the dynamic file name ($objName), with the $ext var, it does not want to create the file.
I echoed the $dynamicName var and it returns dynamicName.txt, so why doesn't this work with fopen. Essentially it has to be a problem with the concatenation right? If so, can I either concatenate a different way, or use a different method to open/create the file?
All help/ideas are appreciated.
I do not really know what you're trying to achieve with the line
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
if from what i understand it should just be a string:
$objCalcTxt = "C:\\xampp\\htdocs\\test.new\\upload\\".$dynamicNameTxt;
Also I'd suggest you provide the needed variables as arguments for the function insted of using globals
function sendCalc($objName, $ext, $dynamicNameTxt){
...
}
You are declaring the global variables inside your function. This could destroy their initial values.
Instead of using global variables in your function, rather pass the variables as arguments:
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc(objName, $ext, $dynamicNameTxt)
{
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\$dynamicNameTxt");
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
}
Your other option is to specifically call the global variable:
global $objName;
global $ext;
global $dynamicNameTxt;
$objName = "dynamicName";
$ext = ".txt"
$dynamicNameTxt = $objName.$ext;
function sendCalc()
{
$objCalcTxt = ("C:\\xampp\\htdocs\\test.new\\upload\\".$GLOBAL['dynamicNameTxt']);
$fp = fopen($objCalcTxt, 'x');
fwrite($fp, "Test\n");
fclose($fp);
}

Read and iterate .txt in PHP

I sense that I am almost there.
Here is a .txt file, which is about 60 Kbytes and full of German words. Every word is on a new line.
I want to iterate through it with this code:
<?php
$file = "GermanWords.txt";
$f = fopen($file,"r");
$parts = explode("\n", $f);
foreach ($parts as &$v)
{
echo $v;
}
?>
When I execute this code, I get: Resourceid#2
The word resource is not in the .txt, I do not know where it comes from.
How can I manage to show up all words in the txt?
No need for fopen just use file_get_contents:
$file = "GermanWords.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents); // this is your array of words
foreach($lines as $word) {
echo $word;
}
fopen() just opens the file, it doesn't read it -- In your code, $f contains a file handle, not the file contents. This is where the word "Resource" comes from; it's PHP's internal name for the file handle.
One answer would be to replace fopen() with file_get_contents(). This opens and reads the file in one action. This would solve the problem, but if the file is big, you probably don't want to read the whole thing into memory in one go.
So I would suggest instead using SplFileObject(). The code would look like this:
<?php
$file = "GermanWords.txt";
$parts = new SplFileObject($file);
foreach ($parts as $line) {
echo $line;
}
?>
It only reads into memory one line at at time, so you don't have to worry about the size of the file.
Hope that helps.
See the PHP manual for more info: http://php.net/manual/en/splfileobject.construct.php
$f, the result of fopen is a resource, not the contents of the file. If you just want an array of the lines contained in the file, you can use file:
$parts = file('GermanWords.txt');
foreach($parts as $v){
echo $v;
}
Alternatively, if you want to stick with fopen you can use fread to read the content:
$f = fopen('GermanWords.txt', 'r');
// read the entire file into $contents
$contents = fread($f, filesize('GermanWords.txt'));
fclose($handle);
$parts = explode("\n", $contents);
The SplFileObject provides a way to do that :
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
echo $file->fgets();
}
And if you prefer the foreach loop, you can create a generator function for that :
function lines($filename) {
$file = new SplFileObject($filename);
while (!$file->eof()) {
yield $file->fgets();
}
}
foreach (lines('German.txt') as $line) {
echo $line;
}
Reading the entire content of the file (with file_get_contents) before treating it can be memory consuming.
If you want to treat a file line by line, this class might help you.
It implements an Iterator (see phpdoc about it), that can be walked through in a foreach loop. Only the last line read is stored in memory.
class TxtFileIterator implements \Iterator{
protected $fileHandler;
protected $key;
protected $current;
protected $fileName;
function __construct($fileName){
$this->fileHandler = fopen($fileName, "r") or die("Unable to open file!");
$this->fileName = $fileName;
$this->key = 0;
}
function __destruct(){
fclose( $this->fileHandler );
}
//Iterator interface
public function current (){
return $this->current;
}
public function key (){
return $this->key;
}
public function next (){
if ( $this->valid() ){
$this->current = fgets( $this->fileHandler );
$this->key++;
}
}
public function rewind (){
$this->__destruct();
$this->__construct( $this->fileName );
}
public function valid (){
return !feof( $this->fileHandler );
}
Usage :
$iterator = new TxtFileIterator("German.txt");
foreach ($iterator as $line) {
echo $line;// or do whatever you want with line
}

php fgets function stuck the server

I have function build_additional_docs which calls another function that do few actions, but first it's call to function read_all_file, which extract the file to string variable and return it.
It's worked perfect when the function create_file_node has been called from another function.
but when it's called from build_additional_docs, the client wait to server untill time out...
I think that the function fail on fgets().
Additional comment: When I call function create_file_node whith with the same files, and the different is that file name is static string, and I have no foreach loop, the code works again...
here is my code:
function build_additional_docs($dir_name, $addDocsArr){
foreach ($addDocsArr as $doc) {
if($summery != ''){
$fileName = $dir_name . '\\' . $doc;
create_file_node($fileName);
}
}
function create_file_node($fileName){ global $base_url;
try{
$text = read_all_file($fileName);
}
catch (Exception $ex){
// some message here
}
return 0;
}
function read_all_file($file_name){
$file_handle = fopen($file_name, "r");
while (!feof($file_handle)) {
$line[] = fgets($file_handle);
}
fclose($file_handle);
return implode('',$line);
}
Found the mistake!
$addDocsArr variable is return value from explode() function for split string to seperated files names. The returned array include strings of file name with spacial characters that cannot be seen...
so when i add the code:
$fileName = $dir_name . '\\' . substr($doc, 0,strlen($doc) - 1);
the code worked.

Categories