If have a file A.php which for sure have some lines, and i want to export or copy specific lines from A.php to a new file B.php, So the process goes like this (copy lines from x to y in the A.php- Create a new file with name B.php- Past and save B.php).
So if i want to extract lines from 3 to 8 (for example) in the following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<?php
$fname= basename(__FILE__,'php');
?>
<title><?php echo $fname; ?></title>
</head>
<body>
<p>This is a test Page</p>
</body>
</html>
How can i do this in details if you can?
From the documentation here:
http://php.net/manual/en/function.file.php
This command splits the file into an array of lines:
// substitute a local file for the URL
$lines = file('http://php.net/manual/en/function.file.php');
echo $lines[0];
// <!DOCTYPE html>
echo $lines[56];
// <![endif]-->
After you have the lines you want you can create a new file and save it. There are 100 ways to do this. Here is one:
http://php.net/manual/en/function.file-put-contents.php
file_put_contents('fileInCurrentDirectory.php', $lines[3], FILE_APPEND | LOCK_EX);
file_put_contents('fileInCurrentDirectory.php', $lines[4], FILE_APPEND | LOCK_EX);
file_put_contents('fileInCurrentDirectory.php', $lines[5], FILE_APPEND | LOCK_EX);
You can use file to convert the file into an array of lines, then array_slice to get the lines you want and finally file_put_contents to export to the new file. Like this:
function A2B($a,$b,$from,$to){
$f = file($a,FILE_IGNORE_NEW_LINES);
$n = array_slice($f,($from-1),($to-$from+1));
file_put_contents($b,implode("\n",$n));
}
and call it like
A2B("a.php","b.php",3,6);
Related
I have page view counter script which fwrite in a .txt file and I echo it in another file where I have to display the page views. The counter updating script is:
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "could not open the file" ;
} else {
$counter = (int ) fread($handle,20);
fclose ($handle);
$counter++;
$handle = fopen("counter.txt", "w" );
fwrite($handle,$counter) ;
fclose ($handle) ;
}
The above code writes (fwrite) page views in file name counter.txt
And the page where I want to show page views is also a combination of HTML and PHP. The code I have added there is following which read views and displays it
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "could not open the file" ;
} else {
$counter = ( int ) fread ($handle,20) ;
}
echo $counter;
The above code shows the page views. It reads from the counter.txt file and displays page views.
I am getting abnormal error for this. When I am trying to access the file via desktop it shows wrong page view. It adds extra 1 view. for e.g. if there is only 1 page view it shows 2
But on android or ios devices it is working fine. For android or ios devices it showing correct count. I want to know is there any problem with the code? In short above script is showing +1 (extra 1 view) every time. (only for laptops or pc's)
<?php
// page-count.php - to be included in other files
class hitcounter{
private $file;
private static $instance=false;
private function __construct($file){
$this->file=$file;
}
public static function initialise( $file ){
if( !self::$instance ) self::$instance=new self( $file );
return self::$instance;
}
public function write(){
$i=$this->read();
$i++;
file_put_contents($this->file,$i,LOCK_EX);
}
public function read(){
return file_exists($this->file) ? (int)file_get_contents($this->file) : 0;
}
public function display(){
printf('<p>Page hits: %s</p>Filename: %s',$this->read(),$this->file);
}
}
$file=sprintf('counter-%s.txt',ip2long($_SERVER['REMOTE_ADDR']));
$oHit=hitcounter::initialise( $file );
?>
The page that will update the textfile
<?php
require 'page-count.php';
# log the page view to the text file
$oHit->write();
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Update & display hitcount</title>
</head>
<body>
<h1>Update & View PageView count</h1>
<a href='view-page-count.php'>View counter</a> | <a href='javascript:location.reload(true)'>Reload</a>
<?php
# display the hit count
$oHit->display();
?>
</body>
</html>
The page that will view the results only ( view-page-count.php )
<?php
require 'page-count.php';
// do NOT log this page view - only display the count
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Display hitcount</title>
</head>
<body>
<a href='javascript:history.go(-1)'>Previous Page</a>
<h1>This page only VIEWS logfile - it does NOT update it.</h1>
<?php
$oHit->display();
?>
</body>
</html>
As stated by others, doing a counter with a simple file in PHP is not a good idea. There are many hits on a webpage you are not aware of (e.g. search-engines, known and unknown spiders, normal visitors, ...). These may or may not interfere and want access to this file at the same time. This results in unclear situations which may result in weird errors. Therefore the foremost hint is to use a database which is able to lock the data during access and makes it safe to add the data.
Lets look into your code:
One of the biggest problem is, that writing your file means the OS clears the file and rewrites it. In the worst case it means a harddisc starts, positiones itself at the file, tries to open it, clears it, writes data to it and closes it afterwards. This will take many cycles - enough time to get interrupted by others who try to visit your page as well. Sure a SSD works much faster but not in terms of data-collisions.
If you cannot use a Database we need to try to "lock" your file for single-usage. Here is your updated code:
$handle = fopen("counter.txt", "r");
if(!$handle){
echo "could not open the file" ;
} else {
$counter = (int ) fread($handle,20);
fclose ($handle);
$counter++;
$handle = fopen("counter.txt", "w" );
if (flock($handle, LOCK_EX | LOCK_NB)) {
fwrite($handle, $counter) ;
flock($handle, LOCK_UN); // open the lock again
}
fclose ($handle) ;
}
This tries to lock your file. If it is not lockable it will not block the further execution but pass the fwrite-line. You can remove the LOCK_NB but this means your server will wait till the block is liftet and this may take a while. Blocking a webserver is not a good idea so maybe not counting a visitor is the better way.
A third - a bit more complex - way is to write unique files for visitors in a directory and an automatic collector (e.g. cron-job) of the votes who has a single access to your visitor-file. This way you get no collisions.
Happy coding.
I want to create a file (index.php) that will dynamically add the below code to the head of another file called (index2.php) and then display the page with the modified code.
<link rel="stylesheet" type="text/css" href="new.css">
<script src="new.js"></script>
<script>
new();
</script>
I know the way to do this without modifying the code is
include 'index2.php';
However I do not know how to add the code to the head section of index2.php
How would I go about doing this?
Maybe it's just:
index2.php:
...
<head>
<?php require("./index.php"); ?>
</head>
...
?
Put index2.php file's head tag code in a diffrent file. and then include that php file in index.php file's tag
like
index.php
include_once('siffrent_file_name.php');
....
After doing some pondering I felt like I didn't want to parse the entire HTML document, so I added a "key" to index2.php and used this code:
$file = "index2.php";
$key = "<!-- KEY -->";
$appcode = 'link rel="stylesheet" type="text/css" href="new.css">
<script src="new.js"></script>
<script>
new();
</script';
$index = fopen($file, "r") or die("Unable to open index symlink");
$code= fread($index,filesize("index2.php"));
fclose($index);
$index_app = (preg_replace ($key, $appcode, $code));
echo($index_app);
I have read the thread Writing a new line to file in PHP pasted the exact code of there in my own netbeans IDE but didn't work. The pasted code (with some minor changes) was:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$i = 0;
$file = fopen('ids.txt', 'w');
$gemList=array(1,2,3,4,5);
foreach ($gemList as $gem)
{
fwrite($file, $gem."\n");
$i++;
}
fclose($file);
?>
</body>
</html>
I also tried to write in a new line of file using another code. My code goes like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>
</body>
</html>
but the result in the text file is
12345
and what I expect is
1
2
3
4
5
I greatly appreciate any help. Also my Netbeans version is 8.2 and my running OS is Windows 10.
With your current code, check the page source and it is giving you the correct result.
But remember that you are running it on an html page so if you want a new line, use the <br> tag.
foreach ($gemList as $gem)
{
fwrite($file, $gem."<br>");
$i++;
}
fclose($file);
HTML does not take new lines \n into consideration, unless you specifically set the CSS property white-space:pre;
Ibu's answer is correct if you are displaying on a webpage.
For your fwrite() call, be sure the text viewer you are using understands \n as the EOL character. In other words if you are on Windows, and will only work with the resulting file(s) on Windows, a \n\r (new line and carriage return) is what you want to use for your EOL character(s)
Or, leave as-is, and use a text editor that supports "Unix style line endings" - Notepad++ does...
If you are viewing the content of your file in the browser (eg. echoed in PHP) you need to use the nl2br() PHP function to convert newlines to html's <br/>:
<div>
<?= nl2br(file_get_contents("testfile.txt")); ?>
</div>
Alternatively enclose the file content withing a with CSS white-space property set to "pre":
<div style="white-space: pre">
<?= file_get_contents("testfile.txt"); ?>
</div>
I'm really really new to PHP, so if you can explain it to me what my code is actually doing and why the result is what it is I would appreciate very much. I'm probably screwing up something very simple.
Basically I want to query a MySQL database, create a csv with the data, and download the csv. Pretty simple. Here is my code:
<?php
include("Includes/PHPheader.php");
$query_string = $_SERVER['QUERY_STRING'];
parse_str($query_string);
$sql = "SELECT many_columns_i_removed_from_this_sample_code FROM table WHERE id = '".$id."'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$f = fopen("csv/tmp.csv", "w");
fputcsv($f, array_keys($row),';');
fputcsv($f,$row,';');
rewind($f);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="tmp.csv"');
fpassthru($f);
fclose($f);
?>
There are some HTML code below it that shouldn't affect anything, but just in case here it is.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
</body>
</html>
Well, I thought this would download my csv with no problem. If I go to the csv folder, there it is, the tmp.csv file I created, with the proper header and data.
But when I open the tmp.csv file I downloaded, it is actually the html code of the page, and not the data I expected.
What is going on?
In case it helps, I'm using WebMatrix 3.0.
There are two things going on, probably. First, You are trying to read (fpassthru) from a file opened for writing (fopen(..., "w")), so You are not able to read anything from the file. Then, after that "reading nothing" goes Your HTML code, which naturally appends to Your output. Try this:
$f = fopen("csv/tmp.csv", "w+");
...
fclose($f);
exit;
Could you please try?
header("Content-type: application/vnd.ms-excel");
instead of
header('Content-Type: application/csv');
I have a test code of CSV output, have a look - https://foowms.googlecode.com/svn/trunk/stockincsv.php
A very informative thread of Stack Overflow
Setting mime type for excel document
==============================================
If csv file open, write and save, then you should do as follows-
$list = array ("Peter,Griffin,Oslo,Norway");
$file = fopen("csv/tmp.csv","w");
foreach ($list as $line) {
fputcsv($file,explode(',',$line));
}
fclose($file);
==============================================
You also could try this
fputcsv($fp, array_values($list), ';', ' ');
instead of
fputcsv($f, array_keys($row),';');
I have a script that I am working on in PHP that logs IP Address's of visters that go to that specific page. This is just a prototype. The script that I have concocted is working, but when it creates the TXT file containing the IP's it only does one line. How can I make it keep adding a line for every visitor regardless if they are a repeat visitor. I am not really sure how to go about that part, I am new to PHP.
Here is what I have so far:
<?PHP
$ip = getenv("REMOTE_ADDR");
$date = date("d") . " " . date("F") . " " . date("Y");
$intofile = $ip . "n" . $date;
$hfile = fopen("ip-address.txt", "w");
fwrite($hfile, $intofile);
fclose($hfile);
?>
<!DOCTYPE html>
<html language="en-us">
<head>
<title>IP Address Logging Software</title>
<link rel="stylesheet" type="text/css" href="Source/Stylesheet/DefaultPage.css" />
<link rel="stylesheet" type="text/css" href="Source/Stylesheet/DefaultPage.css" />
<link rel="stylesheet" type="text/css" href="Source/Stylesheet/DefaultPage.css" />
<script type="text/javascript" src="Source/Javascript/DefaultScript.css"></script>
<script type="text/javascript" src="Source/Javascript/DefaultScript.css"></script>
<script type="text/javascript" src="Source/Javascript/DefaultScript.css"></script>
</head>
<body language="en-us">
<?PHP
$ip=$_SERVER['REMOTE_ADDR'];
echo "<strong>Your IP Address <em>$ip</em> Has Been Logged</strong>";
?>
</body>
</html>
$hfile = fopen("ip-address.txt", "w");
Refer to the manual for fopen:
'w' Open for writing only; place the file pointer at the beginning of
the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
Everytime you open the file it is being truncated. Use the 'a+' instead, or another one that will open the file and append, rather than delete what's already there.
Alternatively use file_put_contents (http://php.net/manual/en/function.file-put-contents.php). Its basically a helper function that does the same as calling fopen(),fwrite(), and fclose().
And to make sure that it appends the content just add the FILE_APPEND flag:
file_put_contents('file.txt', 'Hello World', FILE_APPEND);