displaying random contents with php - php

I have a script with that it write a site url and site name in this format :
::<a href='http://master7np.tk>Master7np</a>::<a href='http://master-land.net>
Master-land</a>::<a href='http://nischal.tk>nischal.tk</a>
I want a php script that display this random url from point :: in a webpage
here is the original, but it is not working--I mean it only displays:
"<a href='http://master7np.tk>Master7np</a>"
but it should display randomly (not just the first one).
<?
$xfile = #file("/home/webtraff/public_html/ads.txt");
$random_num = rand (0,count($xfile)-1);
$udata = explode("::",$xfile[$random_num]);
echo "$udata[1]";
?>

Your instruction order is bit off. i changed how you read the file.
$file = file_get_contents("/home/webtraff/public_html/ads.txt"); //open the file as string removed the
$udata = explode("::",$file); //then we split by tokens
$udata = array_flip($udata); //change the values to keys
$text = array_rand($udata); //get a random key

change your code as following
<?php
$data = file_get_contents("/home/webtraff/public_html/ads.txt"); //open the file
$urls = explode("::",$data); //url split by separator
$number=rand(0,count($urls)-1); // Get random number
echo $urls[$number]; //random output
?>

Related

Display IMAGE OR DATA through external TXT File

I have file1.txt and A PHP Code which increment it.
I have a snippet to display the image.
I paste a snippet in my website that displays Images by reading the data number from file1.txt.
I use the snippet multiple times in one page but I get the same result. What happens is that when the website page is loaded it reads the file1.txt having ,lets say number 10, image number.
What I want is that Snippet 1 Displays 10 Increment file1.txt
then Snippet 2 Displays 11 and so on.
how should i make the snippet in such a way that it waits for the increment and then reads it and then it displays image.
Example:
Snippet 1 >10th Image
Snippet 2 >11th Image
Snippet 3 >12th Image
While all are executed in one page?
One Way i Think might be that the snippet GET the wait.txt and
checks if its 1 or 0 If It is 1 it waits for certain seconds then
execute the external php and if it is 0 it proceeds to executes the
external PHP. Then External PHP on Execution Sets wait.txt to
1 while its being used and then once it has finished it sets the
wait.txt to 0
But I doubt it will flawlessly work. I need you guys to help me out.
Okay the below code is what I have
The PHP Contains this:
$open = fopen("xml/file1.txt", "r+");
$num = fgets($open);
$close = fclose($open);
$num++;
$open = fopen("xml/file1.txt", "w+");
fwrite($open, $num);
$close = fclose($open);
The Snippet
<?php
$myFile = "../xml/file1.txt";
$line= file($myFile);//file in to an array
$image = $line[0]; //So that it Reads the first line if 2nd line has /n
echo "<img src=''.$image.'.img'></img>";
/*Executing PHP through php as it as additional code in php
which does some other verifications.*/
echo '<script src="//localhost/image.php"></script>';
?>
The file1.txt Contains:
1
//Ignore the comment here it just contain 1 number
//which increment each time the snippet executes the php
So I paste The snippet in one page Multiple times. But All snippet displays the same image instead of in ascending order. I want to find how can I do it? No MySql Database. And I don't want to list and read each line.
I want my snippet to read the data from file1.txt after it has been
updated
I want my snippet to know that the php is busy and needs to wait while other snippet is using it. As my project will include heavy traffic I want it Optimized.
Lastly I am a new to this so it's hard to figure out.
THE CODE BELOW WORKS BUT HOW CAN I OPTIMISE IT for heavy traffic?
<?php
session_start();
waitque();
function waitque() {
$input = $_SERVER['HTTP_HOST'];
$e = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$input = trim($input, '/');
// If not have http:// or https:// then prepend it
if (!preg_match('#^http(s)?://#', $input)) {
$input = 'http://' . $input;
}
$urlParts = parse_url($input);
// Remove www.
$dom = preg_replace('/^www\./', '', $urlParts['host']);
if(isset($_SESSION['worker'])){
$open = fopen("queue/imageindex.txt", "r+");
$value = fgets($open);
$close = fclose($open);
$value++;
$open = fopen("queue/imageindex.txt", "w+");
fwrite($open, $value); // variable is not restated, bug fixed.
$close = fclose($open);
$myFile = "queue/imageindex.txt";
$line= file($myFile);//file in to an array
$relid = $line[0];
echo $relid." Code PUBLISHED</div>";
unset($_SESSION['worker']);
} else {
echo "<div>waiting...</div>";
$_SESSION['worker']= $dom.$a.$ip;
waitque();
}
}
?>

Array is shown when printed but cannot compare it with a string in php

I am trying to write a php script to confirm an email address. I am using a file instead of a database to store user info which is outside the root directory. The file is csv.
When I try to store its contents in an array and print it, it works but when I try to compare an element from the array, it doesn't work. And also I want to write the email address of the user in csv as the last entry on the same line as other info.
Please help.
<?php
$rows[] = array();
$username = $_GET["username"];
$passkey = $_GET["passkey"];
$userdata = fopen("/****/*********/*****/$username.csv", "r");
$email = $_GET["email"];
$line = file_get_contents("/****/********/*****/$username.csv");
$rows = explode(",", $line);
print_r ($rows);
$newrows = trim($rows[6]);
$newpasskey = trim($passkey);
if($newrows == $newpasskey)
{
echo "Email-Id confirmed.";
fclose($userdata);
$userdata = fopen("/****/********/******/$username.csv", "a+");
fwrite($userdata, ",".$email);
fclose($userdata);
}
?>
I suggest you take a look at PHPs csv functions to ease loading/writing .csv data.
http://php.net/manual/en/function.fgetcsv.php and http://php.net/manual/en/function.fputcsv.php
Also, in your code, make sure that $username and $passkey are set, trimmed and sanitized before continuing.
You might also want to switch from GET to POST method in your form, I personally wouldn't want my password to be seen in the URL.
Try this:
$passkey = trim($passkey);
$stored_pass = trim($rows[6]);
if($stored_pass == $passkey)
{
//do stuff here
}
I found out the reason.I had made a mistake while entering the user info onto the file. I changed the php script that enters user info to the file. Now it works perfectly.

php get list of files as array, output 1 random file name with extension.

So what i am trying to do is get a list of text files from a directory.
take that list and randomly choose 1 file.
then take that file and print out the contents. now i did this a few years back. but can't find my old script. i tried what i have below just to print out a file name.. but event that is not working?
$path = '/seg1';
$files = scandir($path);
$seg = array ( $files );
$rand_keys = array_rand($seg, 1);
print $rand_keys;
Would love some new eyes on this as well as any input.
/*** Search All files in Dir. with .txt extension ***/
foreach (glob('./seg1/*.txt') as $filename)
{
$myFiles[] = $filename;
/*** Array of file names **/
}
/*** Total count of files ***/
$max=sizeof($myFiles);
/*** Select a Random index for Array with Max limit ***/
$fileNo=rand(0, $max);
/*** Path of the Random file to Access ***/
$file=$myFiles[$fileNo];
/*** Get the content from Text file ****/
$data = file_get_contents($file, true);
As your variable naming suggests, you randomly select one key out of the array; try getting the value by
$filename = $seg[$rand_keys];
$path = '/seg1';
$files = scandir($path));
if($files)
echo file_get_contents($files[mt_rand(2,count($files))]);
Recommend you use glob so you only get files you want, this excludes system directories like . and ..
foreach (glob("seg1/*.txt") as $filename) {
$seg[] = $filename;
}
Or an even simpler solution:
$rand_keys = array_rand(glob("seg1/*.txt"), 1);

Get 3 URLs from XML, randomly select one to save to variable

I'm in over my head at this point - but what i have currently looks like this:
<?php
$request_url = "http://aethereverywhere.tumblr.com/api/read?type=photo&tagged=ae&start=0&num=1";
$xml = simplexml_load_file($request_url);
$img = $xml->posts->post->{'photo-url'};
?>
If increase &num to 3, lets say - it'll pull three files, and simplexml_load_file will parse them out - and save them to $img - but what i'd like to is have only one URL saved to $img, selected at random.
Thanks for the help
New code: select a random image from 0 to 118 (total 119), then outputing, choose the highest resolution.
<?php
$request_url = "http://aethereverywhere.tumblr.com/api/read?type=photo&start=".rand(0,118);
$xml = simplexml_load_file($request_url);
$img = $xml->posts->post->{'photo-url'};
$img=(array)$img;
echo '<img src="'.$img[0].'">';
?>
Add a random number between 0 and the total photos -1. ie, get it in one line randomly.
$img = $xml->posts->post->{'photo-url'}[$random] // if that's the right syntax.
Or while iterating through the tags, do a random check for an even/odd number.
$img = (empty($img) || !$img) ? (rand(10)%2==0) ? $PHOTO_URL : FALSE : $img;
Do it like this:
$xml = simplexml_load_string($x); // assuming XML in $x, or use simplexml_load_file
$urls = $xml->xpath("//photo-url"); // get all <photo-url> nodes
echo $urls[rand(0,count($urls)-1)]; // echo a random url
see it working: http://codepad.viper-7.com/WDq0ha

Create Files Automatically using PHP script

I have a project that needs to create files using the fwrite in php. What I want to do is to make it generic, I want to make each file unique and dont overwrite on the others.
I am creating a project that will record the text from a php form and save it as html, so I want to output to have generated-file1.html and generated-file2.html, etc.. Thank you.
This will give you a count of the number of html files in a given directory
$filecount = count(glob("/Path/to/your/files/*.html"));
and then your new filename will be something like:
$generated_file_name = "generated-file".($filecount+1).".html";
and then fwrite using $generated_file_name
Although I've had to do a similar thing recently and used uniq instead. Like this:
$generated_file_name = md5(uniqid(mt_rand(), true)).".html";
I would suggest using the time as the first part of the filename (as that should then result in files being listed in chronological/alphabetic order, and then borrow from #TomcatExodus to improve the chances of the filename being unique (incase of two submissions being simultaneous).
<?php
$data = $_POST;
$md5 = md5( $data );
$time = time();
$filename_prefix = 'generated_file';
$filename_extn = 'htm';
$filename = $filename_prefix.'-'.$time.'-'.$md5.'.'.$filename_extn;
if( file_exists( $filename ) ){
# EXTREMELY UNLIKELY, unless two forms with the same content and at the same time are submitted
$filename = $filename_prefix.'-'.$time.'-'.$md5.'-'.uniqid().'.'.$filename_extn;
# IMPROBABLE that this will clash now...
}
if( file_exists( $filename ) ){
# Handle the Error Condition
}else{
file_put_contents( $filename , 'Whatever the File Content Should Be...' );
}
This would produce filenames like:
generated_file-1300080525-46ea0d5b246d2841744c26f72a86fc29.htm
generated_file-1300092315-5d350416626ab6bd2868aa84fe10f70c.htm
generated_file-1300109456-77eae508ae79df1ba5e2b2ada645e2ee.htm
If you want to make absolutely sure that you will not overwrite an existing file you could append a uniqid() to the filename. If you want it to be sequential you'll have to read existing files from your filesystem and calculate the next increment which can result in an IO overhead.
I'd go with the uniqid() method :)
If your implementation should result in unique form results every time (therefore unique files) you could hash form data into a filename, giving you unique paths, as well as the opportunity to quickly sort out duplicates;
// capture all posted form data into an array
// validate and sanitize as necessary
$data = $_POST;
// hash data for filename
$fname = md5(serialize($data));
$fpath = 'path/to/dir/' . $fname . '.html';
if(!file_exists($fpath)){
//write data to $fpath
}
Do something like this:
$i = 0;
while (file_exists("file-".$i.".html")) {
$i++;
}
$file = fopen("file-".$i.".html");

Categories