amazon web services – How to stop requests on PHP server while it is running cron job sheduled PHP script?

I have a situation when some DDOS attacks are putting my PHP server down. Occasionally.

I’m using AWS with auto scaling groups, so it is not a problem.

The problems start when this server is going down in the middle of the cron job scheduled PHP script.

So my idea was to block all of the routs on the PHP servers except for the /healthcheck

How can I do that and is there a better solution?

php – Order custom post type is beign ignored

I have a custom post type “car”. I’ve created a loop to show all the titles of that post type. I want to show them alphabetically. But the order is ignored.

<?php
$loop = new WP_Query( array(
    'post_type' => 'car',
    'orderby' => 'title',
    'order' => 'DESC'
)
);
while ( $loop->have_posts() ) : $loop->the_post();

the_title();

endwhile; wp_reset_query(); 
?>

The order output is the same order of the input. So I’ve added Volkswagen Tiguan first, so that is shown first and not Audi A1 (for example).

How do I write non-English text on image using php

How do I write non-English text on image using php

Here’s my situation.
Mobile users have an option to switch their keyboards to a different language.
Some users might be using a chinese language keyboard, some might use Italian, some might use Indian hindi, or Indian Bengali etc etc.
Most are using default English keyboard.

Now I want to take the text they entered and put it on an image, as caption.
I know how to do this with English text.
That is no problem.

How do I do it if they are using some other language?
Is there a global font file I can use?
SEMrush

If not, where can I download those language font files which these devices are using?
And most important, how do I find out which language they typed in?

Any help is greatly appreciated.

 

dynamic php menu with hidden sub-categories only showing when the category name is clicked

This is for a wordpress store and I want to show the categories names automatically, but with the sub-categories hidden, the code below works perfectly with the hover effect, now I wish to have the click effect instead. The $cats variable is to use the get_terms() function, but for here to work everywhere I had included a few categories, the categories only go so far as the “third generation”.

<?php $cats = array(array('first', 'sub-first', 'sub-sub-first'),
                    array('second', 'sub-second'),
                    array('third', 'sub-third', 'sub-sub-third')); ?>
<h3>Categories</h1>
<ul class="ul1"> <?php
  foreach($cats as $cat):
    if (isset($cat(0))): ?>
      <li class="li1" onclick="test()"><a href="#"><?php echo $cat(0) ?></a> <?php
        if (isset($cat(1))):?>
          <ul class="ul2">
            <li class="li2"><a href="#"><?php echo $cat(1) ?></a> <?php
              if (isset($cat(2))):?>
                <ul class="ul3">
                  <li class="li3"><a href="#"><?php echo $cat(2) ?></a> </li>
                </ul> <?php
              endif; ?>
            </li>
          </ul> <?php
        endif; ?>
      </li> <?php
    endif;
  endforeach; ?>
</ul>

<style media="screen">
  ul{
    list-style: none;
  }
  a{
    text-decoration: none;
    color:#fff;
  }
  a:hover{
    color:#EF7522;
  }
  .li1{
    background:#1B2332;
    width:200px;
    border:1px solid lightgreen;
    padding:10px;
  }
  .ul2, .ul3{
    display:none;
  }
  .li1:hover .ul2{
    display:block;
  }
  .ul2:hover .ul3{
    display:block;
  }
</style>

for the click effect I had remove from the style the last two hover effects and add the javascript function test();

<script type="text/javascript">
    function test(){
        $(".ul2").css({
            "display":"block"
        });
    } 
</script>

What is happening is that I click a category and all sub-categories are showing, What I wanted is the same as the hover effect, that if I click the first category, I have only the sub-categories of that category and so on.

If someone could help me, I have been twisting my mind over this for a few days already!

C# Convert.FromBase64String retorna diferente de PHP base64_decode

Estou fazendo o decode em c# de um base64 para poder gerar um qrcode, em PHP funciona normal mas, em c# o retorno do decode fica diferente.
Código PHP funcionando:

<?php  
include('C:phplibphpqrcodeqrlib.php');
    $file = 'D:Testeqrcode.png';
    $a = base64_decode('X0gJQwUAEQBGMEQCIFFztpz6Yi2OHOR9QafHjL4y8MtlwHG7fgE9q9KycCBXAiBlU+xqMnYHBdpArpgxZee/PvsqO5BmEyvAdqSFtLzCNgAAAAxJBBhFVBJBlhBVlAA=');
    QRcode::png($a, $file,  QR_ECLEVEL_M, 3, 1);
?>

Código em c# com o decode diferente

string stringBase64Endode = "X0gJQwUAEQBGMEQCIFFztpz6Yi2OHOR9QafHjL4y8MtlwHG7fgE9q9KycCBXAiBlU+xqMnYHBdpArpgxZee/PvsqO5BmEyvAdqSFtLzCNgAAAAxJBBhFVBJBlhBVlAA=";
string textoDecode = Encoding.UTF8.GetString(Convert.FromBase64String(stringBase64Endode));

var qrCode = new QRCodeEncoder();
qrCode.QRCodeBackgroundColor = Color.White;
qrCode.QRCodeForegroundColor = Color.Black;
qrCode.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCode.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
qrCode.QRCodeScale = 2;
var resultado = qrCode.Encode(textoDecode);
resultado.Save("D:Testeqrcode.png");

Como faço para que o Encoding.UTF8.GetString(Convert.FromBase64String()) em c# retorne o mesmo resultado que o base64_decode em php?

php – Problema carga modal

Llevo tiempo con un problema en una de las páginas de mi aplicación web.. resulta que todo viene por el tema de los modal.. Tengo 3 llamadas, una para dar de alta un registro, otra para editar y otra para eliminar registro. Toqueteando el código hoy me he dado cuenta que la página carga con data-whatever en el button de añadir registro.

<button type="button" class="btn btn-theme btn--icon" data-toggle="modal" title="Add lesson" data-target="#addModal" data-whatever="Edit lesson"><i class="zwicon-plus"></i></button>

<button type="button" class="btn btn-theme btn--icon" title="Edit lesson" data-toggle="modal" data-target="#editModal"
data-whatever="Edit lesson"
data-id="<?php echo $id;?>" 
data-id2="<?php echo $row('class_name');?>" 
data-id3="<?php echo $estudiante; ?>" 
><i class="zwicon-edit-pencil"></i>
</button>
&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-theme btn--icon" data-toggle="modal" title="Delete lesson" data-target="#deleteModal"
data-whatever="Delete lesson"
data-id="<?php echo $id;?>"
data-id2="<?php echo $row('teacher_id');?>"
>
<i class="zwicon-trash"></i>
</button>

Los modal los llamo así:

<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

Y el script:

$('#addModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  var modal = $(this)
  modal.find('.modal-title').text('Operation: ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

$('#editModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  var recipient1 = button.data('whatever1')
  var recipient2 = button.data('whatever2')
  var recipient3 = button.data('whatever3')
  var modal = $(this)
  modal.find('.modal-title').text(recipient)
  modal.find('.modal-body input').val(recipient)
})

$('#deleteModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  var id_lesson = button.data('id')
  var modal = $(this)
  modal.find('.modal-title').text(recipient)
  modal.find('.modal-body input').val(recipient)
  modal.find('.modal-body #id_lesson').val(id_lesson)
  //modal.find('.modal-body input').val(id_lesson)
})

php – Campo não retorna a lista de registros em formulário de exclusão

Meu formulário de exclusão deveria retornar um <select> com todos os registros encontrados no banco, só que isso não acontece e a tela do formulário fica assim.

inserir a descrição da imagem aqui

São dois códigos:

<!DOCTYPE html>
<html>
<head>
    <title> Formulário de exclusão cliente </title>
</head>
<body>
    <form method="POST" action="../aula2/delete.php">
        <p> ID cliente:
            <select name="cd_cliente" required="">
                <option value=""> </option>
                <?php
                    foreach ($resultado_selecao as $valor) {
                        echo "<option value='{$valor('cd_cliente')}'>{$valor('nome')}</option>";
                    }
                ?>
            </select>
        </p>
        <p> <input type="submit" name="Eliminar" value="Eliminar"> </p>
    </form>
    <?php
        
        require_once(__DIR__. '/conexao/conexao.php'); 
        
        try {
            
            $selecao = "SELECT * FROM cliente";
            $seleciona_dados = $conexao->prepare($selecao);
            $seleciona_dados->execute();
            $linhas = $seleciona_dados->fetchAll(PDO::FETCH_ASSOC);
        
        } catch (PDOException $falha_selecao) {
            echo "A listagem de dados não foi feita".$falha_selecao->getMessage();
            die;
        } catch (Exception $falha) {
            echo "Erro não característico do PDO".$falha->getMessage();
            die;
        }
    ?>
    <table border="1">
        <tr> <th> ID <th> Nome <th> Endereço <th> Ações </tr>
        <?php 
            
            foreach ($linhas as $exibir_colunas){
                echo '<tr>';
                echo '<td>'.$exibir_colunas('cd_cliente').'</td>';
                echo '<td>'.$exibir_colunas('nome').'</td>';
                echo '<td>'.$exibir_colunas('endereco').'</td>';
                echo '<td>'."<a href='form_insert.php'>INSERT</a> ".
                "<a href='select.php'>SELECT</a> ".
                "<a href='form_update.php'>UPDATE</a> ".
                "<a href='form_delete.php'>DELETE</a>".'</td>';
                echo '</tr>'; echo '</p>';
            }
        ?>
    </table>   
</body>
</html>
<!DOCTYPE html>
<html>
<head> 
    <title> Remover cliente </title> 
</head>
<body> 
    <?php
        
        require_once(__DIR__. '/conexao/conexao.php'); 
        
        if(isset($_POST('Deletar'))){
            
            $cd_cliente = $_POST('cd_cliente');
            
            try {
                
                $remove = "DELETE FROM cliente WHERE cd_cliente = :cd_cliente";
                $remocao = $conexao->prepare($remove);
                $remocao->bindValue(':cd_cliente',$cd_cliente);
                $remocao->execute();
            
            } catch (PDOException $falha_remocao) {
                echo "A remoção não foi feita".$falha_remocao->getMessage();
                die;
            } catch (Exception $falha) {
                echo "Erro não característico do PDO".$falha->getMessage();
                die;
            }
        }
        // Query que seleciona chave e nome do cliente
        $seleciona_nomes = $conexao->query("SELECT cd_cliente, nome FROM cliente");
        // Resulta em uma matriz
        $resultado_selecao = $seleciona_nomes->fetchAll();  
    ?>
    <?php
        
        try {
            
            $selecao = "SELECT * FROM cliente";
            $seleciona_dados = $conexao->prepare($selecao);
            $seleciona_dados->execute();
            $linhas = $seleciona_dados->fetchAll(PDO::FETCH_ASSOC);
        
        } catch (PDOException $falha_selecao) {
            echo "A listagem de dados não foi feita".$falha_selecao->getMessage();
            die;
        } catch (Exception $falha) {
            echo "Erro não característico do PDO".$falha->getMessage();
            die;
        }
    ?>
    <table border="1">
        <tr> <th> ID <th> Nome <th> Endereço <th> Ações </tr>
        <?php 
            
            foreach ($linhas as $exibir_colunas){
                echo '<tr>';
                echo '<td>'.$exibir_colunas('cd_cliente').'</td>';
                echo '<td>'.$exibir_colunas('nome').'</td>';
                echo '<td>'.$exibir_colunas('endereco').'</td>';
                echo '<td>'."<a href='form_insert.php'>INSERT</a> ".
                "<a href='select.php'>SELECT</a> ".
                "<a href='form_update.php'>UPDATE</a> ".
                "<a href='form_delete.php'>DELETE</a>".'</td>';
                echo '</tr>'; echo '</p>';
            }
        ?>
    </table>   
</body> 
</html> 

php – ¿Como puedo relacionar 2 tablas en 1?

Me encuentro realizando un practica de un pequeño blog con php y sql y necesito relacionar 2 tablas de mi base de datos, por ejemplo que al crear una nueva publicación de mi blog se muestren la ID de la publicación y las ID’S de las categorías seleccionadas en otra tabla para almacenar esa información

Estas son las 3 tablas que tengo creadas, en POSTS se almacena todos los datos de las publicaciones y en CATEGORIAS se almacena todos los datos de las categorias.

introducir la descripción de la imagen aquí

TABLA: POST

introducir la descripción de la imagen aquí

TABLA: CATEGORIAS

introducir la descripción de la imagen aquí

Como puedo hacer que en post_category se almacenen como ya dije las ID de las publicaciones y las ID’S de las categorías seleccionadas. Como por ejemplo en este caso la publicación “El oceano” tiene de categoria “naturaleza”.

Ejemplo de la tabla post_category

introducir la descripción de la imagen aquí

post_id = (ID del post = El oceano)

categoria_id = (ID de la categoría = Naturaleza)

CODIGO: db.php

<?php

session_start();
require('connect.php');

function dd($value)
{
    echo "<pre>", print_r($value, true), "</pre>";
    die();
}


function executeQuery($sql, $data)
{
    global $conn;
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $stmt = $conn->prepare($sql);
    $values = array_values($data);
    $types = str_repeat('s', count($values));
    $stmt->bind_param($types, ...$values);
    $stmt->execute();
    return $stmt;
}


function selectAll($table, $conditions = ())
{
    global $conn;
    $sql = "SELECT * FROM $table";
    if (empty($conditions)) {
        $sql = $sql . " ORDER BY id DESC";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
        $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        return $records;    
    } else {
        // $sql = "SELECT * FROM $table";
        
        $i = 0;
        foreach ($conditions as $key => $value) {
            if ($i === 0){
                $sql = $sql . " WHERE $key=?";
                
            } else {
                $sql = $sql . " AND $key=?"; 
            }
            $i++;
        }
        
        $stmt = $conn->prepare($sql);
        $values = array_values($conditions);
        $types = str_repeat('s', count($values));
        $stmt->bind_param($types, $values);
        $stmt->execute();
        $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        return $records;
    }
}



function selectOne($table, $conditions)
{
    global $conn;
    $sql = "SELECT * FROM $table ";

        $i = 0;
                foreach ($conditions as $key => $value) {
            if ($i === 0){
                $sql = $sql . " WHERE $key=?";
                
            } else {
               $sql = $sql . " AND $key=?"; 
            }
            $i++;
        }
        $sql = $sql . " LIMIT 1";
        $stmt = executeQuery($sql, $conditions);
        $records = $stmt->get_result()->fetch_assoc();
        return $records;
    }

function create($table, $data)
{
    global $conn;
    $sql = "INSERT INTO $table SET ";
      
    $i = 0;
    foreach ($data as $key => $value) {
            if ($i === 0){
                $sql = $sql . " $key=?";
                
            } else {
                $sql = $sql . ", $key=?"; 
            }
            $i++;
        }
    $stmt = executeQuery($sql, $data);
    $id = $stmt->insert_id;
    return $id;
    
}

function update($table, $id, $data)
{
    global $conn;
    $sql = "UPDATE $table SET ";
      
    $i = 0;
    foreach ($data as $key => $value) {
            if ($i === 0){
                $sql = $sql . " $key=?";
                
            } else {
                $sql = $sql . ", $key=?"; 
            }
            $i++;
        }
    
    $sql = $sql . " WHERE id=?";
    $data('id') = $id;
    $stmt = executeQuery($sql, $data);
    return $stmt->affected_rows;
    
}


function delete($table, $id)
{
    global $conn;
    $sql = "DELETE FROM $table WHERE id=?";
      
    $stmt = executeQuery($sql, ('id' => $id));
    return $stmt->affected_rows;
    
}

CODIGO: posts.php

<?php 

include($_SERVER('DOCUMENT_ROOT').'/app/database/db.php');
include($_SERVER('DOCUMENT_ROOT').'/app/helpers/validatePost.php');

$table = 'posts';
$categorias = selectAll('categorias');

$errors = array();
$id = '';
$title = '';
$body = '';
$topic_id = '';

$posts = selectAll($table);

    
    if (!empty($_FILES('image')('name'))) {
        $image_name = time() . '_' . $_FILES('image')('name');
        $destination = "../../images/" . $image_name;
        
        $result = move_uploaded_file($_FILES('image')('tmp_name'), $destination);
        
        if ($result){
            $_POST('image') = $image_name;
        } else {
            array_push($errors, "¡Algo fallo al subir la imagen!");
        }
        
        
    } else {
      array_push($errors, "¡Necesitas subir una imagen!");
    }
    
    if (count($errors) === 0){
        unset($_POST('add-post'));
        $post_id = create($table, $_POST);
        $_SESSION('message') = '¡Anime creado correctamente!';
        $_SESSION('type') = 'success';
        header('location: ../../admin/posts/index.php');
        exit();
    } else {
        $title = $_POST('title');
        $body = $_POST('body');
        $categoria = $_POST('')

    }


if (isset($_GET('id'))){
    $id = $_GET('id');
    $post = selectOne($table, ('id' => $id));
}

if (isset($_GET('del_id'))){
    $id = $_GET('del_id');    
    $count = delete($table, $id);
    $_SESSION('message') = '¡Anime eliminado correctamente!';
    $_SESSION('type') = 'success';
    header('location: ../../admin/posts/index.php');
    exit();
}

if (isset($_POST('update-post'))){
    $errors = validateEdit($_POST); 
    
    if (count($errors) === 0){
        $id = $_POST('id');
        unset($_POST('update-post'), $_POST('id'));
        $post_id = update($table, $id, $_POST);
        $_SESSION('message') = '¡Anime actualizado correctamente!';
        $_SESSION('type') = 'success';
        header('location: ../../admin/topics/index.php');
        exit();        
    } else {
        $id = $_POST('id');
        $title = $_POST('title');
        $body = $_POST('body');

}
} 
?>      

               

CODIGO: categorias.php

<?php 

include($_SERVER('DOCUMENT_ROOT').'/app/database/db.php');
include($_SERVER('DOCUMENT_ROOT').'/app/helpers/validateCategoria.php');

$table = 'categorias';

$errors = array();
$id = '';
$name = '';
$body = '';
$topic_id = '';

$categorias = selectAll($table);


if (isset($_POST('add-post'))) {
    $errors = validateCategoria($_POST);
    
    if (count($errors) === 0){
        unset($_POST('add-post'));
        $post_id = create($table, $_POST);
        $_SESSION('message') = '¡Categoria creada correctamente!';
        $_SESSION('type') = 'success';
        header('location: ../../admin/categorias/index.php');
        exit();
    } else {
        $name = $_POST('name');

    }
}

if (isset($_GET('id'))){
    $id = $_GET('id');
    $post = selectOne($table, ('id' => $id));
}

if (isset($_GET('del_id'))){
    $id = $_GET('del_id');    
    $count = delete($table, $id);
    $_SESSION('message') = '¡Categoria eliminada correctamente!';
    $_SESSION('type') = 'success';
    header('location: ../../admin/categorias/index.php');
    exit();
}

if (isset($_POST('update-post'))){
    $errors = validateEdit($_POST); 
    
    if (count($errors) === 0){
        $id = $_POST('id');
        unset($_POST('update-post'), $_POST('id'));
        $post_id = update($table, $id, $_POST);
        $_SESSION('message') = '¡Categoria actualizada correctamente!';
        $_SESSION('type') = 'success';
        header('location: ../../admin/categorias/index.php');
        exit();        
    } else {
        $id = $_POST('id');
        $name = $_POST('name');

}
} 
?>          

                            

html – PHP – Caixa de seleção não retorna registros em formulário de exclusão

Tenho dois arquivos:

  1. Arquivo de formulário de exclusão de cliente.
<!DOCTYPE html>
<html>
<head>
    <title> Formulário de exclusão cliente </title>
</head>
<body>
    <form method="POST" action="../aula2/delete.php">
        <p> ID cliente:
            <select name="cd_cliente" required="">
                <option value=""> </option>
                <?php
                    foreach ($resultado_selecao as $valor) {
                        echo "<option value='{$valor('cd_cliente')}'>{$valor('nome')}</option>";
                    }
                ?>
            </select>
        </p>
        <p> <input type="submit" name="Eliminar" value="Eliminar"> </p>
    </form>
</body>
</html>
  1. Arquivo php que faz a exclusão do cliente.
<!DOCTYPE html>
<html>
<head> 
    <title> Registro de clientes </title> 
</head>
<body> 
    <?php

        require_once(__DIR__. '/conexao/conexao.php'); 

        if(isset($_POST('Deletar'))){

            $cd_cliente = $_POST('cd_cliente');

            try {

                $remove = "DELETE FROM cliente WHERE cd_cliente = :cd_cliente";
                $remocao = $conexao->prepare($remove);
                $remocao->bindValue(':cd_cliente',$cd_cliente);
                $remocao->execute();

            } catch (PDOException $falha_remocao) {
                echo "A remoção não foi feita".$falha_remocao->getMessage();
                die;
            } catch (Exception $falha) {
                echo "Erro não característico do PDO".$falha->getMessage();
                die;
            }
        }
        // Query que seleciona chave e nome do cliente
        $seleciona_nomes = $conexao->query("SELECT cd_cliente, nome FROM cliente");
        // Resulta em uma matriz
        $resultado_selecao = $seleciona_nomes->fetchAll();  
    ?>
    <?php
        try {
            $selecao = "SELECT * FROM cliente";
            $seleciona_dados = $conexao->prepare($selecao);
            $seleciona_dados->execute();
            $linhas = $seleciona_dados->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $falha_selecao) {
            echo "A listagem de dados não foi feita".$falha_selecao->getMessage();
            die;
        } catch (Exception $falha) {
            echo "Erro não característico do PDO".$falha->getMessage();
            die;
        }
    ?>
    <table border="1">
        <tr> <th> ID <th> Nome <th> Endereço <th> Ações </tr>
        <?php 
            foreach ($linhas as $exibir_colunas){
                echo '<tr>';
                echo '<td>'.$exibir_colunas('cd_cliente').'</td>';
                echo '<td>'.$exibir_colunas('nome').'</td>';
                echo '<td>'.$exibir_colunas('endereco').'</td>';
                echo '<td>'."<a href='form_insert.php'>INSERT</a> ".
                "<a href='select.php'>SELECT</a> ".
                "<a href='form_update.php'>UPDATE</a> ".
                "<a href='form_delete.php'>DELETE</a>".'</td>';
                echo '</tr>'; echo '</p>';
            }
        ?>
    </table>   
</body> 
</html> 

O problema disso tudo é que no formulário não retorna o <select> com todas as chaves dos registros.

inserir a descrição da imagem aqui

php – Include Once Error

Getting Error on Website:

Warning: include_once(/home/awesomere/public_html/hawaiiflatfee/wp-includes/header.php): failed to open stream: No such file or directory in /home/awesomere/public_html/hawaiiflatfee/wp-content/themes/alchem/functions.php on line 2

Warning: include_once(): Failed opening ‘/home/awesomere/public_html/hawaiiflatfee/wp-includes/header.php’ for inclusion (include_path=’.:/opt/alt/php73/usr/share/pear’) in /home/awesomere/public_html/hawaiiflatfee/wp-content/themes/alchem/functions.php on line 2

Functions.php Line 2 is: include_once(ABSPATH . WPINC . ‘/header.php’);

Any suggestions?