Edward Edward - 3 years ago 214
PHP Question

How to POST data from a textarea form?

Here is my current code:

<?php
$apikey='IGNORE-THIS-VARIABLE';

// All URLS to be sent are hold in an array for example
$urls=array('http://www.site1.com','http://www.site2.com/');

// build the POST query string and join the URLs array with | (single pipe)
$qstring='apikey='.$apikey.'&urls='.urlencode(implode('|',$urls));

// Do the API Request using CURL functions
$ch = curl_init();
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_URL,'http://www.example.com/api.php');
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_TIMEOUT,40);
curl_setopt($ch,CURLOPT_POSTFIELDS,$qstring);
curl_exec($ch);
curl_close($ch);
?>


My PHP code works, but here's the line I'm having issues with:

$urls=array('http://www.site1.com','http://www.site2.com/');


Basically I just want to have a text-area on my website where users can enter a list of URLs (one per line) and then it Posts it using the PHP code above.

My code works when I just have the URLs built into the code like you can see above, but I just can't figure out how to make it work with a text-area... Any help would be appreciated.

Answer Source

You can do it like below (on the same php page):-

<form method = "POST">

<textarea name="urls"></textarea><!-- add a lable that please enter new line separated urls -->

<input type = "submit">

</form>

<?php

if(isset($_POST['urls'])){
    $apikey='IGNORE-THIS-VARIABLE';

    // All URLS to be sent as new-line separated string  and explode it to an array
    $urls=explode('\n',$_POST['urls']); //Or $urls=explode('\\n',$_POST['urls']);
    // if not worked then 
    //$urls=explode(PHP_EOL,$_POST['urls']); 

    // build the POST query string and join the URLs array with | (single pipe)
    $qstring='apikey='.$apikey.'&urls='.urlencode(implode('|',$urls));

    // Do the API Request using CURL functions
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_URL,'http://www.example.com/api.php');
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_TIMEOUT,40);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$qstring);
    curl_exec($ch);
    curl_close($ch);
}
?>

Note:- you can separate the form and logic on two different pages. that's seay i think.

You can use text-area and then you have to then explode by \n or if not work then explode by PHP_EOL to the initial url string and rest the code is same as above

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download