How do you rename a textfile with a datetime stamp in php? - php

I'm new to php and programming in general, so forgive my ignorance on this one. I am trying to rename a textfile I created with a datetime stamp, and can't seem to get it right. I am writing info to a textfile after someone submits data, and that works, but I need to make every text file unique, so I need a unique naming convention. I even tried using the first name of the entry, but I can't get that to work either. Here's what I have so far:
<?php
$FirstName = $_POST["fname"].PHP_EOL;
$LastName = $_POST["lname"].PHP_EOL;
$Address = $_POST["address"].PHP_EOL;
$City = $_POST["city"].PHP_EOL;
$State = $_POST["st"].PHP_EOL;
$Zip = $_POST["zip"].PHP_EOL;
$Tel = $_POST["tel"].PHP_EOL;
$AddressFile = "Address_Entries.txt";
$ourFileHandle = fopen($AddressFile, "a") or die("can't open file");
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
fwrite($ourFileHandle, $FirstName);
fwrite($ourFileHandle, $LastName);
fwrite($ourFileHandle, $Address);
fwrite($ourFileHandle, $City);
fwrite($ourFileHandle, $State);
fwrite($ourFileHandle, $Zip);
fwrite($ourFileHandle, $Tel);
fclose($ourFileHandle);
echo "<p>File has been writtten to successfully!</p>";
rename("C:/xampp/security/htdocs/testes/Address_Entries.txt", $FirstName);
?>
Any help is appreciated. Thanks!
A

If you need a unique ID to name files with, try uniqid()

In windows you must use correct path:
rename("C:\\xampp\\security\\htdocs\\testes\\Address_Entries.txt", "C:\\xampp\\security\\htdocs\\testes\\$FirstName.txt");

This will rename the file using the timestamp. But a unique naming convention, this has a great chance to be unique, but is NOT unique. If someone was to post at the very same time... with the same first name... you'll have duplicate files.
Now is it a big chance? No.
<?php
$file = '/tmp/this-is-temp-file.txt';
$firstName = 'BeepBeep';
$timestamp = time();
rename($file, '/path/to/new/file/'.$firstName.'-'.$timestamp.'.txt');
?>
Possibly try to incorporate a uniqid() function. I don't think it is unique again as it uses time() (I think)... but may be better off padding it with a unique counter (like an ID from the database)
This assumes:
a) You have access to the FULL PATH
b) PHP has access to the file! You might be able to WRITE the file, but maybe not enough permissions to move, delete, rename, edit..

Related

Append to a php file instead of txt file

I have the following script which takes some value from a form and appends to a text file each time new values are entered in the form:
$filename = "nic.txt"; #Must CHMOD to 666, set folder to 777
$text = "\n" . str_pad($fname, 30) . "" . str_pad($lname, 30) . "" . str_pad($tdate, 20) . "" . str_pad($ydept, 30) . "" . str_pad($percentage, 0) . "%";
$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
fwrite ($fp, $text);
fclose ($fp);
#echo ("File written");
}
else {
#echo ("File was not written");
}
The issue is, instead of writing to a txt file which isn't secured in storing data, how can I let's say append to a php file so user would need authentication before viewing the file on the web?
I would like some sort of authentication (password/username) in place so not everyone can see it. And with txt file I don't think it's possible.
My SQL writing to data file which I commented out until I find the best option is:
// Write to DB
//$conn = new mysqli('host', 'user', 'pass', 'db');
// check connection
//if (mysqli_connect_errno()) {
// exit('Connect failed: '. mysqli_connect_error());
//}
// store the values in an Array, escaping special characters for use in the SQL statement
//$adds['fname'] = $conn->real_escape_string($fname);
//$adds['lname'] = $conn->real_escape_string($lname);
//$adds['tdate'] = $conn->real_escape_string($tdate);
//$adds['ydept'] = $conn->real_escape_string($ydept);
//$adds['percentage'] = $conn->real_escape_string($percentage);
// sql query for INSERT INTO users
//$sql = "INSERT INTO keepScore ('fname', 'lname', 'tdate', 'ydept', 'percentage' ) VALUES ('". $adds['fname']. "', '". $adds['lname']. "', '". $adds['tdate']. "', '". $adds['ydept']. "', '". $adds['percentage']. "')";
// Performs the $sql query on the server to insert the values
//if ($conn->query($sql) === TRUE) {
// echo 'users entry saved successfully';
//}
//else {
// echo 'Error: '. $conn->error;
//}
//$conn->close();
Keep your text file out of the web server's document root, and use a PHP script to provide authentication/authorization when reading the file.
Take a look at readfile().
PHP files are text files. To achieve what you are asking for, just make $filename end in .php (making sure the data people add is just data and not executable code).
… but editing code programatically is not a great idea. Store your data somewhere outside the web root (possibly in a file, but a database is probably better) and then have your script retrieve it when auth/authz is passed).
A simple solution would be to create a directory with a .txt file in it, which is .htpasswd protected. This way a user needs to authenticate to view the contents, and you are not putting yourself at risk for an untold number of security vulnerabilities.
You can store the files with the .php extension and add header information to serve them as plain text instead of html. Then you can insert a php code at the beginning that will cause the user to authenticate themself.

Resource id #7 when using fopen and fwrite in PHP

I'm trying to create a download link in PHP so you can download the information in a table. I just started writing it and have run into a snag. Here is what I have so far:
<?php
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$row = mysql_fetch_assoc($result);
$something = "This is text";
$myFile = "data.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$download_data = "";
foreach ($row as $k=>$v){
$download_data .= $k . "=" . $v . "\n";
}
fwrite($fh, $download_data);
fclose($fh);
echo $download_data;
?>
Download
It is just supposed to show something like Code = 1 Name = John etc. When I open the txt file, it simply says Resource id #7. The weird part is, when I echo $download_data, it looks correctly in the web page. Is there something special I have to do with fwrite in order to get the whole string into the text file
(Note: I have used both mysql_fetch_array and mysql_fetch_assoc and both have the same result. Also, if I simply declare a variable like $test = "this is a test"; it works).
Edit:
I have tried commenting out all other code in the script and I get the same result. Printing $download_data shows the right result, but the text file is still only showing Resource id #7. I've even tried deleting the txt file and when it is recreated, it does the same thing.
You're almost certainly not showing us the whole picture with your example code.
You are likely writing one of these things to the file:
The file handle, $fh
The result returned from mysql_query()
Check you're not mixing up $result and $row. Or even better, post all of your code.

Mysql blob field has first line of space and therefore wont play file

I have some code to upload and download a sound recording from android. The problem i am having is that it appears an extra blank line is appearing in the binary. When this is removed the file plays i would like to know how to stop this line appearing. Below is my upload and download code as well as a print screen of the blank line
Upload code
mysql_select_db ($database);
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
fclose($fp);
$data = trim(addslashes($data));
// Create the query and insert
// into our database.
$query = "INSERT INTO media";
$query .= "(file, file_size, file_type) VALUES ('$data','$size','$type')";
$results = mysql_query($query, $link);
$mediaid = mysql_insert_id();
$gender = $_POST['gender'];
$cat_id = $_POST['cat'];
$name = $_POST['name'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$user = $_POST['user'];
$query="INSERT INTO instance (name, gender, cat_id, lon, lat, user_id) VALUES ('$name', '$gender', '$cat_id', '$lon', '$lat', '$user')";
$result=mysql_query($query);
$instanceid = mysql_insert_id();
$query4 = "INSERT INTO media_link";
$query4 .="(media_id, instance_id) Values ('$mediaid','$instanceid')";
$results4 = mysql_query($query4, $link);
}
// Close our MySQL Link
mysql_close($link);
?>
download code
$test2 = #mysql_query("select * from media where media_id = '$media'");
$result2 = mysql_fetch_array($test2);
header('Content-Type: audio/AMR');
header('Content-Disposition: attachment; filename="ifound.amr"');
print $result2['file'];
exit;
?>
Blank line that is appearing
Check if your download code has a blank line before the first <?php . Remember to check any file it gets included from as well.
Also change addslashes to mysql_real_escape_string. It might not cause a problem here, but it is security hole.
If you can't find the root of your problem, you could always try base64_encode / base64_decode. It takes 30% more storage space, but it's a bullet proof way to store binary data in strings.
Just a tip:
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
fclose($fp);
could be replaced with
$data = file_get_contents($tmpName)
I also having the same problem on the coding, but after that I found out that actually one of the including files hase empty space like below:
tool.php
line 1
line 2 <?php
line 3 .......
line 4 ?>
line 1 is causing the problem when I include on
<?php
if($_SERVER['REQUEST_METHOD']=="GET"){
if(isset($_GET["ImageID"])){
/* below require file causing the problem */
require_once($_SERVER['DOCUMENT_ROOT'] . "/model/Game/Tools.php");
$image = new ClsGameImage();
$image->Select($_GET["ImageID"]);
header("Content-type: ". $image->MIMEType);
header("Content-length: " . $image->ImageSize);
header("Content-Disposition:attachment;filename=". $image->Name0);
echo $image->Image0;
}
}
?>
It's possible ltrim could help in this situation if the line is being introduced by PHP. There is also a ltrim function for MySQL if it's being introduced in the database.
Also, use mysql_real_escape_string instead of addslashes.
You may want to consider serving media from a media directory instead of storing it in a database. I know this does nothing for replication purposes, but there are things you can do to propagate filesystem changes to multiple computers, if necessary.
This is obviously a preferential choice.

PHP upload file

i have been stressing for an hour at this stupid script i am trying to make it uploa an MP3
file to a folder it creates.
It is putting the information into mysql and making the folder bu when i ftp the folder is empty with no music file in there
here is the script thanks so so so much!
BTW $name is the POSTED name and full name is the posted name + ".mp3"
// BEGIN ENTERING INFORMATION TO MYSQL TABLE
$sql = mysql_query("INSERT INTO mattyc (name, date, length, size, link)
VALUES('$name','$date','$length','$size','$link')"
) or die (mysql_error());
mkdir("../music/albums/donjuma/$name", 0777);
$song = ("../music/albums/donjuma/$name/$fullname");
if (file_exists($song)) {
unlink($song);
}
$newname = "$fullname";
$newfile = rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file( $newfile, "../music/albums/donjuma/$name/"."$newname");
$success_msg = "<font color=\"#009900\">Your SONG has been updated, it may take a few minutes for the changes to show... please be patient.</font>";
echo $success_msg;
}
}
}
$newfile =
rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file(
$newfile,
"../music/albums/donjuma/$name/"."$newname");
rename() returns a bool, not a filename. So your move_uploaded_file() call is going to fail. Any file renaming should be part of your move_uploaded_file() call, don't try and do anything with your temporary file apart from move it.

how to insert a image into Db as blob in ZendFramework

I want to insert a image in blob format to db.
how to write a program in zend framework.
a simple form
just choose one image and insert into db.
In your Zend form create a file element:
$element = new Zend_Form_Element_File('fileElement');
Then you can insert the uploaded image to your DB in BLOB format like this:
$conn = new PDO("mysql:host='host';dbname='database'", 'userName', 'password');
$imagePath = $zendForm->fileElement->getFileName();
$image = file_get_contents('$imagePath');
$sql = "INSERT INTO images (data) values(?)";
$q = $conn->prepare($sql);
$q->bindParam(1, $image, PDO::PARAM_LOB);
$q->execute();
Read it in as a string using file_get_contents and store that.
That said, it is seldom a good idea to store the actual image data in the database. It is better practice to generate a unique filename and store that in the DB instead.
Here is some code to save the file in zend:
// This is to save in saveAction()
$source = $this->view->form->upload->getFileName();
$fp = fopen($source,'r');
$content = fread($fp,filesize($source));
// I don't use addslashes, because i already have that in my mapper
fclose($fp);
$model->image = base64_encode($content);
// Save here
// This is to read in imagesAction()
$this->_helper->Layout()->disableLayout();
$this->_helper->ViewRenderer->setNeverRender();
header('Content-Type: image/gif');
echo base64_decode($image);
exit;
I had alot of problems with it, try to make your save work and don't insert it into the database directly to test the reading. This won't make it possible unless you know the correct db encoding (which i don't).

Categories