How can I add a IF EMPTY to PHP Snippet?

This snippet works very fine, catch de url parameter and show it in a shortcode, but I want to put a conditional if this parameter is empty: IF “NOMBRE” IS EMPTY, SHOW FOR EXAMPLE THE TEXT “¡HOLA MUNDO!”.

function custom_shortcode() {
        return '' . htmlspecialchars($_GET["nombre"]) . ''; 
} 
add_shortcode( 'nombre', 'custom_shortcode' );

I am facing problem while installing laravel package maatwebiste/excel in laravel 9 with php 8.0.3

Problem 1
– maatwebsite/excel[3.1.36, …, 3.1.x-dev] require phpoffice/phpspreadsheet ^1.18 -> satisfiable by phpoffice/phpspreadsheet[1.18.0, …, 1.23.0].
– maatwebsite/excel[3.1.0, …, 3.1.25] require php ^7.0 -> your php version (8.0.3) does not satisfy that requirement.
– maatwebsite/excel[3.1.26, …, 3.1.35] require illuminate/support 5.8.*|^6.0|^7.0|^8.0 -> found illuminate/support[v5.8.0, …, 5.8.x-dev, v6.0.0, …, 6.x-dev, v7.0.0, …, 7.x-dev, v8.0.0, …, 8.x-dev] but these were not loaded, likely because it conflicts with another require.
– phpoffice/phpspreadsheet[1.18.0, …, 1.23.0] require ext-gd * -> it is missing from your system. Install or enable PHP’s gd extension.
– Root composer.json requires maatwebsite/excel ^3.1 -> satisfiable by maatwebsite/excel[3.1.0, …, 3.1.x-dev].

To enable extensions, verify that they are enabled in your .ini files:
– C:xamppphpphp.ini
You can also run php --ini in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with --ignore-platform-req=ext-gd to temporarily ignore these required extensions.
You can also try re-running composer require with an explicit version constraint, e.g. “composer require maatwebsite/excel:*” to figure out if any version is installable, or “composer require maatwebsite/excel:^2.1” if you know which you need.

enter image description here

please help me

Best way to submit many same-record? [duplicate]

Project info

I’m developing a LAMP web app, to keep track of gym progress and programs.

A program is a group of sessions.
A session is a group of exercises you do in a specific day of the week (e.g. every Wednesday).

Situation

When a user adds an exercise to a session, he should be able to modify the exercise parameters in the different weeks (e.g. 1st week: 6 reps, 2nd week: 8 reps, 3rd week: 12 reps).

So I thought of a form like this: https://i.stack.imgur.com/3T8Vu.jpg

The exersice table in the DB has a nWeek column.

Problem

How do I differentiate for week the various same-records in the form, so that I can add them to the DB accordingly?

Thoughts

I thought I could add something like “_week1” to the name attribute of every input box while printing them, but I don’t really like this solution, because then I should parse through all of them.

Webchat updating when other user sends message

Im building a webchat using php and json. I know thats not the best solution but works for what im building.

So far users can send their messages and they get saved and displayed in the chat.

However the users need to manualy update the website to get new messages shown.

Is there anyway to detect file changes in php so that i can reload or rebuild the website.

Maybe checking the array length in the php file and then restarting the process again.

Can anybody please help me 🙂

jQuery clone for input type=”file”

Hi i am trying to clone a div with input tag of type-file i.e-

The div gets cloned but the image or file which i uploaded in the original input tag doesnt get copied to the cloned input tag…The cloned input tag displays the name of the file but when i save the form it’s not passed and is not saved

$(".imageblockbtn").click(function () {
    var langid = jQuery(this).attr("id");

    $(
      `#dynamic${langid}`
    ).append(`<div class="col-12 form-group qwer" id="imageblock">
                                                <label for="imageblock">Image Block</label>
                                                <input class="imageblock" type="file" accept="image/*" name="data[${langid}][imageblock${k}]"><span class="up"></span><span
                                                class="down"></span>
                                                <button type="button" class="btn remove-dyna"><i class="material-icons" style="font-size:18px;color:red">remove_circle</i></button>

                                                <div class="dropdown">
                                                        <a class="dropbtn">Duplicate</a>
                                                        <div class="dropdown-content image_dd">

                                                        <li id="1"><a href="javascript:void(0)">English</a> </li>
                                                        <li id="3"><a href="javascript:void(0)">Chineese</a></li>
                                                        <li id="9"><a href="javascript:void(0)">German</a></li>
                                                        <li id="10"><a href="javascript:void(0)">Italian</a></li>
                                                        <li id="4"><a href="javascript:void(0)">Korean</a></li>
                                                        <li id="5"><a href="javascript:void(0)">Japanese</a></li>
                                                        <li id="6"><a href="javascript:void(0)">Spanish</a></li>
                                                        <li id="11"><a href="javascript:void(0)">Russian</a></li>
                                                        <li id="7"><a href="javascript:void(0)">Ukranian</a></li>
                                                        <li id="8"><a href="javascript:void(0)">French</a></li>

                                            </div>
                                            </div>

                                            </div>`);
    ++k;

    $(".image_dd li").each(function (index, li) {
      var lid = $(li).attr("id");
      // console.log($(li).parents(".qwer"));
      $(li).unbind("click");
      $(li).on("click", function () {
        var clone = $(li).parents(".qwer").clone(true);

        clone
          .children("h1")
          .children("input")
          .attr("name", `data[${lid}][imageblock${k}]`);
        clone.insertAfter(`#dynamic${lid}`);
        ++k;
        alert("Duplicated");
      });
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

replace with tag in php

I want to replace p tag with div tag. if p tag has any attributes like id , class or style tag this attributes should be untouched. Just replace opening and closing ‘p’ tag with opening and closing ‘div’ tag.

e.g.

<p style="font-weight:600">2021 was tough for everyone, especially <span>people working</span> in the retail sector, so we want to start your <strong>2022</strong> with a bang!</p>

<p class="test">The <span style="font-size:18px;color:blue">team</span> would like to invite you to an evening with your peers in the industry to discuss all things retention marketing, CRM strategy, trends, campaigns and more.</p>

should be changed to:

<div style="font-weight:600">2021 was tough for everyone, especially <span>people working</span> in the retail sector, so we want to start your <strong>2022</strong> with a bang!</div>

<div class="test">The <span style="font-size:18px;color:blue">team</span> would like to invite you to an evening with your peers in the industry to discuss all things retention marketing, CRM strategy, trends, campaigns and more.</div>

How can i display second items drupal 9 for loop

for now only can get first and last item so how can i display a second items ? thank for your times

{% if content.field_story_sub_stories['#items']|length > 0 %}
    {% for story in content.field_story_sub_stories['#items']|first %}
        {{ drupal_entity('node', story.value , 'env_series_2022') }}
    {% endfor %}
{% endif %}

Video download api google drive, php javascripts

Good morning, I need a little special help.

I have a need with the google drive api, but I have no experience with it

I need to put on a website, a direct link to download files from google drive, that is, a button, that when pressed automatically starts the download if you leave the web.

The web application is based on php, html, and javascript

Can you help me a little to guide me? I’m very new to this api and I don’t understand it at all…

And I would like that you will not need oauth to authenticate, just the button to download

Thanks…

Deleting a model and all references to it in his relationships in Laravel

I’m still new to Laravel and Eloquent but joining on a project previously built.

I have a User model that have many relationships like for example Actions(HasMany), Roles(BelongsToMany), Type(BelongsTo),..and many others…

What I want to do is to delete an User model and it’s data and when I’m doing it, deleting all traces of him in his relations but not the content itself, basically I want to keep his relations models (Actions, Roles, Type,…) in my database but deleting his FK so that it cannot be linked to my user anymore while keeping the entry previously associated to him.

I tried a few things without success like

$user = User::findOrFail($id)
$user->delete();
// This one giving me a SQLSTATE[23000] The DELETE statement conflicted with the REFERENCE constraint 

$user->actions()->detach()
// or
$user->actions()->dissociate()
// But undefined for HasMany relations

and I was wondering if there was a “clean” and simple way to do it other than updating all those Foreign_Keys to a “NULL” value in each of the relationships

$user->userActions()->update(['id_user' => null]);
$user->userRoles()->update(['id_user' => null]);
//...and on and on... before being able to do a 
$user->delete();

I hope I was clear enough.

Thanks.

Session variable get lost after redirect

I have an issue with session variable getting lost upon redirecting user to a third party website and then getting back at me. I made a simpler version of the error to make it reproductible:

            if($request->getSession()->get('session_variable') == 'made'){
                //I do some stuff           
            }else{
                $request->getSession()->set('session_variable','made');

                $request->getSession()->save();
                //tried adding this but it doesnt change anything 

                $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                return $this->redirect($actual_link);
            }

So this piece of code should, In my understanding get in the else once, set the session variable and then get out of the loop.
The thing is that the code keeps on looping on the else loop forever

I get the request paramter from the webservice:

    public function myWebService(Request $request, $otherParam){
...

I’m using Symfony 6 and php 8

Strange fact that I can hardly understand: sometimes the problem will not happend. Same initial url

Wrong auth_type when trying to add event on bitrix24 REST-API

Array
(
    [error] => WRONG_AUTH_TYPE
    [error_description] => Current authorization type is denied for this method
)

i´m trying to create an event that triggers when a call starts and it should work for all users, not the ones with admin previleges but even i that have admin privileges get this error so i guess it does not have anything to do with it?
this is the error i get when i run my event handler, i´m new to this so i don´t actually know how the authorization works, i´ve read the documentation but haven´t reached any solutions yet.

handler.php:

<?php
require_once (__DIR__.'/crest.php');


class AuthSimple
{
    const AUTH_TYPE = 'demo_simple';

    const AUTH_PARAM_NAME = 'secret_word';
    const AUTH_PARAM_VALUE = 'MySuperSecurePassword123456';

    public static function onRestCheckAuth(array $query, $scope, &$res)
    {
        if(array_key_exists(static::AUTH_PARAM_NAME, $query))
        {
            $res = array('error' => 'INVALID_CREDENTIALS', 'error_description' => 'Invalid request credentials');

            return false;
        }

        return null;
    }
}

$data = file_get_contents('https://gotmink.bitrix24.com.br/rest/4755/uj3p50inofwg6eqm/');

echo '<PRE>';
$result = CRest::call(
    'event.bind',
    [
        'event' => 'OnVoximplantCallInit',
        'handler' => 'https://testebitrix24.herokuapp.com/handler.php',
        'auth_type' => '4755',
        'event_type' => 'online'
    ]
);
print_r($result);

echo '</PRE>';


?>

How to change `curl_multi_init` single thread to multi thread

Ask experts how to change to curl_multi_init multi-threaded?
My idea is to split the $data array into array_chunk($data, 15, true); and then do CURL, but I’m a novice, I don’t understand the examples on the Internet, please help

Simulate 100 pieces of data:

function post($url, $data = '', $head = 'application/x-www-form-urlencoded')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type:{$head};charset=utf-8;"));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_HEADER, 0);
    if (!empty($data)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

$url = 'http://localhost/test.php';
$res = [];

for ($i=0; $i < 100; $i++) { 
    $res[$key] = post($url, 'key='.$i);
}
var_dump($res);

The code below, I know it must be wrong, please correct me, thank you!!

$newData = array_chunk($data, 10, true);
foreach ($newData as $k=> $tmp) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type:application/x-www-form-urlencoded;charset=utf-8;"));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_HEADER, 0);

    $mh = curl_multi_init();
    foreach ($tmp as $key => $value) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $tmp);
        curl_multi_add_handle($mh, $ch);
    }
    $active = null;
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    $res[$k] = curl_multi_getcontent($ch);
    curl_multi_remove_handle($mh, $ch);
    curl_multi_close($mh);
}

标签:
php-analytics-data

答案(无需填写):
There were several issues in your original code, which were fixed in the code above.

  1. Each $ch should be an independent handle, not a common one
  2. curl_multi_getcontent should be called on each $ch handle, you are equivalent to only calling the last $ch of each group.
  3. curl_multi_remove_handle should be called on each $ch handle. It is more appropriate to call it after the previous curl_multi_getcontent.
$newData = array_chunk($data, 10, true);
foreach ($newData as $k => $tmp) {
    $mh = curl_multi_init();
    $chs = [];
    foreach ($tmp as $key => $url) {
        $ch = curl_init();
        $chs[$key] = $ch;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded;charset=utf-8;'));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $tmp);
        curl_multi_add_handle($mh, $ch);
    }
    $active = null;
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    foreach ($chs as $key => $ch) {
        $res[$k][$key] = curl_multi_getcontent($ch);
        curl_multi_remove_handle($mh, $ch);
    }

    curl_multi_close($mh);
}


var_dump($res);

How to display message in HTML Tag with PHP in a function

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>