Why wont my filesize() method work? - php

Why wont my filesize() method work? My path works for the fread() and file() methods, but it wont acknowledge the path on filesize(). Why not? What should my correct path be?
<?php
$strLessonDescription = fopen("http://nova.umuc.edu/~ct386a28/lovej2ee/exercise5/content/lesson5.txt", "r")
or die ("Error - lesson5.txt cannot be opened");
$lessonDescription = fread($strLessonDescription,
filesize("http://nova.umuc.edu/~ct386a28/lovej2ee/exercise5/content/vocabulary5.txt"));
fclose($strLessonDescription);
echo $lessonDescription;
$arrLessonVocabulary = array();
$arrLessonVocabulary = file("http://nova.umuc.edu/~ct386a28/lovej2ee/exercise5/content/vocabulary5.txt");
if (arrLessonVocabulary == NULL)
print "Error - vocabulary5.txt cannot be opened";
?>

Since the file you're trying to read is via a remote request, rather than local file, it significantly changes how you want to read that data. Per the fread() manual page, you need to read the file in chunks. Alternatively, try using file_get_contents() which should simplify your code:
$lessonDescription = file_get_contents('http://nova.umuc.edu/~ct386a28/lovej2ee/exercise5/content/vocabulary5.txt');
echo $lessonDescription;

Related

MAMP strange behaviour : php read external file from an http:// is very slow, but from https:// is quick

I have a simple PHP script to read a remote file line-by-line, and then JSON decode it. On the production server all works ok, but on my local machine (MAMP stack, OSX) the PHP hangs. It is very slow, and takes more than 2 minutes to produce the JSON file. I think it's the json_decode() that is freezing. Why only on MAMP?
I think it's stuck in while loop, because I can't show the final $str variable that is the result of all the lines.
In case you are wondering why I need to read the file line-by-line, it's because in the real scenario, the remote JSON file is a 40MB text file. My only good performance result is like this, but any good suggestion?
Is there a configuration in php.ini to help solve this?
// The path to the JSON File
$fileName = 'http://www.xxxx.xxx/response-single.json';
//Open the file in "reading only" mode.
$fileHandle = fopen($fileName, "r");
//If we failed to get a file handle, throw an Exception.
if($fileHandle === false){
error_log("erro handle");
throw new Exception('Could not get file handle for: ' . $fileName);
}
//While we haven't reach the end of the file.
$str = "";
while(!feof($fileHandle)) {
//Read the current line in.
$line = fgets($fileHandle);
$str .= $line;
}
//Finally, close the file handle.
fclose($fileHandle);
$json = json_decode($str, true); // decode the JSON into an associative array
Thanks for your time.
I found the cause. It is path protocol.
With
$filename = 'http://www.yyy/response.json';
It freezes the server for 1 to 2 minutes.
I changed the file to another server with https protocol, and used
$filename = 'https://www.yyy/response.json';
and it works.

How to pass php vairables to a fopen

I'm struggling to use a php function, fopen with multiple variables.
I have two variables: $language is the extension ( E.G. .php ) and $url is a random number generated at the start of the script.
Here is my code but it always throws the die statement and doesn't work
$filename = "tools/scripts/tool".$language."?id=".$url;
$fh = fopen($filename, "w") or die("There Was An Error With The Script.");
Thanks
fopen will open the files content itself. It doesn't parse the file.
You might use exec() or you can call the file over a webserver.
fopen('http://localhost/yourfile.php?param='.$param);
Not to mention, that you are trying to write to a file there... ,"w")
yourfile.php?param=123 <- is not a valid filename

Cannot open file using fopen (php)

I am trying to open a file for reading in php script but having trouble.
This is my code
$fileHandle = fopen("1234_main.csv", "r")or die("Unable to open");
if (!file_exists($fileHandle))
{
echo "Cannot find file.";
}
The script is in the same directory as the file I am trying to read and there are no other read/write permission errors as I can create/read other files in the same directory.
When I run the script I just get the "Cannot find file" error message. Why is this error message being shown? Surely if fopen() can't open the file the "or die statement" should end the script?
Also, why can't I open the file when it definitely exists and is in the same location as the script (I have also tried using the full path of the filename instead of just the filename).
I am fairly new to php (but have exp in c++) so if its a stupid question I apologize.
Many thanks
In PHP, file_exists() expects a file name rather than a handle. Try this:
$fileName = "1234_main.csv";
if (!file_exists($fileName))
{
echo "Cannot find file.";
} else {
$fileHandle = fopen($fileName, "r")or die("Unable to open");
}
Also keep in mind that filenames have to be specified relative to the originally requested php-script when executing scripts on a web server.
You can use file_get_content() for this operation. On failure, file_get_contents() will return FALSE.For example
$file = file_get_contents('1234_main.csv');
if( $file === false ){
echo "Cannot find file.";
}
file_exists() take the file-name as input, but the logic of your code has problem. You first try to open a file then you check its existence?
You first should check its existence by file_exists("1234_main.csv") and if it exists try to open it.
file_exists takes a string, not a file handle. See http://php.net/manual/en/function.file-exists.php

Using a php://memory wrapper causes errors

I'm trying to extend the PHP mailer class from Worx by adding a method which allows me to add attachments using string data rather than path to the file.
I came up with something like this:
public function addAttachmentString($string, $name='', $encoding = 'base64', $type = 'application/octet-stream')
{
$path = 'php://memory/' . md5(microtime());
$file = fopen($path, 'w');
fwrite($file, $string);
fclose($file);
$this->AddAttachment($path, $name, $encoding, $type);
}
However, all I get is a PHP warning:
PHP Warning: fopen() [<a href='function.fopen'>function.fopen</a>]: Invalid php:// URL specified
There aren't any decent examples with the original documentation, but I've found a couple around the internet (including one here on SO), and my usage appears correct according to them.
Has anyone had any success with using this?
My alternative is to create a temporary file and clean up - but that will mean having to write to disc, and this function will be used as part of a large batch process and I want to avoid slow disc operations (old server) where possible. This is only a short file but has different information for each person the script emails.
It's just php://memory. For example,
<?php
$path = 'php://memory';
$h = fopen($path, "rw+");
fwrite($h, "bugabuga");
fseek($h, 0);
echo stream_get_contents($h);
yields "bugabuga".
Quickly looking at http://php.net/manual/en/wrappers.php.php and the source code, I don't see support for the "/' . md5(microtime());" bit.
Sample Code:
<?php
print "Trying with md5\n";
$path = 'php://memory/' . md5(microtime());
$file = fopen($path, 'w');
if ($file)
{
fwrite($file, "blah");
fclose($file);
}
print "done - with md5\n";
print "Trying without md5\n";
$path = 'php://memory';
$file = fopen($path, 'w');
if ($file)
{
fwrite($file, "blah");
fclose($file);
}
print "done - no md5\n";
Output:
buzzbee ~$ php test.php
Trying with md5
Warning: fopen(): Invalid php:// URL specified in test.php on line 4
Warning: fopen(php://memory/d2a0eef34dff2b8cc40bca14a761a8eb): failed to open stream: operation failed in test.php on line 4
done - with md5
Trying without md5
done - no md5
The problem here simply is the type and the syntax:
php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.
In short, the type you want is temp instead and the syntax you want is:
php://temp/maxmemory:$limit
The $limit is in bytes. You want to count that using safe byte functions.

Best way to download a file in PHP

Which would be the best way to download a file from another domain in PHP?
i.e. A zip file.
The easiest one is file_get_contents(), a more advanced way would be with cURL for example. You can store the data to your harddrive with file_put_contents().
normally, the fopen functions work for remote files too, so you could do the following to circumvent the memory limit (but it's slower than file_get_contents)
<?php
$remote = fopen("http://www.example.com/file.zip", "rb");
$local = fopen("local_name_of_file.zip", 'w');
while (!feof($remote)) {
$content = fread($remote, 8192);
fwrite($local, $content);
}
fclose($local);
fclose($remote);
?>
copied from here: http://www.php.net/fread
You may use one code line to do this:
copy(URL, destination);
This function returns TRUE on success and FALSE on failure.

Categories