i have a html button that made a CURL. When i click this button, is possible to show the browser pop up for the proxy authentication?
I don’t want to set the credentials of the proxy in the curl script.
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
i have a html button that made a CURL. When i click this button, is possible to show the browser pop up for the proxy authentication?
I don’t want to set the credentials of the proxy in the curl script.
Is it good to use && as shorthand for if only statement in PHP? I like its simplicity but is it a good practise to use it?
Example: $a == "foo" && $b = "bar" ;
Is it more like if($a == "foo" && $b = "bar"){} than if($a == "foo"){ $b = "bar" } ?
If so, could it cause any problems?
I have this PHP form validator that is also hooked up to a mail function and to keep things organized I did the form validation in a separate function that is being called when the form is submitted.
Now I have this problem that I don’t know how to display the error message when a field is empty in the HTML form.
Can anyone help? Thank you in advance.
I’m also pretty new to PHP and the whole thing.
PHP:
<?php
// Validation function
function validation($name, $email, $message) {
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
$errors = array();
// Calling function
validation($fname, $femail, $fmessage);
}
HTML:
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="[email protected]"aria-label="[email protected]">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?php echo($final); ?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
Plese i need you’re help !!
I want to open modal by from table by ID, What is the right syntax ?
For link:
data-target="#form_modal?id='.$row1['id'].'"
The Modal
<div class="modal fade" id="form_modal" aria-hidden="true">
I’ve been working on this form for a bit, and it seemed like I solved every error I had earlier and the contact form works. The problem is it works in every browser except Firefox, and I guess it’s because the security level in ff is higher. We work with a high-security level, and my first guess was that Content-Security-Policy was blocking it, but when I don’t validate before submitting it works fine.
This is the code I have, note the last script in HTML, normally an include from include_recaptcha.html
const form = document.getElementById('kontaktskjema');
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.errorkontakt');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.errorkontakt');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.errorkontakt')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.errorkontakt')
const navnboks = document.querySelector('.navnboks')
const teleboks = document.querySelector('.teleboks')
const mailboks = document.querySelector('.mailboks')
const messageboks = document.querySelector('.messageboks')
const vernboks = document.querySelector('.vernboks')
const personvern = document.getElementById('checkbox');
const personvernError = document.querySelector('#checkbox + span.errorkontakt')
const submitbtn = document.getElementById('submitbtn');
// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')
email.addEventListener('input', function (event) {
if (email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-ok" )
emailError.innerHTML = '';
emailError.className = 'errorkontakt';
} else {
showError();
}
});
navn.addEventListener('input', function (event) {
if (navn.validity.valid) {
navnError.innerHTML = '';
navnError.className = 'errorkontakt';
navnboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
telefon.addEventListener('input', function (event) {
if (telefon.validity.valid) {
telefonError.innerHTML = '';
telefonError.className = 'errorkontakt';
teleboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
message.addEventListener('input', function (event) {
if (message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-ok" )
messageError.innerHTML = '';
messageError.className = 'errorkontakt';
} else {
showError();
}
})
personvern.addEventListener('change', function (event) {
if (personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
function makeRed() {
if (!navn.validity.valid) {
navnboks.setAttribute("class", "data-validation-error-true")
}
if (!email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-true")
}
if (!telefon.validity.valid) {
teleboks.setAttribute("class", "data-validation-error-true")
}
if (!message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-true")
}
if (!personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-true")
}
};
function divFill() {
if (navnError.textContent != '') {
errOutput.innerHTML += '<li>Navn</li>'
}
if (emailError.textContent != '') {
errOutput.innerHTML += '<li>E-mail</li>'
}
if (telefonError.textContent != '') {
errOutput.innerHTML += '<li>Telefonnummer</li>'
}
if (messageError.textContent != '') {
errOutput.innerHTML += '<li>Beskjed</li>'
}
}
function showError() {
errOutput.innerHTML = ''
if(navn.validity.valueMissing) {
navnError.textContent = '* Du må fylle inn navnet ditt';
navnError.setAttribute("class", "data-validation-error-true" )
} else if(navn.validity.tooShort) {
navnError.textContent = '* Du må fylle inn hele navnet ditt'
}
if(email.validity.valueMissing) {
emailError.setAttribute("class", "data-validation-error-true" )
emailError.textContent = '* Vennligst fyll inn e-posten din';
} else if(email.validity.typeMismatch) {
emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
} else if(email.validity.tooShort) {
emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
}
if(telefon.validity.valueMissing) {
telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
telefonError.setAttribute("class", "data-validation-error-true" )
} else if(telefon.validity.tooShort) {
telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
}
if(message.validity.valueMissing) {
messageError.setAttribute("class", "data-validation-error-true" )
messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
} else if(message.validity.tooShort) {
messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
}
}
emailError.className = 'errorkontakt kontaktactive';
navnError.className = 'errorkontakt kontaktactive';
telefonError.className = 'errorkontakt kontaktactive';
messageError.className ='errorkontakt kontaktactive';
<div id="contact-form-wrapper" class="align-right-50 lazyload">
<div id="contact-form-padding">
<h2>Send oss en melding</h2>
<p><span class="required">*</span> obligatorisk felt som du må fylle ut</p><br>
<div class="errorsOutput">
</div>
<div class="skjema">
<form id="kontaktskjema" action="nyhandler.kontakt.php" method="post" novalidate>
<input type="hidden" id="sendtfra" name="Sidetittel" value="{title}" />
<input type="hidden" id="sendtfraURL" name="Side URL" value="{url}" />
<div class="navnboks">
<p>
<label for="navn">
<span>* Navn:</span>
<input type="text" id="navn" name="navn" required minlength="3" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="mailboks">
<p>
<label for="mail">
<span>* E-post:</span>
<input type="email" id="mail" name="mail" required minlength="6" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="teleboks">
<p>
<label for="telefon">
<span>* Telefonnummer:</span>
<input type="tel" id="telefon" name="telefon" required minlength="8" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="messageboks">
<p>
<label for="message">
<span>* Melding:</span>
<input type="text" id="message" name="message" required minlength="10" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="vernboks">
<input type="hidden" id="recapta" name="g-recaptcha-response" />
<p>
<label for="personvern">
<div class="personvern">
<span>* Personvern:</span>
<br>
<input type="checkbox" id="checkbox" name="checkbox" required>
<span>Jeg har lest og godkjent <a href="/ac/personvern">Personvernserklæringen (åpnes i nytt vindu)</a></span>
<span class="errorkontakt" aria-live="polite"></span>
</div>
</label>
</p>
</div>
<button value="Send" class="button-send">Send</button>
</form>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<script src="https://www.google.com/recaptcha/api.js?render={sitekey}" async defer></script>
<script>
var rcf = document.getElementsByName('g-recaptcha-response');
for(var i=0; i<rcf.length; i++) {
rcf[i].form.addEventListener('submit', function(e) {
if (!navn.validity.valid || !email.validity.valid || !telefon.validity.valid || !message.validity.valid) {
makeRed();
divFill();
e.preventDefault();
} else {
grecaptcha.execute('{sitekey}', {action: 'homepage'})
.then(function(token) {
document.getElementById('recapta').value = token;
e.target.submit();
});
}});
}
</script>
Hey i wanna make a autonumber code for my product table without using models. How should i write the code on the controller?
Example :
BRG-0001
BRG-0002.
Im not using a models, just using query builder methods. So how should i write in the controller?
Sorry if its something simple I’m just missing but I’m quite new to PHP and don’t understand why I’m getting a syntax error, unexpected token "}" on lines 4, 5 and 6. Here is my code:
if (isset($_POST["submit"])) {
echo "It works";
}
else {
header("location: ../signup.php")
}
I know there were similar threads but nothing seems to be helping in my case.
I have a multidimensional array which outputs nicely with the foreach loop if there are multiple elements
Array
(
[0] => Array
(
[amount] => 1
[productid] => IPAPER-BA-KI-001
[price] => 33
[name] => Backyard Exploration Playground Set
[description] => Whether your backyard is large or small, this play…
)
[1] => Array
(
[amount] => 1
[productid] => IPAPER-BI-KI-001
[price] => 4344
[name] => Bikerkids-Pro lightweight kids bicycle
[description] => The classic model of Bikerkids-Pro boy's and girl'…
)
)
Output:
Backyard Exploration Playground Set 33 1 Whether your backyard is large or small, this play…
Bikerkids-Pro lightweight kids bicycle 4344 1 The classic model of Bikerkids-Pro boy's and girl'…
But as soon as my array has only one element I get the following output
1 1 1 1 1
I I I I I
4 4 4 4 4
B B B B B
T T T T T
My code is here.
<H2>Item Details</H2>
<?php
echo '<table>';
foreach ($arrOutput['item'] as $mydata)
{
echo '<tr>';
echo '<td style="padding: 5px;">' . $mydata['id'] . '</td>';
echo '<td style="padding: 5px;">' . $mydata['name'] . '</td>';
echo '<td style="padding: 5px;">' . $mydata['price'] . '</td>';
echo '<td style="padding: 5px;">' . $mydata['amount'] . '</td>';
echo '<td style="padding: 5px;">' . $mydata['description'] . '</td>';
echo '</tr>';
}
echo '</table>';
i have a question regarding PHP in combination with JSON.
Im using an array to store inside of a .json file. The array which has the data for it comes from my index.php and is getting filled up by the user, so far so good. Everythings saving inside the .json, just when i have more than 1 user storing stuff in it (meaning having 2 arrays inside the .json file) it doesnt return me the data, instead it is returning me NULL. Am i missing something regarding the saving or reading of the JSON file? I figured out that my JSON is invalid and it’s showing me “Multiple Root JSON elements” inside the validator.
Here my code of writing and reading the .json:
public function JSONwrite($lists)
{
$listFill = json_encode($lists)."n";
file_put_contents("/var/www/html/3sprint/test.json",$listFill,FILE_APPEND);
}
public function JSONread()
{
$string = file_get_contents("/var/www/html/3sprint/test.json");
$stringContent = json_decode($string, true);
var_dump($stringContent);
}
My JSON file looks something like this (filled with 2 arrays):
[{"count":"3","name":"testnameone"},{"count":"5","name":"testnametwo"},{"count":"6","name":"testnamethree"},{"info":106}]
[{"count":"3","name":"testnamefour"},{"count":"5","name":"testnamefive"},{"count":"6","name":"testnamesix"},{"info":521}]
This is where i fill my array, before passing it to the JSONwrite method (this is inside a foreach loop):
$lists[]= [
"count"=>$count,
"name"=>$name
];
}
}
$lists[]= [
"info" => $number
];
Is there a way i can validate it now just like this so the decode won’t return null?
I have this code as a script, it uploads pics or videos flawlessly to WP media library.
<?php
$archivo = "/var/www/Digital_Signage/formulario/".$_GET["ruta"]; // Guardamos la ruta en la variable archivo
$username = 'gpda'; //usuario
$password = 'Pvry ZQ3N uypF 1AY6 876h yC8B'; // contraseña
$curl = curl_init(); //Inicia una nueva sesión del curl
$data = file_get_contents( $archivo );
curl_setopt_array($curl, array( // Dentro del curl_setopt se definen las opciones para nuestra sesión
CURLOPT_URL => "http://10.124.133.1:8182/wp-json/wp/v2/media/", //Define la URL de la petición HTTP
CURLOPT_RETURNTRANSFER => true, //Muestra el resultado del proceso (El contenido que devuelve la página se almacene en una variable)
CURLOPT_ENCODING => "", //se enviarán todos los tipos de condificación soportados
CURLOPT_MAXREDIRS => 10, //Número máximo de redirecciones HTTP a seguir.
CURLOPT_TIMEOUT => 30, //Número máximo de segundos permitido para ejectuar funciones cURL
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, // Versión HTTP
CURLOPT_CUSTOMREQUEST => "POST", // Método de petición
CURLOPT_HTTPHEADER => array( //Array de campos a configurar para el header HTTP
'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
"cache-control: no-cache",
'Content-Disposition: attachment; filename="'.basename($archivo).'"',
),
CURLOPT_POSTFIELDS => $data,
));
//Redireccionamos a peticiones.php
header('Location: peticiones.php');
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "No se ha podido insertar en la galeria de medios de WordPress!" . $err;
} else {
echo "Exito se ha insertado en la galeria de medios de WordPress!". $response;
}
?>
~
The problem comes when I try to upload multimedia bigger than 8Mb, I already set maximum_upload_file_size to +2000M as you can see here:
However, when I try to upload a video of 130Mb the script just gets stuck and does not work, any fix around?
This is my docker-compose.yml
version: '3.9'
networks:
bedrock:
services:
web:
container_name: kawa-web
image: nginx:stable-alpine
volumes:
- ./:/var/www/html:delegated
- ./docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
ports:
- 8080:80
depends_on:
- php
- mysql
networks:
- bedrock
php:
container_name: kawa-php
image: nanoninja/php-fpm:8.0
volumes:
- ./:/var/www/html
- ./docker/config/php.ini:/usr/local/etc/php/conf.d/php.ini
ports:
- 9000:9000
networks:
- bedrock
composer:
container_name: kawa-composer
build:
context: .
dockerfile: php.dockerfile
volumes:
- ./:/var/www/html
depends_on:
- php
- web
networks:
- bedrock
wp-cli:
container_name: kawa-wp-cli
build:
context: .
dockerfile: php.dockerfile
volumes:
- ./:/var/www/html
links:
- mysql
depends_on:
- php
- web
- mysql
environment:
- WP_CLI_ALLOW_ROOT=true
networks:
- bedrock
mysql:
container_name: kawa-db
image: mysql:8
volumes:
- ./docker/db:/var/lib/mysql:delegated
ports:
- 3306:3306
command: --default-authentication-plugin=mysql_native_password
environment:
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
networks:
- bedrock
phpmyadmin:
container_name: kawa-phpmyadmin
image: phpmyadmin/phpmyadmin
depends_on:
- mysql
volumes:
- ./config/phpmyadmin.ini:/usr/local/etc/php/conf.d/phpmyadmin.ini
ports:
- 8082:80
environment:
- PMA_HOST=mysql
- PMA_PORT=3306
networks:
- bedrock
node:
container_name: kawa-node
build:
context: .
dockerfile: node.dockerfile
volumes:
- ./:/var/www/html
networks:
- bedrock
Content of node.dockerfile
FROM node:18-alpine
WORKDIR /var/www/html
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
When I run docker compose up -d it shows
failed to solve: error from sender: open /path/to/project/docker/db/#innodb_temp: permission denied
How can I fix this? Or any another way to run nodejs inside PHP container maybe?
I want to turn on desktop notifications for my site.
Recently performed a small composer update on a Laravel project and started seeing errors such as this for some of our events. Exception is being thrown in predis (v1.1.10).
Any ideas why the responses aren’t returning one of the expected values (from the source code it looks like the prefix should be +, $, *, : or -)
// Some examples of the exceptions we get
Unknown response prefix: '"'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: '"'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: '0'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: '3'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: 'e'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: 'e'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: 'e'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Unknown response prefix: 'R'. [tcp://someurl-europe-west2.redis.production.internal:6379]
Stack trace
PredisProtocolProtocolException Unknown response prefix: '0'. [tcp://someurl-europe-west2.redis.production.internal:6379]
vendor/predis/predis/src/Connection/AbstractConnection.php:167 PredisConnectionAbstractConnection::onProtocolError
vendor/predis/predis/src/Connection/StreamConnection.php:370 PredisConnectionStreamConnection::read
vendor/predis/predis/src/Connection/AbstractConnection.php:120 PredisConnectionAbstractConnection::readResponse
vendor/predis/predis/src/Connection/AbstractConnection.php:112 PredisConnectionAbstractConnection::executeCommand
vendor/predis/predis/src/Connection/StreamConnection.php:260 PredisConnectionStreamConnection::connect
vendor/predis/predis/src/Connection/AbstractConnection.php:180 PredisConnectionAbstractConnection::getResource
vendor/predis/predis/src/Connection/StreamConnection.php:288 PredisConnectionStreamConnection::write
vendor/predis/predis/src/Connection/StreamConnection.php:394 PredisConnectionStreamConnection::writeRequest
vendor/predis/predis/src/Connection/AbstractConnection.php:110 PredisConnectionAbstractConnection::executeCommand
vendor/predis/predis/src/Client.php:331 PredisClient::executeCommand
vendor/predis/predis/src/Client.php:314 PredisClient::__call
vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php:116 IlluminateRedisConnectionsConnection::command
vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php:220 IlluminateRedisConnectionsConnection::__call
vendor/laravel/framework/src/Illuminate/Queue/RedisQueue.php:140 IlluminateQueueRedisQueue::pushRaw
vendor/laravel/horizon/src/RedisQueue.php:69 LaravelHorizonRedisQueue::pushRaw
vendor/laravel/horizon/src/RedisQueue.php:52 LaravelHorizonRedisQueue::LaravelHorizon{closure}
vendor/laravel/framework/src/Illuminate/Queue/Queue.php:317 IlluminateQueueQueue::enqueueUsing
vendor/laravel/horizon/src/RedisQueue.php:53 LaravelHorizonRedisQueue::push
vendor/laravel/framework/src/Illuminate/Queue/Queue.php:57 IlluminateQueueQueue::pushOn
vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastManager.php:133 IlluminateBroadcastingBroadcastManager::queue
vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:320 IlluminateEventsDispatcher::broadcastEvent
vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php:243 IlluminateEventsDispatcher::dispatch
vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:450 event
// Our application, dispatches events like so
event(OneOfOurEvents);
I am looking for a way to validate one array obtained via a form.
$arr = [13, 64];
The array is composed of 2 integers and I need to check that these integers are between 0 ad 1000, but also the 2nd integer is greater than the first AND the difference cannot exceed 100.
The only only constraint I could put was the one validating the number with a know pattern :
'constraints' => new AssertCollection([
'fields' => [
0 => new AssertRange([
'min' => 0,
'max' => 1000,
]),
1 => new AssertRange([
'min' => 0,
'max' => 1000,
]),
]
]),
What is missing in my validation:
$arr = [13, 64]; => should be correct
$arr = [140, 64]; => not correct, $arr[0] > $arr[1]
$arr = [13, 340]; => not correct, ($arr[1] - $arr[0]) > 100
I couldnt find in the symfony doc how to validate array fields among each others, and don’t event know if there is a way to.
If anyone has a tip, you’re welcome 🙂
thank you and cheers !
Here is my code;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies.json",
CURLOPT_HTTPHEADER => array(
"Content-Type: text/plain"
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, true);
foreach ($response as $code => $name ) {
$currency = new Currency();
$currency->currency_code = $code;
$currency->currency_name = $name;
$save = $currency->save();
}
If I dd($response), it returns all the arrays but when i use foreach loop, it will only save the first value of the array rather than all the values in the array.
This is a repost of the original question.