How can i get output in sequence rather than random in PHP - php

Hi i have some values in 1.txt and want to show them in sequence one by one rather than random and also on click of a button not on reload. And i don't have much code on it. Can anyone help me with it please. ?
index.php:
<?php $lines = file('1.txt');?> <?php echo $lines[array($lines)];?>
1.txt in list format vertically:
1
2
3
4
5

Writing PHP like this is bad practice:
<?php $lines = ...;?> <?php echo ....;?>
Better write like this:
<?php
$lines = ...;
echo ...;
Now to your problem, you should use sort to order an array see: https://www.php.net/manual/de/function.sort.php
The best way to print an array in PHP is foreach:
foreach ($lines as $line) {
echo "\n<p>" . $line;
}

I'm not sure what your saying with the push of button and reload.
But this code assumes you mean, once the list has been generated keep it in the same order to this visitor.
I do that using a session variable so that even if the user reloads the page the order will be the same (for this user), but different between different users.
session_start();
if(empty($_session['lines'])){
$_session['lines'] = file('1.txt');
shuffle($_session['lines']);
}
// For debug:
echo implode("<br>\n", $_session['lines']);

Related

Getting all from json api array using php

I wanna improve on how to fetch data from an API. In this case I want to fetch every app-id from the Steam API, and list them one per line in a .txt file. Do I need an infinite (or a very high-number) loop (with ++ after every iteration) to fetch everyone? I mean, counting up from id 0 with for example a foreach-loop? I'm thinking it will take ages and sounds very much like bad practice.
How do I get every appid {"appid:" n} from the response of http://api.steampowered.com/ISteamApps/GetAppList/v0001?
<?php
//API-URL
$url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
//Fetch content and decode
$game_json = json_decode(curl_get_contents($url), true);
//Define file
$file = 'steam.txt';
//This is where I'm lost. One massive array {"app": []} with lots of {"appid": n}.
//I know how to get one specific targeted line, but how do I get them all?
$line = $game_json['applist']['apps']['app']['appid'][every single line, one at a time]
//Write to file, one id per line.
//Like:
//5
//7
//8
//and so on
file_put_contents($file, $line, FILE_APPEND);
?>
Any pointing just in the right direction will be MUCH appreciated. Thanks!
You don't need to worry about counters with foreach loops, they are designed to go through and work with each item in the object.
$file = "steam.txt";
$game_list = "";
$url = "http://api.steampowered.com/ISteamApps/GetAppList/v0001";
$game_json = file_get_contents($url);
$games = json_decode($game_json);
foreach($games->applist->apps->app as $game) {
// now $game is a single entry, e.g. {"appid":5,"name":"Dedicated server"}
$game_list .= "$game->appid\n";
}
file_put_contents($file, $game_list);
Now you have a text file with 28000 numbers in it. Congratulations?

How to shuffle file before each session?

I searched all day on this forum but couldn't find any answer.
I use following php code to display the next line from myfile.txt on each pageload (looping when gone through entire file):
<?php
session_start();
$item = file("myfile.txt");
$itemCount = count($item);
if ($_SESSION['sess_row'] === NULL) {
$_SESSION['sess_row'] = 0;
} else {
$_SESSION['sess_row'] = ($_SESSION['sess_row'] + 1) % $itemCount;
}
echo $item[$_SESSION['sess_row']];
?>
Now I want to shuffle the lines in myfile.txt before each session.
For example, if myfile.txt contains 5 lines, it now displays lines in same order every session: 123451234512345...
With shuffle it should display one session: 325413254132541..., another session: 413254132541325..., another session: 142351423514235..., and so on.
How can above code be changed to shuffle myfile.txt before each session?
Use shuffle to shuffle your array each time.
$item = file("myfile.txt");
shuffle($item);
If you need to have different number for each user, you should have a database or something (it could be just a single file containing one number) to keep track of how many of your items are already assigned to users. Each time, read that number (call it cursor), assign the number associated with that cursor, increment the cursor by one and write it back to the file (or database ...)
If you need unique data, you can use array_unique:
$item = file("myfile.txt");
$item = array_unique($items);
shuffle($item);

Accessing variables in PHP files

Is there anyway to access variables of one php file into another?
- I am trying to validate a form. I need to access variables from the validationConditions.php file in form.php file.
I have tried creating sessions but they are error prone.
I am using the latest version of dreamweaver.
Is it possible to use $_POST to achieve the results?
Any example will be welcome...
Thanks a lot in advance.
The easiest would be to use session variables. In the first page you could set the values like this
session_start();
$_SESSION['myvar'] = 'My Data';
Then in the second page you can retrieve the data like this...
session_start();
$myvar = $_SESSION['myvar'];
Which in turn sets $myvar to "My Data"
You can read a php file with another php file. Assume that we have 2 php files.
new.php
<?php
$a="something";
?>
serach.php ---> search in new.php
<?php
// What to look for
$search = '$a'; //WE are searching $a
$lines = file('new.php'); // in new.php
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
?>
Something like that. You have to edit this file.
A somehow devious solution:
ob_start();
$request = array(
"_id"=>"0815",
"user"=>"john",
"email"=>"john#dunbar.com",
"phone"=>NULL
); // Don't know. Just how u need your request to look like.
include('validationConditions.php');
$response = getValidationConditions($request); // Function in 'validationConditions.php' that responds an array or a JSON
$out = ob_get_clean();
echo json_encode($out);

How to show 1 element of array dynamically with php?

in "file.txt" i have some numbers like 1234,123456,12345678 etc.
so i was wondering how i can get dynamically just one element, for example echo just 12345,then echo 123456, but one by one ???when user comes i want to show him one element,and then next time i want to show another element on the page, it would be good also if i could erase elements that i have echo...When i manually enter position it works... Please help...
I have a following code:
function test($n){
$file=file_get_contents("file.txt");
$array = explode(",", $file);
return print_r($array[$n]);
};
The solution will need deleting the number on your filesystem or marking it as already showed either on the filesystem or on the database, after the number gets echoed.
Shuffling the numbers or generating a random index will never quite be full proof since the same number could be shown again.
First of all, this is usually a terrible way of doing this.
It's much better to use a database, for example.
But you could do the following:
<?php
function getRandomNumber() {
// retrieve and parse the numbers
$numbers = file_get_contents('file.txt');
$numbers = explode(',' $numbers);
// select a random index
$randomIndex = array_rand($numbers);
// get the chosen number
$randomNumber = $numbers[$randomIndex];
// remove it from array
unset($numbers[$randomIndex]);
// save updated file
file_put_contents('file.txt', implode(',', $numbers));
return $randomNumber;
}

Removing Lines in php ? Is this possible?

I have been struggling to create a Simple ( really simple ) chat system for my website as my knowledge on Javascripting/AJAX are Limited after gather resources and help from many kind people I was able to create my simple chat system but left with one problem.
The messages are posted to a file called "msg.html" in this format :
<p><span id="name">$name</span><span id="Msg">$message</span></p>
And then using PHP and AJAX I will retrieve the messages instantly from the file using the
file(); function and a foreach(){} loop withing PHP here is the code :
<?php
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
if(count($data) > $max_lines){
// here i want the data to be deleted from oldest until i only have 20 messages left.
}
foreach($data as $line_num => $line){
echo $line_num . " . " . $line;
}
?>
My Question is how can i delete the oldest messages so that i am only left with the latest 20 Messages ?
How does something like this seem to you:
$file = 'msg.html';
$data = file($file);
$max_lines = 20;
foreach($data as $line_num => $line)
{
if ($line_num < $max_lines)
{
echo $line_num . " . " . $line;
}
else
{
unset($data[$line_num]);
}
}
file_put_contents('msg.html', $data);
?>
http://www.php.net/manual/en/function.file-put-contents.php for more info :)
I suppose you can read the file, explode it into an array, chop off everything but last 20 fields and write it back to file, overwriting the old one... Perhaps not the best solution but one that comes to mind if you really cant use database as Delan suggested
That's called round-robin if I recall correctly.
As far as I know, you can't remove arbitrary portions of a file. You need to overwrite the file with the new contents (or create a new file and remove the old one). You could also store messages in individual files but of course that implies up to $max_lines files to read.
You should also use flock() to avoid data corruption. Depending on the platform it's not 100% reliable but it's better than nothing.

Categories