Passing on validated variables to a different page (PHP) - php

On form index.php I have three input fields (Name, Surname and Date of Birth) which I want to pass along to form myProfile.php, the user cannot continue to the next myProfile.php unless all three fields have been completed.
How can I send the variables to the next page, once it has been determined that all the input fields are valid? Currently I can determine that all the input fields are valid, but I don't know how to pass the variables along to myProfile.php
Variables and Input handling (index.php):
<?php
$nameErr = $surnameErr = $dobErr = "";
$name = $surname = $dob = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
}
if (empty($_POST["dob"])) {
$dobErr = "Date of Birth is required";
} else {
$dob = test_input($_POST["dob"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Creating the form (index.php):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Surname:
<input type="text" name="surname">
<span class="error">* <?php echo $surnameErr;?></span>
<br><br>
Date of Birth:
<input type="date" name="dob">
<span class="error">*<?php echo $dobErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
My problem is that in order to send my name, surname and date of birth to myProfile.php, I need the form action to be action="myProfile.php", however for the input validation to take place it has to be action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>". How can I allow the input validation to take place, and if all the input is valid, then pass the variables along to myProfile.php in order to use the following code:
myProfile.php:
<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";
?>

You should be able to use PHP's session functionality to do this. Sessions are not specific to PHP, but PHP has functions which make it easy to maintain data about a specific visitor. This can be tricky because HTTP is a stateless protocol.
In index.php, after you have made sure that the data is valid you can store it in session by calling session_start and using the superglobal $_SESSION variable:
if ($data_is_valid) // you'll have to figure out yourself whether data is valid or not
{
session_start(); // you must call this before using $_SESSION
$_SESSION["valid_data"] = array(
"name" => $name,
"surname" => $surname,
"dob" => $dob
);
// redirect the user to the other page
header("location: myProfile.php");
// always remember to exit after redirecting or code may continue to execute
exit;
}
Then, in my Profile.php, you can call session_start and check for the valid data
session_start();
if (!array_key_exists("valid_data", $_SESSION)) {
die("No valid data found!"); // you might want to redirect back to the first page or something?
}
$data = $_SESSION["valid_data"];
if (!is_array($data)) {
die("Data found is not an array!");
}
// otherwise, data was found...you can keep going!
// you might get errors here if you didn't set these properly on the the previous page
$name = $data['name'];
$surname = $data['surname'];
$dob = $data['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";

Related

How do i create a php log in that outputs hello and then name

When the user logs in successfully I want it to output "hello" followed by the username.
I have problems with outputting the name.
Please be gentle since I am still learning.
<?php
$_user = "true";
$name = "";
$_POST = "";
if ($_user == "true") {
}else
$name = $_POST["$name"]; {
echo "Hello, " . "$name";
}
if ($_user !== "true") {
echo "youre not logged in";
}
?>
The problem in your code is that you set $_user to true in your first line, later you perform the statement if ($_user === true) , which is true, so the code in your else statement (in which you try to echo the username) is not executed.
Basically this is how you process a post in php:
if (!empty($_POST['name'])){
echo "The name is: " . $_POST['name'];
}
else{
echo "No name found in post.";
}
<?php
// Start a server side session, indentified by cookie.
session_start();
// Handle post data from form
if( empty($_POST['name']) ) {
// Post wasn't sent
echo '<form method="post">
<input type="text" name="name" />
<input type="password" name="password" />
<button type="submit">Login</button>
</form>';
} else if( isset($_POST['password']) ) {
// Normally you would handle a password or so here (either static or via querying a database)
echo 'You logged in with name: ' . htmlspecialchars( $_POST['name'] ) . ' and password ' . htmlspecialchars( $_POST['password'] );
// Set as logged in.
$_SESSION['name'] = $_POST['name'];
}
if( !empty($_SESSION['name']) ) {
// Writing input data, htmlsp... is for escaping html (don't trust user data)
echo 'Hi, ' . htmlspecialchars( $_SESSION['name'] ) . '<br />';
}

How to set validation on Phone number in PHP

This is my code:
I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend
what can I do? for set validation for phone number field.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $phoneErr = "";
$name = $phone = "";
$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['name']);
$phone = htmlspecialchars($_REQUEST['phone']);
if (empty($name)) {
$nameErr = "* Name is required";
$error = 1;
// echo "Name is empty";
}
if (empty($phone)) {
// echo "phone is empty";
$phoneErr = "* Phone is required";
$error = 1;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<h1>Login Form</h1>
Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
<span class="error"> <?php echo $nameErr?></span>
<br></br>
Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
<span class="error"> <?php echo $phoneErr?></span>
<br><br>
<input type="submit">
<br><br>
</form>
</body>
</html>
I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number
Sorry to answer an old post.
However, you can check if the number exists by calling a web service.
In this case, I found numverify.com, allowing to verify if a phone number exists.
After creating a free account (allows you to make 250 requests each month), you can invoke the following basic code in PHP:
// set API Access Key
$access_key = 'YOUR_ACCESS_KEY';
// set phone number
$phone_number = '14158586273';
// Initialize CURL:
$ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$phone_number.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Store the data:
$json = curl_exec($ch);
curl_close($ch);
// Decode JSON response:
$validationResult = json_decode($json, true);
I have no idea if this is reliable, but it worked with my phone number and even retrieved the company carrier.
According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.
$tel = '091-9869123456';
if(preg_match("/^[0-9]{3}-[0-9]{10}$/", $tel)) {
echo "valid";
} else {
echo "invalid";
}
Now for more validating need to check country code:
if(substr($tel, 0, 3) == '091'){
echo "valid";
} else {
echo "invalid, it should start with 091";
}
Or you do this with same preg_match like this:
if(preg_match("/^[091]{3}-[0-9]{10}$/", $tel)) {
echo "valid";
} else {
echo "invalid";
}
Demo
Why do you need to validate phone number using php?
You can do it using JS as shown below.
if (/^\+[-0-9]{6,20}$/.test(phoneNumber) == false) {
alert('Wrong Phone Number format. Only numbers,+ and - are allowed. Format: \<Country Code\>\<Phone number\> Eg: +9199999999, +1-105-893-9334 etc');
return;
}

How to save a PHP variable when a page loads twice

A user enters two dates periods on a text-box and a SQL select statement picks mobile numbers from a database entered in between the period. I want to pick and display them on a page. On the same display page, I have a text area where a user can type a message and on submit, it should be sent to these selected numbers and displayed mobile numbers. I am having a challenge on passing the $mobilenumber to the function sendbulk that is to send the message to the mobile numbers displayed by $mobilenumber variable. Everything else is okay apart from passing the $mobilenumber. I think this is because after the page loads to display the contacts selected, on the second load as you submit the $message to bulk function the value of $mobilenumber is already lost. How can I save it.
Check sample code below and please advice. How do I save the $mobilenumber so that by the second load it is still there to be passed to the function sendbulk()? Anyone?
<?php
//Define variable and set to empty values
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = test_input($_POST['message']);
echo "$message";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$time1 = isset($_POST['t1']) ? $_POST['t1'] : 'default something missing';
$time2 = isset($_POST['t2']) ? $_POST['t2'] : 'default something missing';
//connection
$sql = "SELECT DISTINCT msisdn FROM customer WHERE DATE_FORMAT(time_paid, '%Y-%c-%e') BETWEEN ADDDATE('$time1',INTERVAL 0 HOUR) AND ADDDATE('$time2',INTERVAL '23:59' HOUR_MINUTE)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo " Recipients: "; echo "$result->num_rows <br> <br>";
// output data of each row
while($row = $result->fetch_assoc()) {
$mobilenumber = $row['msisdn'];
echo "Mobile : " . "$mobilenumber" . "<br>";
}
} else {
echo "No Contacts to Display";
}
$conn->close();
sendbulk($mobilenumber,$message);
?>
<center></center> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<textarea name='message' rows="6" cols="60" placeholder="Please Type Your Message Here"></textarea>
<br><br>
<input type="submit" name="submit" value="Send Message">
</form></center>
<?php
function sendbulk($mobilenumber,$message) {
echo "$mobilenumber";
echo "$message";
$serviceArguments = array(
"mobilenumber" => $mobilenumber,
"message" => $message_sent
);
$client = new SoapClient("http://*******");
$result = $client->process($serviceArguments);
return $result;
}
You use sessions.
Here is a sample code:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count'] += 1;
}
echo $_SESSION['count'];
?>
Keep reloading this file via your web server. You should see the variable incrementing.
As an alternative, you can also use $_COOKIE. The only difference is that $_SESSION is saved on the server side and not accessible on the client. To identify the client it does store a cookie for that session on the client.
$_COOKIE on the other hand is completely stored on the client and passed by the browsers to the server on every request.
Also note a caveat, don't overload your session variables or cookies as it will hit your response times.
Also note that session_start() is required in every PHP file where you want to access the session.

PHP login from text file

Hi I have looked at other posts about this but they are 2 or more years old so I thought it was better to start fresh.
As the title suggests I am trying to make a login page with php. Users should be able to login to a special member only page. The usernames and passwords are stored in a textfile (note this is for an assignment otherwise I'd use SQL). My code is below
?php
echo "Username: <input type=\"text\" name=\user-name\"><br>";
echo "Password: <input type=\"text\" name=\pass-word\"><br>";
echo "<input type=\"submit\" value=\"login\" name=\"login\"><br>";
$userN = $_POST['user-name'];
$passW = $_POST['pass-word'];
$userlist = file ('users.txt');
$checkUser =$userlist[0];
if (isset($_POST['login']))
{
if ($userN == $userlist)
{
echo "<br> Hi $user you have been logged in. <br>";
}
else
{
echo "<br> You have entered the wrong username or password. Please try again. <br>";
}
}
?>
<form action="login.php" method="post">
Username: <input type="text" name="username">
<br />
Password: <input type="password" nme="pass"
<br />
<input type="submit" name="submitlogin" value="Login">
I know I need to use the explode function and I need to define how the text file will be set out. ideally username|password. in a file called users.txt The users file also has to contain information such as the email (can replace username) the customers name, the business name (of the customer) and special prices for members.
Lets say your text file looks something like this:
pete|petepass|pete#somesite.com|Pete Enterprizes
john|johnpass|john#somedomain.com|John Corporation
Your code can read something like this:
$userN = $_POST['user-name'];
$passW = $_POST['pass-word'];
$userlist = file ('users.txt');
$email = "";
$company = "";
$success = false;
foreach ($userlist as $user) {
$user_details = explode('|', $user);
if ($user_details[0] == $userN && $user_details[1] == $passW) {
$success = true;
$email = $user_details[2];
$company = $user_details[3];
break;
}
}
if ($success) {
echo "<br> Hi $userN you have been logged in. <br>";
} else {
echo "<br> You have entered the wrong username or password. Please try again. <br>";
}

Checkbox value not displaying

The form inputs aren't displaying on the form.php page and negates my form validation. The error says undefined variable for all my variables on form.php. Please tell me what I have to edit in my code to make it display the form inputs on form.php. It works when I use it on the same page but I would rather it display on another page.
EDIT
Thanks so far but I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A".
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>
If you would like to transfer the data from contact.php to form.php you should use something like this:
contact.php
$data = urlencode(
serialize(
array(
"name" => $name,
"email" => $email,
"subject" => $subject,
"message" => $message)
));
header('Location: form.php?data=' . $data);
form.php
$data = unserialize(urldecode($_GET['data']));
$name = $data["name"];
$email = $data["email"];
$subject = $data["subject"];
$message = $data["message"];
This serializes the array of data from contact.php then URL encodes it and sends it as a GET variable to form.php. After, form.php URL decodes and unserializes the data for use.
The problem is when you header("Location:") to form.php, all the POST values are lost. You have to either resend them with the header, or modify them into GET and retrieve them again. It should be more efficient to have them both (contact.php AND form.php) in one page. That way, the form data only has to be sent once.
You could probably just send the POST values as GET over to form.php like this.
contact.php:
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject."&message=".$message);
form.php (to retrieve the values):
$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];
$subject = $_GET['subject'];
If you want to display form elements then you have to use this approach.
<form method="POST" action="contact.php">
Email<input type="text" name="email">
.......
.......
.......
// All elements
</form>
This may help you.
Give action in your form in contact.php
<form action="form.php">

Categories