需要帮助获取用户提交的值并从PHP表单生成唯一的URL

需要帮助获取用户提交的值并从PHP表单生成唯一的URL

问题描述:

In the script below, you will see a value that is submitted in the form titled "shorturl." Ultimately I would like to take that value and use it to generate a unique URL that displays all of the submitted data from the form.

Here is the form where a user will submits the data:

    <html>
    <body>

    <p>Required fields are <b>bold</b></p>

    <form action="contact.php" method="post">
<p><b>Author's Name:</b> <input type="text" name="author" /><br />
<p>Company Name: <input type="text" name="company" /><br />
<p>Address:<br /><textarea name="address" rows="5" cols="40"></textarea></p>
<p>Phone Number: <input type="text" name="phone" /><br />
<b>Title:</b> <input type="text" name="title" /><br />
<p><b>One Word Description:</b> <input type="text" name="shorturl" /><br />
<p><b>Full Description:</b><br />
<textarea name="comments" rows="10" cols="40"></textarea></p>

<p><input type="submit" value="submit"></p>

<p> </p>

</form>

</body>
</html>

The next bit of code is the contact.php page that will output the user data:

<?php


/* Check all form inputs using check_input function */
$author = check_input($_POST['author'], "Enter your name");
$company = check_input($_POST['company']);
$address = check_input($_POST['address']);
$phone = check_input($_POST['phone']);
$shorturl = check_input($_POST['shorturl'], "Provide a single word description");
$title  = check_input($_POST['title'], "Write a title");
$comments = check_input($_POST['comments'], "Provide a full description");




/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
    show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<b>Please correct the following error:</b><br />
<?php echo $myError; ?>

</body>
</html>
<?php
exit();
}
?>

<head>
    <title><?php echo $_POST['title']; ?></title>
</head>
<body>

<p>
<b><?php echo $_POST['title']; ?></b><br>
Created by:<br> 
<?php echo $_POST['author']; ?><br>
<?php echo $_POST['company']; ?><br>
Contact: <br>
<?php echo $_POST['phone']; ?><br>
<?php echo $_POST['address']; ?><br>
Flyer Description: <br>
<?php echo $_POST['comments']; ?><br>
</p>

</body>
</html>

As you will see if you run this form, the function is pretty basic. Here is where I need the assistance. In the initial form the "shorturl" value is taken. The function of the shorturl value is as follows:

If this form was hosted on examplesite.com, then I would ultimately like for the form that is created to be available with submitted answers at examplesite.com/shorturl

First of all, how do I verify that this is in fact a single word via PHP? If a user submits the shorturl value as "House" then I need the form to return the value as true, but if the user submits "Big House" then the value is false and they need to alter the value to something that is acceptable such as "BigHouse"

Secondly, I need to verify that the shorturl value is unique to the site. In other words, once a shorturl has been used, that value needs to be sent to the MySQL database so that it will not be replicated by another user. To continue our example, if someone already had "House" as their shorturl value then the full URL of examplesite.com/House is already taken. Then if a new user comes and tries to use "House" the submission will produce an error message that says the name is taken.

And finally, how do I get all of this information to auto-generate a unique webpage with the form results? For an example let's continue examplesite.com/House Right now, when a user submits the form, the data is displayed on examplesite.com/contact.php. How do I generate a URL which would display the form data and be unique as defined by the shorturl and be viewable to a third party site visitor without submitting new data?

Wow. I hope that all makes sense.

I know there are several questions in here, so if you can only assist with one step that is fine. If you can tackle this entire issue then more power to you :)

I have done a fair amount of research on this and I am thinking that the first 2 questions should be able to be solved with PHP, but the third might involve a mod_rewrite function of some sort. I cannot thank you enough for getting this far with my query and many many thanks if you can provide a solution.

This should do a good job of verifying $shorturl:

if (preg_match('/[^a-z0-9]/i', $shorturl)) {
    // $shorturl contains characters other than just numbers or
    // letters such as a tab, space, or special chars you probably don't want
}

As for making sure the url is unique:

if (!mysql_num_rows(mysql_query("SELECT id FROM contact WHERE url = '$shorturl' LIMIT 1")) {
    // it is unique, yay    
}

And you would insert the urls like so:

mysql_query("INSERT INTO contact (url) VALUES ('$shorturl')");

As for autogenerating the content, that shouldn't be that tricky. First, you will need to insert all the form data into the database, I would do this at the same time you insert the url. For dynamically retrieving the data, (using such a short url) you will need to do a tiny bit of .htaccess modification.

Here is an example of what your .htaccess might look like for a user to be able to go to domain.com/shorturl while the actual scripts being ran (and what they will see) are at domain.com/contact.php?short_url=shorturl

RewriteEngine on  

# don't rewrite if the file exists
RewriteCond %{REQUEST_FILENAME} !-f
# don't rewrite if the directory exists
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ contact.php?short_url=$1

At this point the rest is just capturing the GET variable as $_GET['short_url'] within contact.php (or anywhere you want this script to reside, as long as you change the RewriteRule accordingly) and returning the rest of the the information you captured using database queries, maybe something like:

$short_url = mysql_real_escape_string($_GET['short_url']);

$sql = "SELECT * FROM contact WHERE url = '$short_url'";
$user_data = mysql_fetch_array(mysql_query($sql));

extract($user_data);
// with extract, all of $user_data's keys are now variables and their respective values
// are contained within those variables
// $user_data['company'] now becomes simply $company, for example

echo "Company: $company";
// etc...

I hope this helps :)

I agree with Wylie. I also agree with you (Presto) that your post is a little hard to get at times x). Either way, I will try to answer your questions as fully as possible, based on what I understand what you mean.

1) The best way to check if it's a single word is by checking word delimiters. The most typical word delimiter is the space, but things like hyphens, commas, and periods are obviously delimiters as well. In your case, the best way to determine what to allow is to consider what will correctly parse as a URL and what won't. For example, you should not allow the plus sign (+) to be used.
You can do several things to prevent these kinds of breaks. You can either correct it, or refuse it. In other words, you can either replace/ remove 'illegal characters' without any additional interaction/ approval of the user, or you can simply bounce it back to the users stating that it is invalid and that they will need to fix it. You can do this at a server level (PHP) or at a client and server level (Javascript for direct check, and PHP as a fail safe). Depending on how tolerant you'll be, and whether you will fix or refuse a string, you should either use a str_ireplace() type of function, or you should use regexp (preg_match()). There is, at this point, no way for me to tell you which one to use.

2) I can't say what's the best way to do this, as this very strongly depends on your system setup, but if it would make sense in your system, I would use MySQL for this task and store the names of the 'page directory' in a table with at least two rows: id and shorturl (as you refer to it). The id should be the primary key and you'll use this id to identify (/ JOIN) data that is needed to be displayed on the web page. The shorturl column should be index as 'UNIQUE'. This way, if you try to insert another value in that table column, MySQL will throw you an error (I believe errno 1169). Because of this, you can simply run the insert query after a user has submitted your form (and your PHP code has checked it) and you can then just check for that errno to see if the name has been used before.

3) Depending on how you set up your web server, you can do several things. Writing a mod_rewrite file is of course possible (and fairly easy, as you can build it in PHP and just write it to your web server). Another way you can do it is to fetch the shorturl that the visitor typed in his/ her address bar and then cross check that with your database table (like the one from point two above here) and then do an internal redirect, using the header() function in PHP.

Let me know if that was of any help, or if things are still unclear.