Home > Software engineering >  How to show the file name to the user that fopen created in PHP?
How to show the file name to the user that fopen created in PHP?

Time:10-10

I am using

$fp = fopen(rand(1,10000000000).'', "w");

that creates files with user's Submitted content through a textarea. Once submited, I want to show the url of the file that is just created by the user. As the filename is random, I couldn't find any way to show the filename to the user.

CodePudding user response:

A key skill in programming is breaking a problem down into smaller parts, allowing you to understand those parts, and reuse them in different ways.

Although this is a very simple line of code, it's doing two different things:

  1. Generating a random filename
  2. Opening a file handle

Quite simply, you need to make those into two separate lines of code:

$filename = rand(1,10000000000).'';
$fp = fopen($filename, "w");

Now you have a variable with the filename, which you can pass to whatever is doing the display to the user.


As an aside, if the purpose of the .'' is just to make the value into a string, it would be clearer to use the appropriate type casting operator: (string) rand(1,10000000000).

CodePudding user response:

In its simplest form:

$filename = rand(1,10000000000).''; // Create filename and save in a variable
$fp= fopen($filename, 'w');         // Open the filen
echo $filename;                     // Tell the user.
  • Related