How To Add ucwords() in PHP To HTML Form Value? - php

I have a basic contact form on my website and I am trying to add the PHP ucwords() function of PHP to the form for the users first_name and last_name fields so they capitalize the first letter correctly. How would I add this to the actual HTML form?
Edit: I want these changes to be applied only after the user submits the form. I don't really care about how the user types it in. I just need someone to actually show me an example.
Like how would I add the PHP ucwords() code to this simple form?
<!DOCTYPE html>
<html>
<body>
<form action="www.mysite.com" method="post">
First name: <input type="text" name="first_name" value="" /><br />
Last name: <input type="text" name="last_name" value="" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I am assuming I do something like value='<php echo ucwords() ?>' but I have no idea how?
Thanks!

When user submit the form you can access the submitted information through $_POST variable [because method="post"] of PHP and in action you have to specify the actual page where you need the submitted information to be process further
<?php
// for example action="signup_process.php" and method="post"
// and input fields submitted are "first_name", "last_name"
// then u can access information like this on page "signup_process.php"
// ucwords() is used to capitalize the first letter
// of each submit input field information
$first_name = ucwords($_POST["first_name"]);
$last_name = ucwords($_POST["last_name"]);
?>
PHP Tutorials

Assuming short tags are enabled:
$firstName = 'Text to go into the form';
<input type="text" name="first_name" value="<?=ucwords($firstName)?>" />
Otherwise as you stated
<input type="text" name="first_name" value="<?php echo ucwords($firstName); ?>" />

Assuming you wanted to do it without a page refresh, you need to use Javascript. Simplest way would be to add an onkeyup event to the input field and simulate PHP's ucwords functions, which would look something like...
function ucwords(str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
Edit: In response to your edit, if you want to get the value they sent with ucwords applied, all you need to do is $newVal = ucwords($_POST['fieldName']);

Related

How do I use get method to input values to form field with PHP

I have the following code snippet of my fields I have in my form:
<input id="username" type="text" placeholder="E-mail Address" value="" name="username"></input>
This is what I have in my input field. Is there anybody who will tell me how to get input values to the field using a url? e.g https://mysite?username=ken and it will show "ken" in the input field?
In your HTML, add the input field like this:
<input type="text" name="username" value="<?php echo htmlspecialchars($_GET['username']); ?>" />
Basically, the value attribute of the text field needs to be set to:
<?php echo $_GET['username']; ?>
The code right above this is how you would output a get variable in php whether you are putting it in a text field or not.
To access get variables, always use:
$_GET['variable_name'];
Then you can assign it to variables or pass it as a function parameter.
**However, I strongly do not recommend passing sensitive information like usernames and passwords through GET variables. **
First off, users could change the URL hence changing the variable. They could also accidentally share the URL with someone and that could give someone else access to their account. I would recommend that you create a cookie on their machine that is set to a random ID, and then in a MySQL database, associate that ID with a username so that you know the user can't accidentally share their account or change their username through the URL.
You can do it like this, make an isset in your php form input that can catch your ken variable from GET post, never forget the method="get" inside the form tag and if you are planning on submitting on the same page you can use action="<?php echo $_SERVER['PHP_SELF']; ?>" inside your form tag.. hope this helps, here is your code.. ^_^
<form id="form" name="form" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<p>Input</p>
<div>
<input type="text" name="nameoffield" id="nameoffield" value="<?php if(isset($_GET['ken'])){echo $_GET['ken'];} ?>"> <br />
</div>
</fieldset>
<div>
<button type="submit" value="Submit" name="submit">
Submit
</button>
</div>
</form>
The <input> tag and other fields of form must be in a <form>tag.
<form action = "https://mysite" method = "get">
<input id = "username" type = "text" placeholder = "E-mail Address" name = "username" value = "<?php echo $_GET['username']; ?>" />
</form>
In the above code, form tag specifies that the method of submission is 'GET' and the action that will be taken on submission is URL to which your form data will be submitted and processed.
Now assuming that your form is in the same URL to which you are submitting your form, you will get the GET value in the same page (or URL), so in the input text field set the value which is obtained by GET method and use it.
All the GET key-value pairs are stored in an associative array $_GET from which you can access the value of a given key by using that as the index of the array.
e.g. Key is username in this case, so to get the value of the username, $_GET['username'] was used.

Change certain text from User input (From a User Input field)

I want to have a simple HTML input field where people can type all kinds of nonsense. For example, a user types: "Hello, I'm Nicky". When the user then clicks the button Send, I want a simple PHP script to replace the word "Nicky" to "Nicki" and show it to the user. So basially, just a simple PHP script which replaces specific words from an input field and then print out the exact same line the user has inputted, except show Nicki instead of Nicky.
How can I achieve this, in the most simplest way?
My code looks like this now:
<?php
$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']);
?>
<form method="post">
<input type="text" name="name">
<input type="submit">
</form>
<?php
if(isset($_POST['form-action']) && $_POST['form-action'] == "submit-form"){ // form has been submitted
echo "<p>BEFORE: ".$_POST['name']."</p>"; // what the user entered "Nicky"
$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']); // find/replace Nicky with Nicki
echo "<p>AFTER: ".$_POST['name']."</p>"; // what the $_POST['name'] now is
}
?>
<form method="post">
<input type="text" name="name" value="Nicky">
<input type="submit">
<input type="hidden" name="form-action" value="submit-form">
</form>
In addition to this, if you want to expand the Find & Replace variables, you could use an array:
$FindReplace = array("Nicky"=>"Nicki", "Blue"=>"Red"); // build an array of find/replace variables
....
foreach($_POST as $Name=>$Value){
echo "<p>Before: ".$Name."=".$Value."</p>"
foreach($FindReplace as $Find=>$Replace){
$Value = str_replace($Find,$Replace,$Value);
}
echo "<p>After: ".$Name."=".$Value."</p>"
}

How to capture data from form and put these data into a HTML file

My company want to make things easier. We always create a letter for our customers to say our thank you. We have a letter that has the same content. As an example:
hi (customer_name),
thank you for doing business with us! we will contact u at (customer
number)
What I want to do is to let my staff edit the content of the letter from a form like:
Customer name: _________________
phone: _________________
[submit button]
On click of the submit button, the data from here will be saved into a DB and append to the letter just now and the letter will also saved into a DB.
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$letter = 'hi (customer_name),
thank you for doing business with us! we will contact u at (customer_number)';
$letter = str_replace('(customer_name)', $_POST['customer_name'], $letter);
$letter .= str_replace('(customer_number)', $_POST['customer_number'], $letter);
//db save code here..
//save $letter variable into db
}
?>
<form method="post">
<input type="text" name="customer_name" /><br />
<input type="text" name="customer_number" /><br />
<input type="submit" value="Submit" />
</form>
It isn't that hard. Firstly, you need to create a form.
<form method="post" action="path/to/file.php">
<input type="text" name="customerName" placeholder="Customer Name">
<input type="text" name="phoneNumber" placeholder="Phone Number">
<input type="submit" value="Generate">
</form>
So, now when the button is clicked, the data will be sent through a POST request to the URL specified in the action attribute defined in the <form> tag. So, to fetch a value from what was entered in the form, you have to access the $_POST super global. Every single form that is submitted with the method attribute set to post, all the input fields data is moved on to the $_POST super global, and to access a specific value for a specific input field, you will have to fetch it from the index in the $_POST super global which is equal to the value specified in the input field name attribute. So, for example, to get the customer name, you would try to get it from $_POST['customerName'.
So, you can do something like this:
$string = "hi " . $_POST['customerName'] . ",<br /><br />thank you for doing business with us! we will contact u at " . $_POST['phoneNumber'];
And now, you can save this $string to your database in a table.
More information on this topic can be found here:
http://www.w3schools.com/php/php_forms.asp
http://php.net/manual/en/tutorial.forms.php
http://myphpform.com/
http://www.the-art-of-web.com/php/form-handler/

get custom attribute value in php

I am try to get the value of the input field with a custom attribute I have created using PHP. This is my code:
<form action="uploadform.php" method="post">
<input type="text" name="email" id="email" mynewattribute="myemail">
<input type="submit" name="submit">
</form>
//uploadform.php
<?php
//I know $name = $_POST['email']; will give me the value but I would like to get the value of the input field with "mynewattribute" and not name. Is it possible?
?>
The web browser doesn't know what to do with your custom attribute, so will simply ignore it. The only data sent when you submit the form is the values of "successful" elements. So your custom data will never be sent, and can never be read by the receiving script.
The best place to put such data is into hidden input fields. One possibility is to use names with square brackets in, which PHP automatically converts into arrays. e.g.
<input type="text" name="email[value]">
<input type="hidden" name="email[magic]" value="true">
Populates an array like this:
$_POST['email']['value'] = '';
$_POST['email']['magic'] = 'true';

Is there something wrong with my form?

I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />

Categories