function isset() checks whether variable is set or not and return boolean true or false.
You can use below code :
if (! (isset($_POST['name']) && isset($_POST['description']))) {
http_response_code(422);
echo 'name and description are required.';
exit;
}
$name = $_POST['name'];
$description = $_POST['description'];
I suggest you to try to install guzzle.
http://docs.guzzlephp.org/en/stable/quickstart.html
To do a request to your api would be simple like
use GuzzleHttpClient;
$client = new Client();
$response = $client->post('adsf', [
'auth' => ['username', 'password'], // basic auth
// sending data via form request
'form_params' => [
'name' => 'Some name',
'description' => 'Some description'
]
]);
var_dump($response->getBody());
var_dump($response->getStatusCode());
I’m new to PHP, and I’m developing a simple client for one of my subjects in college. The main goal of this client, is to do CRUD into a JAVA API. After a little research, I saw that for simple clients like this one, people use CURL. I have never worked with curl and I don’t know if I’m doing something wrong. When I submit my form it doesn’t appear any error, but when I open postman I see that my data was not posted successfully.
If anyone could help me, I would be grateful!
HTML FORM:
<form class="form" action="createActivity.php">
<label for="name" class="labelActivityName"><b>Name</b></label>
<input type="text" id="name" placeholder="Name" name="name">
<label for="description" class="labelActivityDescription"><b>Description</b></label>
<textarea id="description" placeholder="Description..." name="description"></textarea>
<button type="submit"><b>Submit</b></button>
</form>
PHP CURL:
$url = "http://localhost:8080/myapi/actvities";
$username = 'user';
$password = 'user123';
$name = (isset($_POST['name']));
$description = (isset($_POST['description']));
$fields = array(
'name' => $name,
'description' => $description
);
$client = curl_init();
curl_setopt($client, CURLOPT_URL, $url);
curl_setopt($client, CURLOPT_RETURNTRANSFER,1);
curl_setopt($client, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($client, CURLOPT_USERPWD, "$username:$password");
curl_setopt($client, CURLOPT_POST, 1);
curl_setopt($client, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($client);
curl_close($client);
hum ok, I’m starting to understand, but if I remove the isset, php throws this error “notice: undefined index: name”, what can I do to fix this?
hum, I updated my code with your snippet, and now when I run this it only appears “name and description are required”, and it doesn’t let me see the form to introduce the data