Link to home
Start Free TrialLog in
Avatar of MICHAEL HOGGATT
MICHAEL HOGGATT

asked on

Browse my computer for a file

This is the code I received from my first question.
It searches the original text file for a period.
When the period is found it prints the sentence to a new text file and prints a carriage return so that each sentence is on its own line.

I would like to be able to browse my computer for the file I want to open and then convert the file and then placed the new file in say 'Downloads'.

Thanks,

Michael

<?php
// The source file
$inFile = "1corinthians7.txt";
var_dump(file_exists($inFile));

// The file we'll write with the line breaks
$outFile = "converted_lines.txt";

// Open the files
$fpIn = fopen($inFile, "r");
$fpOut = fopen($outFile, "w");

// Loop through the source file, 1k at a time
while(!feof($fpIn))
{
  $chunk = fread($fpIn, 1024);

  // Replace every . with a . and a line break afterwards and write that to the out file
  fwrite($fpOut, str_replace(".",".\n",$chunk));
}

// Close the files
fclose($fpIn);
fclose($fpOut);

Open in new window

Avatar of Rob
Rob
Flag of Australia image

So that should be easy enough.

Add a file html element to your php page.  That will allow you to browse your computer and upload the file to your php script.  Once your PHP script has finished processing, it will send it back to the browser and prompt you to save it, where you'll be able to select your "Downloads" folder.

Make sense?
Avatar of MICHAEL HOGGATT
MICHAEL HOGGATT

ASKER

Rob, Thanks for the reply,
I am not a programmer so could you write out the code for me and I'll test it.

Thanks,

Michael
Reference: https://www.w3schools.com/php/php_file_upload.asp

This is what you need to get started with the file upload (beats me rewriting it) so follow the steps and i'll show you below where to add in the code above.  Be sure to review the php.ini settings and requirements to make file uploads work.

Refer firstly to the "Create The HTML Form".  Save that as index.html in the same directly as your php script.
<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Open in new window


Then create the following as save as upload.php (from the section "Complete Upload File PHP Script")

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "txt" && $imageFileType != "log" ) {
    echo "Sorry, only TXT and LOG text files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        processTextFile($_FILES["fileToUpload"]["name"]);
        
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

function processTextFile($inFile) {

	// The file we'll write with the line breaks
	$outFile = "converted_lines.txt";

	// Open the files
	$fpIn = fopen($inFile, "r");
	$fpOut = fopen($outFile, "w");

	// Loop through the source file, 1k at a time
	while(!feof($fpIn))
	{
	  $chunk = fread($fpIn, 1024);

	  // Replace every . with a . and a line break afterwards and write that to the out file
	  fwrite($fpOut, str_replace(".",".\n",$chunk));
	}

	// Close the files
	fclose($fpIn);
	fclose($fpOut);
	
	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename='.basename($outFile));
	header('Expires: 0');
	header('Cache-Control: must-revalidate');
	header('Pragma: public');
	header('Content-Length: ' . filesize($outFile));
	readfile($outFile);
    exit;
}
?>

Open in new window


This will allow you to upload your file and process before sending it back to you for saving

Hello Rob,
We are making progress but we're not quite there yet.
I saved the two files as you instructed.
If I try to open and .rtf file for example the code catches it.
If I open an text file the code says 'Sorry there was an error uploading your file' which is in the php code.
I have run the code in both IE and FireFox.
Can you run this code on a text file on your computer ?

I also run a program that Ray Paseur wrote for me which browses the computer in the same way and it works just fine.
And your code works just fine also.
So what could be the problem ?
Thanks,

Michael
I tweaked a few things to get it working.  See here for a demo: https://home.aidellio.com/ee/fileupload

I also included rtf files, however you may find some weird results if there's too much rich text going on

upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
/*
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
*/
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "txt" && $imageFileType != "log" && $imageFileType != "rtf" ) {
    echo "Sorry, only TXT / LOG / RTF text files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        processTextFile($target_file);

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

function processTextFile($inFile) {

	// The file we'll write with the line breaks
	$outFile = "converted_lines.txt";

	// Open the files
	$fpIn = fopen($inFile, "r");
	//$fpOut = fopen($outFile, "w");

	// Loop through the source file, 1k at a time
	while(!feof($fpIn))
	{
	  $chunk = fread($fpIn, 1024);

	  // Replace every . with a . and a line break afterwards and write that to the out file
	  //fwrite($fpOut, str_replace(".",".\n",$chunk));
	  echo str_replace(".",".\n",$chunk);
	}

	// Close the files
	fclose($fpIn);
//	fclose($fpOut);

	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename='.basename($outFile));
	header('Expires: 0');
	header('Cache-Control: must-revalidate');
	header('Pragma: public');
	header('Content-Length: ' . filesize($outFile));
	readfile($outFile);
    exit;
}
?>

Open in new window


Rob,
I ran the script on your site and it works fine.
The code you gave me includes the numbers in each line and I believe you have a section of code commented out starting around line 8 with a /* and a */.

Can you check the code and resubmit it for me because it's not working in the php code.

Thanks,
Michael
Hi Michael,

Not sure how you ended up with the line numbers in your code, just click the "select all" link under the code box above then copy the text to your upload.php file (I've attached it here anyway for you).

The commented out code ignores the test to see if the file had previously been uploaded.  I'll leave that up to you whether you want it or not.

Rob
upload.php

Rob,
For some reason the file still can't be opened.
I ran the script from your web site once again on another file and it worked just fine.
Might there be a tmp file that I need to add somewhere ?
I know Ray's code needed the tmp file in order to work.
We're close and I'm sure the problem must be a simple one.

Thanks,

Michael

My first guess is PHP settings. Can you check you have everything in your php.ini file that the link i posted explains?
Secondly make sure your "upload" directory is writable. I gave mine full access

Rob,
You may be right about the php.ini.
If I run just the index.html by itself and choose a file to upload
the program does ask me if I wan to open the file but of course the file that is displayed is upload.php.
All of the scripts I run that read and write to disk work just fine.

If the original script that I started with works it looks like your script would work as well.
I am legally blind so if I need to check the php.ini file you'll have to be specific as to what I need to look for.

This may not help but here is the link to the program Ray wrote that basically opens a file on my computer and processes it.
http://iconoun.com/mhoggatt/

So what exactly do I look for in php.ini.

Thanks,

Michael




Rob,
Which file is not opening ?
Is it the input file or the output file ?

Michael

try changing the target folder to

$target_dir = ".";

good morning Rob,
you are a genius! The code now works.

the only thing now is that the program doesn't give me the option as to where I want to store the file.
is that going to be too much trouble to have to add in or just saving it to downloads would be okay?
the program also saves the file as, .1 Corinthians 3.txt.
Is that the way it is supposed to be saved?

Thanks again,

Michael

Glad to hear that's now working! :)

Unfortunately the browser controls where the file is saved. It would be a huge security flaw otherwise...
 You can change the settings in your browser to prompt you for a save location for downloaded files.

If you just want to save the file to same computer that's running PHP then that's possible, rather than sending the file back to the browser

Alternatively, of you're just converting these files on your localcomputer and saving to your local computer then you can run PHP like you would a batch program, at the command line and specify a save location

good morning Rob,
I was so excited about opening the file that I didn't realize the program hadn't converted the file as it should have.
When the program runs it saves a file named.1 Corinthians 7.txt. but it's the same file as was opened.

The PHP code when it runs should save the converted file in converted_lines.txt, so were not quite there yet.

Iran the script on your site and the result is the same, it only prints out the original file that is opened.
I'm sure it must be something simple, like the file name that is supposed to be opened is not transferred to the PHP code.

Once again, thanks,

Michael


Hi Michael,

I've modified the code so that it saves the file rather than prompting you to save the converted file.  It does work though I suspect you were looking at the file on the hard drive and not saving the one sent back to you by the browser but that's all changed now :)

So take a look at https://home.aidellio.com/ee/fileupload/ and you'll see what I mean.

I've also attached the updated "upload.php"
upload.php

good morning Rob,
could you post the code for index.html again for me. When I run this part of the code and after I hit the upload image button I'm getting a 404 error which says the resource can't be found.

I tried using this code in the php section
$target_dir = ".";                                  
instead of
 $target_dir = "uploads/";
with the same result
I'm not giving up on this one if you're not!
And yes I did try the code on your website and it does work just as you said.
We just need to figure out wise not working on my computer.

Michael




Hi Michael, i haven't given up, don't worry! :) Just had Easter and not much time on the computer.
You'll hear from me sometime today 👍
Hi Michael,

Here are both files that are currently running on my server.

Rob
index.html
upload.php
hello Rob,
glad you got to enjoy some time off. We enjoyed our Easter weekend also.
I copied both files and ran the code.
and there was a 'Sorry there was a problem uploading your file' error message.

I replaced this line of code -
 $target_dir = "uploads/";

with
 $target_dir = "."; as you recommended before                                  
 then I ran the code and it gave me the option to click on the link but when I did
there was  a 404.3 error, Resource not found.
so at least were getting down into the php code.

Thanks,

Michael
ah ok... create a directory "uploads" in the same directory as the upload.php and index.html files.  Make it writable.

Also, change $target_dir back to "uploads/"
[good morning Rob,
we are definitely making progress.
The PHP code does its job but when the file is saved it is saved as, for example -
1 Corinthians 7.txt-converted

The Internet browser displays this message which is just a part of what it says but I think this will be
enough to explain what's going on
Error Code      0x80070032
Requested URL      http://localhost:80/uploads/test.txt_converted
Physical Path      C:\webapps\BVC\uploads\test.txt_converted
Logon Method      Anonymous
Logon User      Anonymous
so evidently it's the saving of the file in a _converted format that the browser doesn't know how to display. So we are just about there.

Michael
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Good morning Rob,
perfect! The program does just what I wanted it to do.
You don't know how much time this will save me. Having two separate hundreds of sentences from the next can be very time-consuming.
Thank you for all of your expertise because it has really helped me and I know it will help others in the future.

Michael

This program allows a user to search for a text file on a computer, opens it and then searches for all of the periods in the text, then performs a carriage return so that each sentence is separated from the other.
A file called 'uploads' must be created and must be writable and in the same directory as the executable code because this is where the files will be placed.

Here is a copy of the working code.

index.html
<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

upload.php
<?php
$target_dir = "uploads/";
$uploaded_file = $_FILES["fileToUpload"]["name"];
$target_file = $target_dir . basename($uploaded_file);
$uploaded_filename = pathinfo($uploaded_file,PATHINFO_FILENAME);
$uploadedExt = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$output_file = $target_dir . $uploaded_filename . "_converted" . "." . $uploadedExt;
$uploadOk = 1;

// Check if file already exists
/*
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
*/
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($uploadedExt != "txt" && $uploadedExt != "log" && $uploadedExt != "rtf" ) {
    echo "Sorry, only TXT / LOG / RTF text files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        processTextFile($target_file, $output_file);
        echo "<a href='$output_file'>click here for your converted file</a>";

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

function processTextFile($inFile, $outFile) {

	// Open the files
	$fpIn = fopen($inFile, "r");
	$fpOut = fopen($outFile, "w");

	// Loop through the source file, 1k at a time
	while(!feof($fpIn))
	{
	  $chunk = fread($fpIn, 1024);

	  // Replace every . with a . and a line break afterwards and write that to the out file
	  fwrite($fpOut, str_replace(".",".\n",$chunk));
	}

	// Close the files
	fclose($fpIn);
	fclose($fpOut);

}
?>

Open in new window

Great news and my pleasure.  Good luck with the project :)