How do I read a file from a destination to variable? - php

I am trying to read a file's content, while doing something like this
$con="HDdeltin";
$fp = fopen($_SERVER['DOCUMENT_ROOT']. "/HDdeltin/Users/$con", "r");
echo $fp;
It doesn't return anything. What am I doing wrong?

Fast solution :
file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/HDdeltin/Users/HDdeltin");
Use file_get_contents(), and you can prevent bad url with realpath().
$con = "HDdeltin";
$path = realpath($_SERVER['DOCUMENT_ROOT'] . "/HDdeltin/Users/$con");
echo file_get_contents($path);
To get current root, you can also use :
getcwd() function.
dirname(__FILE__), you can get more here.
See more :
faster fopen or file_get_contents?

you can read by using this function
echo file_get_contents($_SERVER['DOCUMENT_ROOT']. "/HDdeltin/Users/$con");

You will likely need to use file_get_contents. http://php.net/manual/en/function.file-get-contents.php
Here is the example they provide:
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
So you will likely need to use
$fp = file_get_contents($_SERVER['DOCUMENT_ROOT']. "/HDdeltin/Users/$con", true);
echo $fp;
There are some differences between PHP versions it seems
<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
So be sure to check out the first link provided.

fopen return a resource, not the text
Use file_get_contents($_SERVER['DOCUMENT_ROOT']. "/HDdeltin/Users/$con") instead

Related

PHP. How to read a file, if it is writing without a problem with "a+", but is not readable with "r"?

I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:
$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);
Here I read the file:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
// Result is TRUE
}
if(is_readable ($file)){
// Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);
The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.
file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:
$peer_id = file_get_contents($fileLocation);
That is the same for is_readable:
if(is_readable($fileLocation)){
// Result is FALSE
}
So full code should be something like:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
$peer_id = file_get_contents($fileLocation);
} else {
echo 'Error message about file being inaccessible here';
}
The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:
file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);

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.

PHP fwrite writing empty file

I'm trying to make this save a file and it creates the file, but it's always empty. This is the code for it:
<?php
$code = htmlentities($_POST['code']);
$i = 0;
$path = 'files/';
$file_name = '';
while(true) {
if (file_exists($path . strval($i) . '.txt')) {
$i++;
} else {
$name = strval($i);
$file_name = $path . $name . '.txt';
break;
}
}
fopen($file_name, 'w');
fwrite($file_name, $code);
fclose($file_name);
header("location: index.php?file=$i");
?>
I echoed out $code to make sure it wasn't empty, and it wasn't. I also tried replacing
fwrite($file_name, $code);
with this:
fwrite($file_name, 'Test');
and it was still empty. I have written to files a couple of times before in PHP, but I'm still really new to PHP and I have no idea whats wrong. Could someone tell me what I'm doing wrong or how to fix this? Thanks
Reading/Writing to/from a file or stream requires a resource handle:
$resource = fopen($file_name, 'w');
fwrite($resource, $code);
fclose($resource);
The resource handle $resource is essentially a pointer to the open file/stream resource. You interact with the created resource handle, not the string representation of the file name.
This concept also exists with cURL as well. This is a common practice in PHP, especially since PHP didn't have support for OOP when these methods came to be.
Take a look of the samples on php.net

Save website sourecode to file via php

Hi I wan to save the sourecode of http://stats.pingdom.com/w984f0uw0rey to some directory in my website
<?php
if(!copy("http://stats.pingdom.com/w984f0uw0rey", "stats.html"))
{
echo("failed to copy file");
}
;
?>
but this does not work either for me:
<?php
$homepage = file_get_contents('http://stats.pingdom.com/w984f0uw0rey');
echo $homepage;
?>
But I cannot figure how to do it!
thanks
use
<?
file_put_contents('w984f0uw0rey.html', file_get_contents('http://stats.pingdom.com/w984f0uw0rey'));
?>
be sure that the script has write privileges to the current directory
Use file_get_contents().
The best variant you can do in PHP is to use stream_copy_to_stream:
$url = 'http://www.example.com/file.zip';
$file = "/downloads/stats.html";
$src = fopen($url, 'r');
$dest = fopen($file, 'w');
echo stream_copy_to_stream($src, $dest) . " bytes copied.\n";
If you need to add HTTP options like headers, use context options with the fopen call. See as well this similar answer which shows how. It's likely you need to set a user-agent and things so that the other website's server believes you're a browser.

Response any web page in the internet from a PHP file

How can I create a simple PHP file, which will retrieve the HTML and the Headers of any web page in the internet, change images/resources url to their full url (for example: image.gif to http://www.google.com/image.gif), and then response it?
Okay first of all to get the headers use the PHP get_headers function.
<?php
$url = "http://www.example.com/";
$headers = get_headers($url, true);
?>
Then read the content of the page into a variable.
<?php
$handle = fopen($url, r);
$content = '';
while(! feof($handle)) {
$text .= fread($handle, 8192);
}
fclose($handle);
?>
You then need to run through the content looking for resources and pre-pending the url to get the absolute path to the resource if it isn't already an absolute path. The following regex example will work on src attributes (e.g. images and javascript) and should give you a starting point to look at other resources such as CSS which uses href="". This regex won't match if a : is in the source a good indicator that it contains http:// and is therefore an absolute path. PLEASE NOTE this is by no means perfect and won't account for all sorts of weird and wonderful resource locations but it's a good start.
<?php
$pattern = '#src="([0-9A-Za-z-_/\.])+"#';
preg_match_all($pattern, $text, $matches);
foreach($matches[0] as $match) {
$src = str_replace('src="', '', $match);
$text = str_replace($match, 'src="' . $url . $src, $text);
}
print($text);
?>
<?
$file = "http://www.somesite/somepage";
$handle = fopen($file, "rb");
$text = '';
while (!feof($handle)) {
$text .= fread($handle, 8192);
}
fclose($handle);
print($text);
?>
I think what you're looking for is a PHP Proxy script. There are several on the internet - this is one I created (although don't have time to fix bugs at the moment).
I would recommend using one which is already created over one which you've written yourself, as it's not a trivial thing to do (there are better scripts than mine available as well).

Categories