OK guys, this is my first post. I have searched all over and spent countless hours and I am still stuck so I asking for help with this relatively easy PHP module.
basically in a nutshell, what I want to do is upload a text file into an uploads directory, and have PHP process the file and perform a string function that will add HTML BREAK TAGS to the end of each line and then save this output to file. I have learned how to echo the formatted text into the browser and it appears the way it should as formatted html, but it doesn't work to write back to the file.
here is the code;
<?php
$form = <<<EOD
<form enctype="multipart/form-data" action="" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000" />
Choose an file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
EOD;
echo $form;
$target_path = "uploads/"; //SETS THE UPLOAD DIRECTORY
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); // GETS FILEPATH OF UPLOAD FOR OPENING/PROCESSING
$uploadfile = basename($_FILES['uploadedfile']['name']); //GETS FILENAME OF THE UPLOADED FILE IN CASE ITS NEEDED.
//PROCESSING - MOVES TMP FILE INTO TARGET DIRECTORY. NEED STRING FUNCTIONS APPLIED TO ADD <BR/> AT END OF EACH LINE.
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$file = fopen($target_path, "r");
while(!feof($file))
{
$line = fgets($file); //READS EACH LINE
// STRING PROCESSING PART -- SHOULD I USE str_replace, substr_replace, nl2br, or str_pad ??
..........CODE GOES HERE............PLEASE HELP ME CHOOSE THE RIGHT CODING HERE...THANKS!!! SORRY FOR THE PSEUDOCODE!
/* EXAMPLE SCRIPT:
$line2 = str_replace("\n", "<br />\n", $line);
// THIS WORKS -- GREAT FOR OUTPUTTING FORMATTED HTML INTO BROWSER
echo $line2;
// FOR NICE VIEWING BUT STILL CANNOT GET FORMATTED
// HTML TO SAVE TO FILE USING FWRITE() ...
*/
fwrite($file, $newstr);
} //CLOSES WHILE
fclose($file); //CLOSES FILE HANDLE
} //CLOSES IF
?>
too many late nights, open windows, and troubleshooting steps to make my brain want to explode! When I know one of you guys can knock this out in 2 minutes!!!
I notice I keep getting this error log:
PHP Warning: Module 'mailparse' already loaded in Unknown on line 0
There are a couple of problems with what you're doing currently. First, you've opened the file for reading only, but even if you change that, you won't be able to just replace a line with a longer line in the same file. In order for your current approach to work, you'll need to open a second file for writing, and add the modified lines into the second file as you go. But as long as the files aren't very large, you should be able to create the modified file more simply:
file_put_contents($output_file, nl2br(file_get_contents($input_file)));
Incidentally, the mailparse warning does not appear to be related to the code you've posted here.
Related
if(isset($_POST['submit'])){
if(!empty($_FILES['files']['name'])){
$Zip = new ZipArchive();
$Zip->open('uploads.zip', ZIPARCHIVE::CREATE);
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
$Zip->close();
}
else {
echo "no files selected";
}
}
What is wrong here ? I have just watched a tutorial of creating archives and adding files in it but it is not working ...I am using php 5.4 . It is not even giving me any error. Can any one please guide me what i am doing wrong here.
Below is the form
<form action="" method="POST" enctype="multipart/form-data">
<label>Select files to upload</label>
<input type="file" name="files">
<input type="submit" name="submit" value="Add to archieve">
</form>
These lines don't make any sense
$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
$Zip->addFile($UploadFolder.$file);
}
At that point in the code you posted, no uploaded files have been moved to a uploads/ directory, and looping though the $_FILES["files"] element - which is an associative array of various values, only one of which is the actual file name - and adding each value to the ZIP as a file, is nonsensical. - You should read the PHP docs relating to file uploading. It's clear you don't really know how PHP handles file uploads yet, which you should learn before attempting things like this.
One solution would be to move the uploaded file to the uploads/ directory using move_uploaded_file, but seeing as you are only really using the file there to add it to the archive, that step is pretty redundant; you can just add it directly from the temp location. First you need to verify it, though, which you can do with the is_uploaded_file function.
// Make sure the file is valid. (Security!)
if (is_uploaded_file($_FILES["files"]["tmp_name"])) {
// Add the file to the archive directly from it's
// temporary location. Pass the real name of the file
// as the second param, or the temporary name will be
// the one used inside the archive.
$Zip->addFile($_FILES["files"]["tmp_name"], $_FILES["files"]["name"]);
$Zip->close();
// Remove the temporary file. Always a good move when
// uploaded files are not moved to a new location.
// Make sure this happens AFTER the archive is closed.
unlink($_FILES["files"]["tmp_name"]);
}
I have the following;
$FilePath = "c:\user\test\koala.jpg";
$put = $dropbox->putFile($FilePath);
or
$put = $dropbox->putFile("c:\user\test\koala.jpg");
This works great, and uploads the file to dropbox.
However, obviously I can not get the full path ie c:\user\test\koala.jpg through a form input box, due to security restrictions.
Is there a way around this that would work. Where I can just get $FilePath through some form of input without having to submit it as a temp file to my server.
I have put the full code below.
<?php
// #link https://github.com/BenTheDesigner/Dropbox/blob/master/Dropbox/API.php#L122-139
// Require the bootstrap
require_once('bootstrap.php');
// Extend your sript execution time where required
set_time_limit(0);
$put = $dropbox->putFile($FilePath);
// Dump the output
// var_dump($chunked);
Test something like this:
HTML
...
<form type="POST" action="myPhpUploadPage.php" enctype="multipart/form-data">
<input type="file" name="file"/><br/>
<input type="submit" value="send"/>
</form>
...
PHP (myPhpUploadPage.php)
// Require the bootstrap
require_once('bootstrap.php');
// Extend your sript execution time where required
set_time_limit(0);
if(isset($_FILES['file'])){
$FilePay = $_FILES['file']['tmp_name'];
$put = $dropbox->putFile($FilePath);
} else {
echo 'not file selected';
}
How about uploading your files to your server, and after running the script to copy them to your Dropbox account. Then run a script to erase the files in the temporary directory or specific folder.
Okay, so I set up an upload engine for a website so that an authenticated user can upload a audio file (a key) for a song in the library, but I come across this strange problem when I try to upload any file over 5MB.
I set my php.ini max filesize to 50MB by the way
Everything uploads properly, but there is no data associated with the file on the other end.
HTML CODE:
<form action="keyUpload.php?id=<?php echo $id;?>" method="post" enctype="multipart/form-data">
<p style="color:#fff;font-size:30px;font-family:Times">
Add a new Key:<br/><input name="uploaded" type="file" id="file"><br />
<input type="text" name="kname" id="kname" value placeholder="Key Name (Ex. Demo, A#, etc.)" style="width:300px;"><br/>
<button class="button">Upload File</button><br/>
<span style="font-size:12px;">*Max Filesize is 50 MB*</span>
</p>
</form>
PHP CODE:
<?php
$id=$_GET["id"];
$name=$_POST["kname"];
$name = str_replace(" ","%20",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
Both $filename and $ext are empty variables when I upload a file larger than 5 MB. In all other cases, this engine works perfectly.
When echoed, simply nothing happens, so obviously the engine will not save the file if it doesn't exist. What's going on?
var_dump:
array(0) { }
Thanks for all your help!
Check for upload errors:
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['uploaded']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
As well, do NOT use filenames to validate the uploads. It is beyond trivial for a malicious user to fake a filename and upload malicious files, eg.
ren nastyvirus.exe good_tune.mp3
And don't use string operations on filenames. There's a whole whack of PHP functions for filename manipulation, e.g. http://php.net/basename
Set max_post_size in php.ini as well.
To populate an sql database I upload .txt files with all data for each field and rows. When my internet connection is bad i have a lot of problems and sometimes process is aborted.
To fix the problem I'd upload .txt files in a compressed format(.zip or if possible also other formats: .rar ...etc). In this way, filesize is 15 times smaller and i can upload it easier and faster.
How can i do?
Here are codes i use at the moment:
upload.php
...
<form action="readfile.php" enctype="multipart/form-data" method="post">
<br>Filename: <input name="userfile" type="file">
<p><input type="reset" value="Reset">
<input type="submit" value="Upload">
</form>
...
readfile.php
...
// Read data posted from form
$browser_name = $_FILES['userfile']['name'];
$temp_name = $_FILES['userfile']['tmp_name'];
$usrname = $_POST['uname'];
// Connect to the database
if (!($connection = # mysql_connect ($hostName,
$username,
$password)))
die ("Could not connect to database");
if (!mysql_select_db ($databaseName, $connection))
showerror();
echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\"http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd\">";
echo "<html>";
echo "<head>";
echo "<title>Upload file</title>";
echo "</head>";
echo "<body>";
// Was a file uploaded?
if (is_uploaded_file ($temp_name))
{
echo "<h1>File Upload $browser_name</h1>";
echo "<p>Filename - $browser_name\n";
echo "<br>User name - $uname\n";
// Open the file
if (!($file = fopen ($temp_name, "r")))
die ("Could not open the file $file\n");
// Read the first line
$string = fgets ($file, 1024);
...
Where to modify and/or add codes?
If you need more details, please ask me and I paste more: I presumed they're the right lines to explain better everything and to modify for my needs.
Thank you so much in advance for your help.
Mattew
UPDATES:
I made some new modifies using ZipArchive. In a few words now the .zip file is uploaded in a folder and unzipped. So the nomefile.txt file can be read and processed as a normal .txt file inside the specific folder.
Unfortunately the fopen looks for a specific filename. My idea is now to rename any unzipped file (having a random name but .txt extension) to a specific file (for example myfile.txt). In this way i can fix also problems with "different" extensions having small/capitol letters such as .txt and .TXT
HERE IS THE CODE I MENTIONED BEFORE:
...
//unzip del file
$zip = new ZipArchive;
$zip->open('file.zip');
$zip->extractTo('./');
$zip->close();
echo "File unzipped and ready to be processed";
if (!($file = fopen ("namefile.txt", "r")))
die ("Could not open the file $file\n");
// Read the first line
$string = fgets ($file, 1024);
....
Opinions? Helps?
Thanks in advance, I'm very new of php and maybe my problems are elementary, excuse me.
Bye.
Use the ZIP Wrapper:
$filedata = file_get_contents("zip://absolutepathtozip.zip#pathintozip/file.txt");
The approach differs with the compression mechanism you use, since the available libraries all use different interfaces; Exemplary, I'll show bzip2 here since that seems to be the simplest to me. Locally, just execute bzip2 <file> on any *ix command line shell; on Windows you could use e.g. 7-Zip for creating a .bz2 file.
In your php, you will want to read the whole file content instead of single lines (single lines don't make much sense in a compressed file). So you'll have to change your code starting from opening the files:
/*
// Open the file
if (!($file = fopen ($temp_name, "r")))
die ("Could not open the file $file\n");
// Read the first line
$string = fgets ($file, 1024);
*/
$compressed_filecontent = file-get-contents($temp_name);
$filecontent = bzdecompress($compressed_filecontent);
...
// instead of reading from the file line by line,
// you'd then have to split up the $filecontent variable
// in separate lines and work on them
Note: of the "compression" formats where there is a PHP library available for, only LZF is similarly simple to use (you'd just have to replace bzdecompress with lzf-decompress); that is because the other formats (like ZIP and RAR) are not only compression formats but also archiving formats (meaning that such files can hold multiple compressed files). That makes reading them a little harder - see the documentation for more info.
I have an upload PHP script and before it uploads the file, it renames it to to a random name, so no files that are already there will be overrided. The problem is that it is not working properly. It is putting in a bunch of weird symbols in the file name, and when I try viewing the file, it has a 404 error. It was working before I added this random name part in. Here's the PHP script that I have right now:
<?php
// Where the file is going to be placed
$target_path = "files/";
/* Rename file with random name and keep extension */
$length = 10;
$characters = ’123456789’;
$string="";
for($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
$pos = strrpos(basename( $_FILES['uploadedfile']['name']), ".");
$ext = str_split(basename( $_FILES['uploadedfile']['name']), $pos);
$target_path = $target_path.$string.$ext[1];
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<h2>Your file has been uploaded!</h2><br /><p>Your file has been uploaded successfully. <a href='".$target_path."'>Click here</a> to see the file you uploaded.
<br /><br /><br />
<h2>A link to your file</h2><br />The full link to your file is:
<br /><br />
<code>http://www.example.com/upload/".$target_path."</code></p>";
} else{
echo "<span class='error'>There was an error uploading the file, please try again.</span>";
}
?>
For some reason, it is really acting weird. Then, when I view the folder /files/ in my hosting file manager and I try deleting a file with the weird symbols in it, and I refresh and they are all back. Take a look at this screenshot:
Weird, huh?
I will probably need a new random naming PHP script, but this is annoying because I delete all of those files, and, what do you know, they come right back when I reload! It's like the PHP is forcing them to not delete or something.
Thanks for any help in advance,
Nathan
You put forwardticks around your string of characters instead of quotes: ’123456789’. Changing those to quotes will probably fix your error.
But You should be using tempnam(). A PHP function which generates a random and unique file name, creates a file and returns the file name.
You just specify the folder you want the file in, and a prefix for the filename (only the first three characters are used on Windows), and it does all the "random" for you while guaranteeing uniqueness, so you generating the same random number twice and overwrite a file.
PS. Despite the functions name, the file is not temporary. If you want to delete it you have to do so yourself. You can use unlink() for that.