opening and viewing a file in php - php

how do i open/view for editing an uploaded file in php?
i have tried this but it doesn't open the file.
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
i've also tried this but it wont work.
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);
what i have in mind is like when you want to view an uploaded resume,documents or any other ms office files like .docx,.xls,.pptx and be able to edit them, save and close the said file.
edit: latest tried code...
<?php
// Connects to your Database
include "configdb.php";
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM employees") or die(mysql_error());
//Puts it into an array
while($info = mysql_fetch_array( $data ))
{
//Outputs the image and other data
//Echo "<img src=localhost/uploadfile/images".$info['photo'] ."> <br>";
Echo "<b>Name:</b> ".$info['name'] . "<br> ";
Echo "<b>Email:</b> ".$info['email'] . " <br>";
Echo "<b>Phone:</b> ".$info['phone'] . " <hr>";
//$file=fopen("uploadfile/images/".$info['photo'],"r+");
$file=fopen("Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt","r") or exit("unable to open file");;
}
?>
i am getting the error:
Warning: fopen(Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt): failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/uploadfile/view.php on line 17
unable to open file
the file is in that folder, i don't know it wont find it.

It might be either:
A permissions issue on the server. If it's a linux machine, try chmod 754 Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt (you may need root).
An issue with apache (or whatever webserver you might be using). Make sure you've defined a directory entry in the config file for that site. Documentation here.
Although, if I recall properly, an odt file will just be binary data rather than the text information. That might be what you're looking for, I don't know. If you just want to read the actual text, and you aren't interested in using some library to extract it, you need to save it as plain text. If you're actually trying to edit these files in the browser, you're gonna need a lot more than just fopen.

For text based files you can use file_get_contents and file_put_contents
However, ODT files are zip compressed XML files so you need to decompress them first:
$zip = new ZipArchive;
$res = $zip->open('Applications/XAMPP/xamppfiles/htdocs/uploadfile/images/file.odt');
if ($res === TRUE) {
$zip->extractTo('/tmp/myOdt.xml');
$zip->close();
}
$data = file_get_contents('/tmp/myOdt.xml');
$data .= 'add this to the end';
file_put_contents('path/to/file.txt', $data);
However, it seems your problem regards the actual path of the file. Try using a relative path instead: "images/file.odt"

Related

Unable to append (read and write) text file with php. Using fopen() and fwrite() together

I recently installed Apache, PHP and started working on a small project.
I have the following code.
<?php
$tim=time();
$ip=$_SERVER['REMOTE_ADDR'];
$ipadd=$tim."IPaddress".$ip;
$fp="user_log.txt";// file address
$myfilea = fopen($fp,"a");//open file
fwrite($myfilea,$ipadd.PHP_EOL);//add data to file
echo fread($myfilea,filesize($fp));//read file
fclose($myfilea);//close file
?>
Here is what I can do... I can either use "a" mode to add text or I can use "r" mode to read text. I cant do both. I tried using "a+","r+","ar" etc.
Did I miss something during my setup ???
I am running this on windows 8.1.
Thanks for your help.
You need to rewind the file pointer.
$tim = time();
$ip = $_SERVER['REMOTE_ADDR'];
$ipadd = $tim.'IPaddress'.$ip;
// file address
$fp = 'user_log.txt';
//open file
$myfilea = fopen($fp, 'a+');
//add data to file
fwrite($myfilea, $ipadd.PHP_EOL);
// your file pointer is at the end of the file now
// so rewind before you read
rewind($myfilea);
//read file
echo fread($myfilea, filesize($fp));
//close file
fclose($myfilea);
Try this code, use file_put_contents
file_put_contents = Write a string to a file
$fp="user_log.txt";
$tim=time();
$ip=$_SERVER['REMOTE_ADDR'];
$ipadd=$tim."IPaddress".$ip;
$myfile = file_put_contents($fp, $ipadd.PHP_EOL , FILE_APPEND | LOCK_EX);
And for your code try this, it will check able to open file or not
fopen("logs.txt", "a") or die("Unable to open file!");

create txt file list from php

I have bunch of images file (.jpg) in a folder, then I want to list them to a single file text, I using php (xampp in windows).
This for list images name in my browser (it's working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
echo $filenames."<br />";
}
?>
This for create text file called 'images_list.txt' (not working):
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
$data = echo $filenames."<br />";
fwrite($handle, $data);
}
?>
When I execute that script, appear warning message
"
Parse error: syntax error, unexpected 'echo' (T_ECHO) in D:\xampp\htdocs\rename_file_php\try_list_img.php on line 7"
If line 7, I change
$data = $filenames;
The file 'images_list.txt' will created, but only fill one image name listing in the file. Can anyone help me?
Sorry for my bad english.
Open file once and try to write data once:-
<?php
ob_start();
$file='F:\images\upload\google\ready_45';
$data = '';
foreach (glob($file."\*.jpg") as $filenames) {
$data .= $filenames."\n";
}
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $data);
fclose($handle);
?>
You want to fopen() the file only once, so outside the loop. Otherwise you overwrite the content again and again. Take a look at this modified version:
<?php
$folder = 'F://images/upload/google/ready_45';
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
foreach (glob($folder . "/*.jpg") as $filename) {
$data = $filename . PHP_EOL;
fwrite($handle, $data);
}
fclose($handle);
One certainly could simplify that. For example by simply imploding the list of matched file names with a linebreak and then writing the result in one go:
<?php
$folder = 'F://images/upload/google/ready_45';
$data = implode(PHP_EOL, glob($folder . "/*.jpg"));
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'w') or die("Cannot open file: ". $my_file);
fwrite($handle, $data);
fclose($handle);
However the first (loop based) approach allows more flexibility, for example filtering or escaping.
Side notes:
using a normal slash as folder delimiter (/) instead of the insane backslash (\\) natively used in MS-Windows will save you a lot of hassle. PHP can work with both on a MS-Windows platform.
using a line break instead of the html linewrap makes more sense when writing into a file in most cases. Using PHP_EOL instead of a hard coded line break (\r\n) will make your code portable for systems using different types of line breaks (only MS-Windows uses \r\n for that).
I took the liberty to also fix some indentation and code styling issues. It definitely makes sense if programmers loosely agree on some standard to enhance readability of code.
This is all you need:
// Creates a newline separated list from the array returned by glob()
$files = glob ($folder.'/*.jpg');
$files = implode (PHP_EOL, $files);
∕∕ This is all that is needed to write something to a file.
file_put_contents ($my_file, $files);
The fopen() and all that is old, old code, which should be avoided whenever possible. Not only is this method simpler and easier to read, but it's also generally faster.
Note that you might want to wrap an IF statement around the last line, in order to handle any errors with writing that might crop up.
Following code is working fine, I have a images folder which is having some image files, please change the folder path and try the below code
<?php
ob_start();
$file='images';
foreach (glob($file."\*.jpg") as $filenames) {
$my_file = 'image_list.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
$data = $filenames."\r\n";
fwrite($handle, $data);
}
?>

My php script won't open files that aren't in its root directory

This is a php script for a user login system that I am developing.
I need it to read from, and write to, the /students/students.txt file, but it won't even read the content already contained in the file.
<?php
//other code
echo "...";
setcookie("Student", $SID, time()+43200, "/");
fopen("/students/students.txt", "r");
$content = fread("/students/students.txt", filesize("/students/students.txt"));
echo $content;
fclose("/students/students.txt");
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
//other code
?>
You are not using fopen() properly. The function returns a handle that you then use to read or edit the file, for example:
//reading a file
if ($handle = fopen("/students/students.txt", "r"))
{
echo "info obtained:<br>";
while (($buffer = fgets($handle))!==false)
{ echo $buffer;}
fclose($handle);
}
//writing/overwriting a file
if ($handle = fopen("/students/students.txt", "w"))
{
fwrite($handle, "hello/n");
fclose($handle);
}
Let me know if that worked for you.
P.S.: Ty to the commentators for the constructive feedback.
There are many ways to read/write to file as others have demonstrated. I just want to illustrate the mistake in your particular approach.
fread takes a file handle as param, NOT a string that represents the path to the file.
So your line:
$content = fread("/students/students.txt", filesize("/students/students.txt")); is incorrect.
It should be:
$file_handle = fopen("/students/students.txt", "r");
$content = fread($file_handle, filesize("/students/students.txt"));
Same thing when you write contents to file using fwrite. Its reference to the file is a File Handle opened using fopen NOT the filepath. when opening a file using fopen() you can also check if the $file_handle returned is a valid resource or is false. If false, it means the fopen operation was not successful.
So your code:
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
Needs to be re-written as:
$file_handle = fopen("/students/students.txt", "w");
fwrite($file_handle, $content."\n".$SID);
fclose($file_handle);
You can see that fclose operates on file handles as well.
File Handle (as per php.net):
A file system pointer resource that is typically created using fopen().
Here are a couple of diagnostic functions that allow you to validate that a file exists and is readable. If it is a permission issue, it gives you the name of the user that needs permission.
function PrintMessage($text, $success = true)
{
print "$text";
if ($success)
print " [<font color=\"green\">Success</font>]<br />\n";
else
print(" [<font color=\"red\">Failure</font>]<br />\n");
}
function CheckReadable($filename)
{
if (realpath($filename) != "")
$filename = realpath($filename);
if (!file_exists($filename))
{
PrintMessage("'$filename' is missing or inaccessible by '" . get_current_user() . "'", false);
return false;
}
elseif (!is_readable($filename))
{
PrintMessage("'$filename' found but is not readable by '" . get_current_user() . "'", false);
return false;
}
else
PrintMessage("'$filename' found and is readable by '" . get_current_user() . "'", true);
return true;
}
I've re-written your code with (IMO) a cleaner and more efficient code:
<?php
$SID = "SOMETHING MYSTERIOUS";
setcookie("Student", $SID, time()+43200, "/");
$file = "/students/students.txt"; //is the full path correct?
$content = file_get_contents($file); //$content now contains /students/students.txt
$size = filesize($file); //do you still need this ?
echo $content;
file_put_contents($file, "\n".$SID, FILE_APPEND); //do you have write permissions ?
file_get_contents
file_get_contents() is the preferred way to read the contents of a
file into a string. It will use memory mapping techniques if supported
by your OS to enhance performance.
file_put_contents
This function is identical to calling fopen(), fwrite() and
fclose() successively to write data to a file. If filename does not
exist, the file is created. Otherwise, the existing file is
overwritten, unless the FILE_APPEND flag is set.
Notes:
Make sure the full path /students/students.txt is
correct.
Check if you've read/write permissions on /students/students.txt
Learn more about linux file/folder permissions or, if you don't access to the shell, how to change file or directory permissions via ftp
Try to do this:
fopen("students/students.txt", "r");
And check to permissions read the file.

Developing a text editor with PHP

I've started a small project trying to make an online text editor, it WAS going well until the system started overwriting files and adding spaces in unnecessarily. I have one file called editor.php where all the file loading, saving and editing is done.
So this is the opening/closing for the files:
<?php
if(isset($_POST['new'])){
$filer = substr(md5(microtime()),rand(0,26),6);
$file_create = $filer.".txt";
$handle = fopen("files/".$file_create,"w");
fclose($handle);
header("Location: editor.php?e=".$filer);
}
$file = $_GET['e'];
$file = basename($file);
$filename = "files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
file_put_contents($filename, $_POST['text']);
}
?>
further down the page I have this in a <textarea> tag:
<?php
echo $file_content;
?>
This uses the string from the file_get_contents();
But when I save, nothing happens, in fact it erases the file, when I load a file there are eight spaces but nothing else.
I know there is another way to do this with fopen() and if someone could give me a method to use that, it would be much appreciated.
You have to verify if the $_POST['text'] actually has a content in it.
if(isset($_GET['e'])){
$file = $_GET['e'];
$file = basename($file);
$filename = $_SERVER['DOCUMENT_ROOT']."/files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
if(!empty($_POST['text']) && isset($_POST['text']))
{
$length = strlen($_POST['text']);
if($length > 0)
file_put_contents($filename, trim($_POST['text']));
else
die("No content");
}
}
}
ALso check if the file exists and its writable. You can use chmod,mkdir and file_exists functions.
Have a look at PHP's file modes: http://php.net/manual/en/function.fopen.php
If you are opening all your files using fopen() in w mode then your files are being truncated as they are opened. This is how w mode operates. Try using a+ or c+ modes with fopen().
EDIT
Also, the file_put_contents() will also overwrite file contents unless you sett the FILE_APPEND flag, e.g. file_put_contents($file, $data, FILE_APPEND).

Manage several files in PHP

I'm testing php because I'm a freshman in this matter. I put my php code in a free server, they let me do my own index.php, manage some php variables (like register_globals, magic_quotes_gpc etc. I left them as default), but apparently I can handle not more than one file in a php code, for example:
<?php
//--------Updating Data-------------
$cdc = intval($_POST['cantidadDeCapitulos']);
$toWrite = array('ctot' => $cdc);
for($i=1;$i<$cdc+1;$i += 1){
$toWrite["cap".$i] = $_POST['numdeCap'.$i];
}//---------------------------------
$datos = file_get_contents("myfile.json.");
$toWrite = json_encode( $toWrite );
//Open a file in write mode
$fp = fopen("myfile2.json", "w");
if(fwrite($fp, "$toWrite")) {
echo "&verify=success&";
} else {
echo "&verify=fail&";
}
fclose($fp);
?>
If I comment out the line $datos = file_get_contents("myfile.json."); it's alright!, something is written in myfile2.json but if it is uncommented, the data is not updated. Both files have permission 666 and they are in the same directory i.e., /root.
$datos = file_get_contents("myfile.json.");
Seems like a typo has occurred. Take off the final dot from your file. I mean, change the line to:
$datos = file_get_contents("myfile.json");
try this:
<?php
$file = 'myfile.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Write the contents back to the file
file_put_contents($file, $current);
?>

Categories