Php Method for randomly reading files from folders

Source: Internet
Author: User

Php Method for randomly reading files from folders

This example describes how php randomly reads files from folders. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

Function RandomFile ($ folder = '', $ extensions = '.*'){

// Fix path:

$ Folder = trim ($ folder );

$ Folder = ($ folder = '')? './': $ Folder;

// Check folder:

If (! Is_dir ($ folder) {die ('invalid folder given! ');}

// Create files array

$ Files = array ();

// Open directory

If ($ dir = @ opendir ($ folder )){

// Go trough all files:

While ($ file = readdir ($ dir )){

If (! Preg_match ('/^ \. + $/', $ file) and

Preg_match ('/\. ('. $ extensions. ') $/', $ file )){

// Feed the array:

$ Files [] = $ file;

}

}

// Close directory

Closedir ($ dir );

}

Else {

Die ('could not open the folder "'. $ folder .'"');

}

If (count ($ files) = 0 ){

Die ('no files where found :-(');

}

// Seed random function:

Mt_srand (double) microtime () * 1000000 );

// Get an random index:

$ Rand = mt_rand (0, count ($ files)-1 );

// Check again:

If (! Isset ($ files [$ rand]) {

Die ('array index was not found! Very strange! ');

}

// Return the random file:

Return $ folder. $ files [$ rand];

}

 

// Usage Demonstration:

// "Jpg | png | gif" matches all files with these extensions

Print RandomFile ('test _ images/', 'jpg | png | gif ');

// Returns test_07.gif

// ". *" Matches all extensions (all files)

Print RandomFile ('test _ files /','.*');

// Returns foobar_1.zip

// "[0-9] +" matches all extensions that just

// Contain numbers (like backup.1, backup.2)

Print RandomFile ('test _ files/',' [0-9] + ');

// Returns backup.7

I hope this article will help you with php programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.