Jump to content

[SOLVED] Calling a file??


DJTim666

Recommended Posts

Ok, say I made a txt file with 5000+ words in it, and I wanted to call them to be random. So when someone refreshes it will show, hello(one of the words in the file), then when they refresh again, it will say bang(another word in the file). It is going to be for a random word game that I am gunna code very shortly. It will be;

 

1. Someone types a word, then clicks enter.

2. It takes them to the next page where one of the words from the file are displayed.

 

So it will look like this;

 

You say: (whatever they type goes here).

 

The computer says: (one of the words from the file)

 

I know it sounds stupid, but it's gunna be cool once I figure out how to do the file thing.

 

Any help is appreciated.

 

--

DJ

Link to comment
https://forums.phpfreaks.com/topic/54933-solved-calling-a-file/
Share on other sites

Off the top of my head...

<?php
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$words = array(explode($contents, " "));
$length = count($words);
$num = rand(0, $length);
return $words[$num];
?> 

 

Did not test that.

Link to comment
https://forums.phpfreaks.com/topic/54933-solved-calling-a-file/#findComment-271672
Share on other sites

<?php
function getWord() {
$filename = "something.txt"; //specifies what file to use
$handle = fopen($filename, "r"); //opens a connection to the file
$contents = fread($handle, filesize($filename)); //from file, reads the entire filesize
fclose($handle); //close connection

//i assumed that your file contained only the words you wants separated by spaces
$words = explode(" ", $contents); //creates a list called $words
$length = count($words); //counts how many words in the list
$num = rand(0, $length-1); //generates a random number from 0 to the length of the list (-1 because it's inclusive)
return $words[$num]; //returns the word at the random position
}
?>
Random word: <?php echo getWord(); ?> 

 

So, the best way to use this would be to wrap it in a function and call the function when the page loads.

This is how that looks: http://www.charlieholder.com/randomWord.php

Here's the text file with the words: http://www.charlieholder.com/something.txt

 

I had a few errors in my code.

1. explode() returns an array so you don't have to wrap it in array().

2. explode() takes a delimiter and THEN a string, not the other way around.

Link to comment
https://forums.phpfreaks.com/topic/54933-solved-calling-a-file/#findComment-271807
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.