PDO Insert uploading a textarea into my DB - php

I have been trying for months to figure out how to fix and create what I am envisioning which I know is possible to be done and probably is not hard to do.
I am trying to take a textarea that I have placed on a page of mine upload its contents into a database where people can view the information they uploaded. Here's an example.
Person A copy/pastes text into a text area at: http://example.com/textarea/
he clicks an upload/submit button and gets a link like this: http://example.com/A93KJUQ21.txt
Anyone that has access to that link will be able to click it and it will display the contents that were uploaded to it. Whatever Person A, B, C, D, etc uploads it will generate a new unique link to the information. Example of this would be as follows:
http ://example.com/A93KJUQ21.txt
http ://example.com/JKO2QN498.txt
http ://example.com/PMNR01NEQ.txt
and so on..
Here is the code I currently have
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['upload'])) {
$textarea = $_POST['paste-area'];
//Add validations
$odb = new PDO("mysql:dbname=dbname;host=localhost", "dbusername",
"mypasswordgoeshere");
$query = $odb->prepare("INSERT INTO submission (`textarea`) VALUES
(:textarea)"); //I'm just making up the structures
$query->bindParam(':textarea', $textarea, PDO::PARAM_STR);
$status = $query->execute(); //$status contains true or false
//Other codes...
}
}
?>

Your table needs two columns, the random string and the textarea contents. When the user submits the form, you need to create the random string and insert that into the DB along with the text area.
$string = uniqid();
$query = $db->prepare("INSERT INTO submission (id, textarea) VALUES (:string, :textarea)");
$query->bindParam(':string', $string);
$query->bindParam(':textarea', $textarea);
$query->execute();
echo "Link is <a href='http://example.com/lookup.php?id=$string'>href='http://example.com/lookup.php?id=$string</a>";
I've made the link point to a PHP script. You can't retrieve from the database using a .txt URL, that just tries to download a regular file. You need to point to a PHP script that fetches the textarea from the submission table.
If you want to make it seem like a .txt file, you could use a rewrite rule on the server, that rewrites the .txt URL to the equivalent .php URL.

why do you think you need a database for this?
<?php
if (!empty($_POST['text'])) {
$filename = uniqid().".txt";
file_put_contents($filename, $_POST['text']);
die("http://".$_SERVER['HTTP_HOST']."/$filename");
}
?>
<form method=post>
<textarea name=text></textarea>
<input type=submit>
</form>

Related

PHP - Saving form data to two different text files

I have a simple HTML form comprising of check boxes and text fields.
When I submit this form it submits the data back to the same page where I capture the data and write it to a text file.
What I'd like to try and do is write some of the check box and field data to one text file and the rest to another.
Can this be done ? if it can how do I say which fields are written to which file ?
Thanks
you send your form and after that you handle the data. For example:
$dog = $_POST["dog"];
$cat = $_POST["cat"];
$fileForDogs = fopen('path://to/first/file', 'a+'); //a+ means if not exst, create one and write on the end of file
fwrite($fileForDogs, $dog);
fclose($fileForDogs);
$fileForCats = fopen('path://to/second/file', 'a+'); //a+ means if not exst, create one and write on the end of file
fwrite($fileForCats, $cat);
fclose($fileForCats);
I would highly recommend to look at databases for example mysql to save data from form.

Retrieve saved text from MySQL database

I have a form that saves text into the MySQL database. The user does not need to register to save that form. How do I make it so that when someone submit's a form, it will display their text that THEY typed in a saved. I want it to be able to retrieve they're text that they submitted at that time and possibly give it a link like this: http://www.example.com/text115612 (the numbers are for different texts...) and make the retrieved text display on that page?
When the user submits the text, you can save the text together with an ID, in your example text115612.
After they've submitted, a server side script will redirect the user to the newly created text (Serverside, because the user can't predict what the ID will be).
If you wish to make the texts a little more private, you can make a harder ID so it's not possible for people to guess it.
What you need to do is retrieve the text and create new file
with unique name
$userttext = $textfromdb // get the user text
$file = fopen('text_file_name.txt','w') // open a new file
frwite($file,$textfromdb); // write to the file
fclose($file); // close the file
$link = "http://website.com/"."text_file_name.txt"; // create the website link
When user submits the form, you would do something like this.
//insert your text//
INSERT INTO table_name (text) VALUES ('text');
//get the primary key that was just inserted//
//column must be auto-increment//
$textid = SELECT LAST_INSERT_ID();
//you can also do this directly in PHP//
$textid = $mysqli->insert_id;
echo "http://www.example.com/" . $textid;

Creating a Registration and Login Page

I'm currently in the process of making a Registration and Login Page. My first page asks you if you want to create an account or login. What we have to do is take the information from the form that the user enters information into, and place it into a text file. I've got this working roughly. I understand that this is not good practice for security reasons, but this is an assignment for class and I MUST put the information into the text file. I have the information going into the text file, however I am having trouble comparing the posted username to all of the usernames inside of the database. Here is my code for the newaccount.html page, and the register.php file that the form submits to.
newaccount.html
<html>
<head>
</head>
<body>
<h3>Hello new user! Choose a user name and password ^_^</h3><br>
<form action = "register.php" method = "POST" >
Username: <input type = "text" name = "username"><br><br>
Password: <input type = "password" name = "pass"><br>
<input type = "submit" value = "Create Account" name = "submit"><br>
</form>
<form method = "LINK" action = "Proj2_practice.html">
<input type = "submit" value = "Home Page" name = "submit2">
</form>
</body>
</html>
register.php
<?php
$username = $_POST['username'];
$password = $_POST['pass'];
$userAndPass = $username.",".$password;
$userNames = 'usernames.txt'." ";
$passwords = 'passwords.txt'." ";
$fh_users = fopen($userNames, 'a+')or die("sorry, we couldnt open the file");
$fh_passwords = fopen($passwords, 'a+')or die("sorry, we couldnt open the file");
fwrite($fh_users, $username." ");
fwrite($fh_passwords, $password." ");
$allUserNames = fread($fh_users, filesize('usernames.txt'));
echo $allUserNames;
?>
The usernames and passwords are being sent to the text files correctly, At the end of the code, it is not echoing the variable. As of right now, there is no information in the text files, I don't know if that is the reason that nothing is being echoed. Is my approach correct here? What I'm trying to do here is send each name and password to a username and password text file.Then, Im planning on
exploding each of those text files by a space between them, which is why I add one after writing them to the text file, and then comparing the usernames and the passwords by their respective array elements. Am I overcomplicating this as much as I think I am? Please share your comments with me, I'm just trying to get better ^_^
Thank you in advance!
if you open the file with the "a+" flag it will place the file pointer on the end of the file. so when you're reading then you won't get anything as you're already on teh end of teh file.
just go back to the beginning of the file before reading
fseek ($fh_users, 0);
or close and open it again with flag "r"
$fh_users = fopen($userNames, 'r')
or simply do
$dataString = file_get_contents($userNames);
or
$dataArray = file($userNames);
If this is a class assignment, can I suggest a method as well as a solution?
If things like this don't work, try to reduce the complexity of what you're trying to do and build step by step. You say yourself that your file is empty; if it's empty you're not going to be able to read from it so your first problem is figuring out how to correctly write to a file and read stuff back from it. Forget about all of the rest of your task, focus on that first.
Now, if you open a resource (such as a file), you must close it again when you no longer need it. So you definitely need an fopen / fclose pair to begin with.
$username = "Penguin";
$userNames = 'usernames.txt'; // Why did you have a space after this?
$fh_users = fopen($userNames, 'a+');
fwrite($fh_users, $username." ");
fclose($userNames);
I haven't tested this, but at this point, you should have a file that contains "Penguin ". If you run the code multiple times, you should see the file contents grow.
If you want to read things back from this file, realise that there is a file pointer that determines where you are going to read or write. You can open the file again in such a way that the file pointer is moved to the front (and so you can read what you need) or you can explicitly move it back to the front using fseek or rewind.
Once you have gotten this writing and reading to work, then add code to handle your form and so on.

Correct way to use an if statement and a $GET in PHP

Am fairly new to PHP and am making a basic CRUD style management system. I Have an update page and it displays data from a News table, and populates a form with it. The current picture ?(reference) is pulled through and displayed on the form. However if a user wants to change the picture they can press a 'delete' button and then I have written some PHP to display a upload button, set the values in the database for the image to null and hide the delete button, allowing the user to upload a new picture.
The Delete button only removes the reference (path) to the picture from the database, it doesn't delete the actual picture.
This is the HTML control to show the image and delete button. It also shows how the delete button works:
<td align="right">Image 1:</td>
<td align="left"><img src="uploads/newsimages/<?php echo $row["Image"]; ?>" width="230" border="0"> delete</td>
As you can see, when clicked it sets change=imagex and cid= the current news id.
There is then an if statement I have written, but it doesn't seem to only get activated when the delete button is clicked. Because I always get an error that 'cid' is undefined. It is as follows:
<?php
if (isset($_GET['change'] = "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I am pretty sure my lack of PHP knowledge is letting me down and I am trying to go about this the wrong way, because however I alter the if statement it always gives me an error. First it was cid is undefined so I changed to id but i already use that for something else, another query/function. I hope that all amde sense, can anyone tell me where Im going wrong?
You are missing a parenthesis + you have to specify individually:
if (isset($_GET['change'] = "image1") {
Change to:
if (isset($_GET['change']) && $_GET['change'] == "image1") {
Some more things to consider:
1) Don't use unsanitized values directly from $_GET in a mysql query
WHERE NewsID =".$_GET['cid']."
It is very easy to exploit this with some funky sql injection (see http://xkcd.com/327/ ).
If you are using numeric values for cid, you should cast your $_GET value to integer to prevent sql injection:
$cid = (int)$_GET['cid];
$query = '(...)WHERE NewsID = '.$cid.' limit 1';
Or even better:
$cid = (int)(array_key_exists('cid', $_GET) ? $_GET['cid'] : 0);
if ($cid) {
$query = (...)
}
If you need this kind of sanitizing in different places, you should think about writing a helper function for it to keep your code readable.
2) Don't use GET requests to change data on your server
Imagine a google bot browsing your site and following all those links that you use to delete images. Other scenarios involve users with prefetch plugins for their browsers (e.g. Fasterfox). Also, GET requests may be cached by proxies and browsers, so that the request won't hit the server if you click the link.
The HTTP specification comes with numerous request methods, the most important ones are:
GET to fetch content from the server
PUT to store new information on the server
POST to update existing information on the server
To update your news record (by removing the image) the appropriate method would be POST. To send a POST request, you can use the <form method="POST"> tag.
try this
<?php
if (isset($_GET['change']) && $_GET['change'] == "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>

I am making a form that includes city and email and a submit button and I need help on how I connect this to a database

I am having a difficulty of finding a answer that is simple to follow and understand... I making a site (on dreamweaver cs5) and the frontpage of the site has a select city and a dropdown of all the major cities and a email text box.
I have a few questions and those are as follows:
What is my next step now that I have the html pretty much done... do I connect it to a database?
What php script would I need to make sere both fields (the city and email) are filled? and where would I enter this php script?
Here is some of my code in case you were wondering:
http://answers.yahoo.com/question/index?qid=20110611111223AAeAnrT (had to put it on here because overflow wouldn't let me put in code..)
Just a quick starter, to get your form up.
On creating your PHP script, I don't know much about Dreamweaver, but if you have PHP installed on your server, you should be able to create it in the same directory as your HTML. All of the form elements should be in a form tag, and should point to the PHP, such as <form method="POST" action="dosomething.php"> before and </form> after.
Also, a "Please select your city..." might be nice to have on the form, like <option value="unset">Please select your city...</option>. (Also, all of the options in the sample should have a value attribute).
I don't know how much you have learned about PHP, so I'm going to try to start with the basics. The PHP script would be a plain-text file with the extension .php, such as dosomething.php. Inside of the script, the PHP code needs to be surrounded by the PHP start and end tags, <?php and ?>.
The values inputed into the form should be accessible with the $_POST variables in PHP, so in the script $_POST['select'] will be set to the current value. I recommend setting the names to something you can remember, such as selectedCity and emailAddress.
In our PHP script, we will want to get the variables from our form, and check to see if they are both filled. Then the data will get written to the database. I have created a sample snippet below that is commented, but extra security should be added, and this code should not be used as-is.
<?php
$city = $_POST['selectedCity']; // Get the city the user selected from the form
$addr = $_POST['emailAddress']; // Save the email address the user entered
if($city == "unset")
{
// Stops user if a city hasn't been selected
die("Please select a city."); // Stop executing code, and tell user to go back and select a city
}
if($addr == "")
{
// Stops user if the email address is blank (also would be good to make sure email address is correct, like user#domain.com)
die("Please enter a valid email address");
}
if(!file_exists("../mailinglist.sqlite"))
{
// Creates the database if it doesn't exist
// The database should be outside the document root (meaning you can't access it through the web)
$db = sqlite_open("../mailinglist.sqlite"); // Opens the database, creates it if non-existent (it is)
sqlite_query("CREATE TABLE users (city, email)"); // Creates a table for users
}
else
{
$db = sqlite_open("../mailinglist.sqlite"); // Opens the database if it exists
}
sqlite_query("INSERT INTO users (city, email) VALUES ('".sqlite_escape_string($city)."','".sqlite_escape_string($city)."')"); // Add the new user to the database
?>
(Anything that you need help with that is in blue should be searchable on the PHP Documentation)
The code above will take the output from the HTML form, check to make sure that it is not empty, and enter it into a database, creating a new database if it does not exist. Again, this is just a starter, and the code needs to be improved before taking it live.
Hope this helps!

Categories