PHP how to split an array in variables - php

Hi everybody i need help! I've starting to learn php some week ago.
i have a form that POST some text field for a contact, i need to split the array in some variables to put in a email. this is my code
$field = $_POST['input'];
if ( isset( $field ) === TRUE){
foreach ($field as $key => $value) {
echo '<pre>' , print_r( $value ) , '</pre>'; //to list the array
}
$to = $mail;
$sbj = "thanks to register to $site";
..//some headers
mail($to,sbj,$headers)
}
and this is the form
<form action="upload.php" method="POST">
<input type="text" name="input[]">
<input type="text" name="input[]">
<input type="text" name="input[]">
<input type="submit" value="invia">
</form>
any suggestion for retrive the variables on the array to include on the mail?

#John has given the right procedure . You can use another procedure by using array_push() function eg:
$field = $_POST['input'];
$info = array();
foreach ($field as $key => $value) {
array_push($info,$value);
}
// echo implode(",",$info);
$to = $mail;
$sbj = "thanks to register to $site";
$body = implode(",",$info);
..//some headers
mail($to,sbj,$body,$headers)

You can use the implode() function , which takes an array and a separator and joins the elements of the array together into a string, with each element separated by the separator string you pass it eg:
foreach($field as $key=>$value) {
$input[] = $value;
}
$body = implode("\n",$input); //implode here
$to = $mail;
$sbj = "thanks to register to $site";
..//some headers
mail($to,sbj,$body,$headers)
This would create your list of input each on a separate line in the email.

the easiest, but most ugly way to to this is just using:
mail($to,sbj,print_r($field, true),$headers);
print_r($field, true) will output the value to a variable and not print it out immediately.

Related

How to pass multiple urls from text fields into array

I am trying to enter multiple urls from text field as input, into array to extract some data.
Here's my code
<form method="post">
<textarea name="urls[]" cols="150" rows="15" value=""></textarea>
<input type="submit" value="Get URLs" />
</form>
if (isset($_POST['urls']) && !empty($_POST['urls'])) {
// fetch data from specified url
foreach($_POST['urls'] as $key => $value){
$data = array($value);
$r = multiRequest($data);
}
}
foreach ($r as $key => $url){
$res = preg_match_all( "/[a-z0-9]+[_a-z0-9\.-]*[a-z0-9]+#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})/i",
$url, $matches);
if($res) {
foreach(array_unique($matches[0]) as $email) {
echo $email . "<br />";
}
} else {
echo "No data found.";
}
unset($value);
Now if I enter single url,www.example1.com, if fetches the data (email). But if I enter more than one url in the form, it doesn't works (No data found).
If I define url in array manually
$data = array('www.example1.com', 'www.example2.com', 'www.example3.com');
I can extract the data (email).
How to do it for multiple entries?
If you delimit your urls by a line return, we can split and process them:
<form method="post">
<textarea name="urls" cols="150" rows="15" value=""></textarea>
<input type="submit" />
Omit the square brackets on the input name if we have one textarea. (Alternatively use many text inputs with the name attribute urls[], to get your input into an array.)
<?php
$urls = $_POST['urls'] ?? '';
$urls = preg_split('#\R#', $urls);
$emails = [];
foreach ($urls as $url)
{
$pattern = '/[a-z0-9]+[_a-z0-9\.-]*[a-z0-9]+#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})/i';
if (preg_match_all($pattern, $url, $matches))
{
foreach(array_unique($matches[0]) as $email) {
$emails[] = $email;
}
}
}
if(empty($emails)) {
echo 'No emails found.';
} else {
print implode('<br>', $emails);
}
The input:
http://example.com
mailto://foo#example.com
Will output:
foo#example.com
You're passing one value in $data array by this syntax $data = array($value);.
Replace $data = array($value);
with
$data = array();
$data[] = $value;
This will append each new value to the &data array.
Example
Also, you have one textarea, it means that the value(text input) of it comes into name=urls[] as a first value of array urls[]. In PHP you'll get one value.
If you want to separate inputted data you need to split it. For example, if you will write inputs comma separated, then you'll need to make explode(",",$_POST["urls"];) at least. By the way, change name="urls[]" to simply name="urls".
Use this code for retrieving inputs comma separated:
<form method="post">
<textarea name="urls" cols="150" rows="15" value=""></textarea>
<input type="submit" value="Get URLs" />
</form>
if (isset($_POST['urls']) && !empty($_POST['urls'])) {
// fetch data from specified url
$inputs = explode(",",$_POST["urls"]);
$data = array();
foreach($inputs as $key => $value){
$data[] = $value;
}
$r = multiRequest($data);
}
As I understood your multiRequest() function should process your $data array, put this line outside the foreach loop. If you won't you will process $data array each loop.
Note: inputs should be comma separated in this case(in textarea).

how to store $_POST values to save in a file line by line

I have a PHP form and I want to save the selected values to a file one in a line. I am not very much used with PHP.
Right now, my script is storing data in one line with many other characters included. Below is the code I am using in the action.php
if(isset($_POST)) {
$o = json_encode($_POST);
file_put_contents('data.txt',$o);
die();
}
The output I am receiving in data.txt is like below.
{"formDoor":["phpandmysql.tk\r\n","mytestdomainjordi\r\n","my1domain\r\n","ihatelinux\r\n","php1andmysql.tk\r\n","lubitz.co\r\n","testereed.com\r\n"],"formSubmit":"Submit"}
What I would like to get is something like this:
phpandmysql.tk
mytestdomainjordi
my1domain
ihatelinux
php1andmysql.tk
lubitz.co
testereed.com
EDIT
FORM:
<?php
$handle = fopen("newtest1.txt", "r");
if ($handle) {?>
<form action="checkbox-form.php" method="post">
<?php
while (($line = fgets($handle)) !== false) {
?>
<input type="checkbox" name="formDoor[]" value="<?php echo $line; ?>"/><?php echo $line; ?><br />
<?php
}
}
?>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
fclose($handle);
?>
I googled to come this far, can somebody help me?
Thanks in advance.
"formDoor" is a key in your $_POST associative array (which is similar to a dictionary here). You can access it via $_POST['formDoor'], and check for its existence via isset($_POST['formDoor']). Outputting the formDoor parameter to the file can be done like this:
if(isset($_POST['formDoor'])) {
$formDoor = $_POST['formDoor'];
// check if the formDoor field is actually an array
if(is_array($formDoor)) {
// combine the array values into a string
$data = implode('',$formDoor);
file_put_contents('data.txt', $data);
}
try like this
$result="";
foreach ($_POST["formDoor"] as $key => $value) {
$result.=$value. "\n";
}
file_put_contents('data.txt',$result);
Use this:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$result="";
foreach ($_POST as $key => $value)
{
$result .= $key. " = ". $value. "\r\n";
}
file_put_contents('data.txt',$result);
}

use implode in $_GET

I have some forms in my page like :
<form method="get">
Enter Your Firstname :<input type="text" name="t1" />
Enter Your Lastname :<input type="text" name="t2" />
<input type="submit" name="sb" />
</form>
so users will fill this form and i want to have values of this form separated with comma
for example
John,Smith
James,Baker
so here is my php code
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
foreach ( $t_array as $key )
{
echo implode(',' , $_GET[$key]);
}
}
When i try to do this , i got this error :
Warning: implode() [<a href='function.implode'>function.implode</a>]: Invalid arguments passed in PATH on line 24
i don't know why i can't use implode in $_GET or $_POST
so how can i solve this problem ?
P.S : i want to use array and implode in my page , please don't write about other ways
There is an error in your logic.
here is sample code that might help you:
$t_array = array($_GET['t1'], $_GET['t2']);
$imploded = implode(',', $t_array);
echo $imploded;
This will work.
You're calling implode on a value, not an array. This code
echo implode(',' , $_GET[$key]);
calls it on $_GET[$key], which is a string.
You are trying for implode($_GET);.
What you need is something like below, you don't actually need implode for this:
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
$result = '';
foreach ( $t_array as $key )
{
if ($result != '') $result .= ',';
$result .= $_GET[$key];
}
}
You can't impode strings...
Try something like this:
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
$arr = array();
foreach ( $t_array as $key )
{
$arr[] = $_GET[$key];
}
echo implode(',' , $arr);
}

post to form via php with array

i'm using sirportly for my support and i have the ability to post forms remotely via html, however i'm trying to integrate this into wordpress and so want to post this form from a plugin via curl/php the challenge i am having is to post into array objects:
eg the basic original HTML form generated by sirportly contains the following:
<input type='text' name='ticket[name]' id='form26-name' />
<input type='text' name='ticket[email]' id='form26-email' />
<input type='text' name='ticket[subject]' id='form26-subject' />
<textarea name='ticket[message]' id='form26-message'></textarea>
i know for basic form elements eg name=name, name=email etc i can do the following:
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
how do i do similar given that the elements need to be posted as 'ticket[name]' rather than just 'name'
EDIT/UPDATE - ANSWER
thanks to the answers below i came up with the solution, my issue wasn't getting access to the data from the array as i was recieving it a different way (but from an array all the same), but correctly encoding it in the post request, here is what i ended up with(note that i'm using gravity forms to get the data:
//numbers in here should match the field ID's in your gravity form
$post_data['name'] = $entry["1"];
$post_data['email'] = $entry["2"];
$post_data['subject'] = $entry["3"];
$post_data['message']= $entry["4"];
foreach ( $post_data as $key => $value) {
$post_items[] = 'ticket[' . $key . ']' . '=' . $value;
}
$post_string = implode ('&', $post_items);
i just had to change the for loop to wrap the extra ticket[ and ] parts around the key for the post submission
foreach ( $post_data['ticket'] as $key => $value) {
$post_items[] = $key . '=' . $value;
}
The form you listed above will result in this structure on server:
$_POST["ticket"] = Array(
"name" => "some name",
"email" => "some#thing",
"subject" => "subject of something",
"message" => "message text"
);
So, $_POST["ticket"] is really your $post_data
You access the variable by this: $_POST['ticket']['name']
so if you want to see the value you should: echo $_POST['ticket']['name'];
to loop you go:
foreach($_POST['ticket'] as $key => $val){
echo "Key => " . $key. ", Value => " . $val . "<br />";
}

Automate assignment of multiple values from the $_POST variable

I just wrote the following code:
<?php
$email = checkPost("email");
$username = checkPost("username");
$firstname = checkPost("firstname");
$lastname = checkPost("lastname");
$zipcode = checkPost("zipcode");
echo("EMAIL: ".$email." USERENAME: ".$username);
function checkPost($formData) {
if (isset($_POST[$formData])) {
return $_POST[$formData];
}
}
?>
What I'd like to do is eliminate all those calls to checkPost() at the top. This code below doesn't require any knowledge of the fields in the form that submits to it, it just loops through all of the fields and spits out their values.
<?php
// loop through every form field
while( list( $field, $value ) = each( $_POST )) {
// display values
if( is_array( $value )) {
// if checkbox (or other multiple value fields)
while( list( $arrayField, $arrayValue ) = each( $value ) {
echo "<p>" . $arrayValue . "</p>\n";
}
} else {
echo "<p>" . $value . "</p>\n";
}
}
?>
I want to modify this code such that variables like $email, etc would be created and assigned values on the fly. Like say you run this on a form that has "email" and "name". You won't have to give php a variable name $email or $name. It will just loop through and for "email" create and fill a variable named $email and so on and so forth.
Am I dreaming?
foreach ($_POST as $key=>$value) {
echo '<p>', htmlspecialchars($key), ' = ', htmlspecialchars($value), '</p>';
}
I think that's what you're looking for anyway. Basically, we just loop through all $_POST elements and display them. You can of course do whatever you need with them, within the loop.
You could use...
extract($_POST, EXTR_SKIP);
...but I don't recommend it. This will unpack the array's keys into the scope it is in. I've set it to not overwrite existing variables.
You should explicitly define your variables.

Categories