running tinker laravel from .bat file windows

I’m using Laravel tinker to run my script

use SpatieBrowsershotBrowsershot;
$namafile = 'foto.jpeg';
$selectorIndex = '0';
$path = storage_path().'/app/'.$namafile;
Browsershot::url('http://127.0.0.1:8000/ds_rev_daily_l2')->select('.print', $selectorIndex)->setDelay(20000)->save($path);

I want to run script above with CMD Commands After Batch Script.
How can the script run from single click at .bat file?
Running the script from tinker from CMD Commands After Batch Script

Why im i getting that error when i want to migrate tables? [closed]

1

vendorlaravelframeworksrcIlluminateDatabaseConnectorsConnector.php:65
PDOException::(“SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: YES)”)

2

vendorlaravelframeworksrcIlluminateDatabaseConnectorsConnector.php:65
PDO::__construct(“mysql:host=localhost;port=3306;dbname=exam-app”,
“root”, “1234”, [])

How to make HTTP request among dockerized Nginx containers?

Let there be two microservices A and B built on Laravel, each with nginx, PHP, and MySQL containers. The nginx of A (on port 8001) and B (on port 8002) are connected via an external network common_network. The nginx, PHP, and MySQL of A are connected through network_A, and similar services of B are connected through network_B.

The ping of nginx B and MySQL and PHP of A inside the nginx container of A returns a response and everything is OK.

I need to make an HTTP request from microservice A to B. From what I googled, it can be done via a reverse proxy, but I would like to know how I can do that. I am new to Nginx.

Thanks in advance.

Trying to download the stream gives a file with content of “Resource id #xxx”

I’m using Laravel, and am trying to export items in my database to a CSV file. I am getting pretty close. Unfortunately, I get an output of Process id #xxx in the downloaded file.

This is a more minimal and anonymous example of the code I’ve been using.

public function exportCSV(): StreamedResponse
{
    $keys = ['id', 'title'];
    $posts = Post::select($keys)->get();

    $stream = fopen('php://memory', 'w+');
    fputs($stream, "sep=,n"); // Excel will be nice
    fputcsv($stream, $keys);

    foreach ($posts->toArray() as $post) fputcsv($stream, $post);

    rewind($stream);

    // dd(stream_get_contents($stream)) gives the expected result here
    return response()->streamDownload(function () use ($stream) {
        echo $stream;
    }, 'export.csv');
}

Phalcon PHP – Token not being read from Authorization Header in Postman

I have a Phalcon PHP application where I’m trying to implement token-based authentication. I have a method in my code like this:

public function infoAction()
{
$access_token = $this->request->getHeader('Authorization');
if (!$this->isLoggedIn($access_token)) {
return $this->unauthorized();
}
return $this->response->setJsonContent($this->getUserInfo());
}

When I register, I receive a token like this:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyNTZ9.v0cXrqoDEix-xCSVa8aFzNvyLW1monPv0lsaB8cj0Rc

Now, I want to test the infoAction method in Postman. I’m adding the token I received during registration to the “Authorization” header in Postman with the key “Authorization,” and I set the value to the token. However, after sending the request, it seems like the token parameters are not being read, and I’m not getting the expected result.

enter image description here

I’m looking for guidance on how to properly send and read the token in the “Authorization” header using Postman with my Phalcon PHP application.

enter image description here

I even tried to put that token as Bearer token in the Authorization section, but the problem was still not solved

When using Symfony Forms, how to render inputs for one entity type but with multiple input types

I am having a hard time making a form to edit a already existing subset of the Entity “Setting”.
The idea is to render only a determined collection of “Settings” in one template, each with his custom input type, at least on template level changing the widget.

The Setting Entity looks like this:

AppEntitySetting.php

<?php

namespace AppEntity;

use AppRepositorySettingRepository;
use DoctrineDBALTypesTypes;
use DoctrineORMMapping as ORM;
use SymfonyComponentUidUlid;

#[ORMEntity(repositoryClass: SettingRepository::class)]
class Setting
{
    #[ORMId]
    #[ORMColumn(type: 'ulid', unique: true)]
    #[ORMGeneratedValue(strategy: 'CUSTOM')]
    #[ORMCustomIdGenerator(class: 'doctrine.ulid_generator')]
    private ?Ulid $id = null;

    #[ORMColumn(length: 255)]
    private ?string $name = null;

    #[ORMColumn(length: 255)]
    private ?string $slug = null;

    #[ORMColumn(type: Types::TEXT, nullable: true)]
    private ?string $value = null;

    public function getId(): ?Ulid
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getValue(): ?string
    {
        return $this->value;
    }

    public function setValue(?string $value): self
    {
        $this->value = $value;

        return $this;
    }
}

The Form Type:

AppFormSettingGeneralType.php

<?php

namespace AppForm;

use AppEntitySetting;
use AppFormSettingType;
use DoctrineORMEntityRepository;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeCollectionType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class SettingGeneralType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name')
            ->add('value')
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Setting::class,
        ]);
    }
}

For the “Set” that needs to be in the form i could give following data:

id name value slug
App name AppName app_name
App logo NULL app_logo
App description NULL app_description
Maintenance mode false app_maintenance
Default date and time format d.m.Y H:i app_datetime_format
PHP bin path pathToPhp.bin app_php_bin_path
Default color mode auto app_theme_default

The value types vary between string,choice (Dropdowns),boolean (checkboxes).

I would have no problem in formatting the different form widgets manually in the template to fit the required value, but i can’t find any solution to how to render only a little collection each with his own “input” from this entity.

My only idea was using the “CollectionType” since it can render a set of simple forms i can render in the template and handle on submit, but i could not get it to filter entites that i wanted be rendered in those forms since i dont want every setting to be rendered…

This is my first question, so no hate if i missed something please 🙂

Symfony 6.3 / Post Request with MapRequestPayload

Sorry for my English, I hope you can understand my request.

I would like to use the MapRequestPayload attribute to create an entity from the POST request data.
I then validate this and then save it.
This works very well so far, but how do you deal with data from a select?

{
    "name": "test",
    "firstname": "test",
    "company_id": 486
}

compay_id is a select in a frontend.

This is of course ignored when assigning, which is ok because it shouldn’t be created, but the relationship should be saved.

My approach would now be the following, but it doesn’t work because the MapEntity attribute refers to the Request Query.

    public function add(
        #[MapRequestPayload] Person $person,
        #[MapEntity(id: 'company_id')] Company $company
    ): JsonResponse
    {
        $person->setCompany($company);
    }

Do you know a way to do that?

phpstan array shape definition using a class constant

Is there a way to use class constants to define array shapes in phpstan?

The purpose is to enable the definition to be used by PHP code, otherwise we have to repeat the definition (once for phpstan and once for PHP) and that feels wrong!

For example, we have:

/**
 * @phpstan-type BarArrayShape = array{
 *     abc => string,
 *     def => string,
 *     ghi => int,
 *     jkl => DateTime,
 * }
 */
class Foo
{
    private const ARRAY_SHAPE_BAR = [
        'abc' => 'string',
        'def' => 'string',
        'ghi' => 'int',
        'jkl' => 'DateTime',
    ];

    /**
     * @param BarArrayShape $dataArray
     * @return void
     */
    public function doSomething(array $bar): void
    {
        $expectedKeys = array_keys(self::ARRAY_SHAPE_BAR);
        foreach ($expectedKeys as $key) {
            ...
        }
    }
}

We used to use PHP Storm ArrayShape attributes (which worked fine) but trying to migrate to phpstan instead.

E.g. used to be able to do something like this:

    public function doSomething(#[ArrayShape(self::ARRAY_SHAPE_BAR)] array $bar) {}

Is there a way to do the same in phpstan?

I’ve tried doing:

@phpstan-type BarArrayShape = self::ARRAY_SHAPE_BAR. It works for the array keys, but the syntax is wrong, so it thinks that ‘int’ is a literal string which says ‘int’, and not an integer type definition.

Is there a solution?

Call AJAX to populate form fields from mysql database when an input is given

I have made form in which I want to give the ID of an order in a specific field and AJAX will fetch data from database and autofill the remaining fields as per database info.

Here is my FORM –

<form name="confirm_order_entry_form" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
      
      <div class="form_data">
         <label>Projection Code :</label>
         <input type="text" name="projection_code" onchange="projection_code_data_fetch(this.value)">
      </div>
      <div class="form_data">
         <label>Marketing By :</label>
         <input type="text" name="c_marketing_person" id="marketingPerson">
      </div>
      <div class="form_data">
         <label>Factory Name :</label>
         <input type="text" name="c_factory_name" id="factoryName">
      </div>
      <input type="submit" value="submit" name="submit">
</form>

Here is my javascript function –

function projection_code_data_fetch(input_data){

    if (input_data==""){
        return;
    }
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var data = JSON.parse(xmlhttp.responseText);
            for(var i=0;i<data.length;i++){
              document.getElementById("marketingPerson").value = data[i].name;
              document.getElementById("factoryName").value = data[i].factory;
            }
        }
    }

    xmlhttp.open("GET","formUp.php?q="+input_data,true);
    xmlhttp.send();

}

And here is formUp file –

<?php

$servername='localhost';
$username='root';
$password='';
$dbname = "xcel-erp";
$conn=mysqli_connect($servername,$username,$password,"$dbname");

if(!$conn){
    die('Could not Connect MySql Server:' .mysql_error());
}

$q = intval($_GET['q']);

$sql="SELECT * FROM projectiondatabase WHERE System_ID = '".$q."'";

$result = mysqli_query($conn,$sql);
$info = array();
while($row = mysqli_fetch_array($result)){
    $cMarketingPerson = $row['MarketingPerson'];
    $cFactoryName = $row['FactoryName'];
    $info[] = array( 'name' => $cMarketingPerson, 'factory' => $cFactoryName);
}
echo json_encode($info);

?>

I have run the javascipt & formUp file individually. Both are running fine. But the actual output is not coming when combined.

Please help!

I want to add a widget to my site as follows:

I want to add a widget to my site as follows:

<script src="https://widgets.coingecko.com/coingecko-coin-price-marquee-widget.js"></script>
      <coingecko-coin-price-marquee-widget coin-ids="bitcoin,ethereum,eos,ripple,litecoin" Currency = USD
                                           background-color="#ffffff" locale="en"></coinecko-coin-price-marquee-widget>

My site is written using LiveWire and is a full component
Now the problem is that I want to put the widget in one of these components and display it, but I can’t!

But it runs without problems in the plan
where is the problem from

Error 404.0 on IIS 10.0, but file exist in IIS directory

I have installed IIS 10.0 on an Windows Server 2019 Datacenter. To use PHP-Files I have installed PHP over CGI and its works great. All php files working without an error. But when I go to “…/task/php/sql_task_success.php”

Error 404.0 returns. MIME-TYPE from *.php is “application/octet-stream”. The Error-Code from IIS is: 0x80070002 and the handler is: PHP.

I have tried to find a solution in this and other forums, but nothing works. I have checked the rights an IUSR has full access and the physical path exist and the file is in this directory the file.

Pdf uploading without using input box in php

I am using a javascript code to annotate the pdf within the browser and after annnotating i am saving it to mydevice and then uploading it using another form.

but i want it be uploaded into the local storage of web page and then upload automatically to my upload.php

function printPDF() {
    const printWindow = window.open('', '_blank');
    const printDoc = printWindow.document;

    for (let i = 0; i <= pdfDoc.numPages; i++) {
        pdfDoc.getPage(i).then(page => {
            const viewport = page.getViewport({ scale: 1.5 });
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = viewport.width;
            canvas.height = viewport.height;

            const renderContext = {
                canvasContext: context,
                viewport: viewport
            };

            page.render(renderContext).promise.then(() => {
                renderAnnotationsOnCanvas(context, i); // Render annotations on the canvas
                const imageData = canvas.toDataURL();
                printDoc.write('<img src="' + imageData + '" style="max-width: 100%;">');
                if (i === pdfDoc.numPages) {
                    printDoc.close();
                    printWindow.onload = function () {
                        printWindow.print();
                        printWindow.close();
                    };
                }
            });
        });
    }
}

this is output window we get after the print pdf get trigger this just an example:

this is output window we get after the print pdf get trigger this just an example

This is my java script code to save the the annotated pdf

class stdClass could not be converted to string [closed]

Good morning! I have a problem with my website. I get this message when i try to go to my website

“Object of class stdClass could not be converted to string”.

I tried to find stdClass in my code base but I could not find it. there are my files in my website. is there any tools to go over my code fils in find this STDclass?

How to configure htaccess to display images from a directory other than the root directory

I am working with PHP and apache, and I have configured a router that shows me the images that are on the public site and root without problem, but when trying to show the images of the private site does not load them.

test

I need to save images on the private site and show them only to the owners, I don’t think saving the images on the public site is ideal.

The router is configured so that all routes publicly begin with “/” and not “../”.

How could I solve this locally and have it work correctly on a real server?.

//project structure:

app/
-------/public     <======Root
---------------/css
---------------/img
---------------/js
---------------/index.php
---------------/.htaccess
-------/private
---------------/imgs    
---------------/pages
---------------/dashboard.php
-------/lib
-----------/route.php`

//.htaccess config

AddType Content-Type: application / x-www-form-urlencoded

Options -MultiViews
RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 


RewriteRule ^(.*)$ index.php? [QSA,L]

//html

    <span> <img src="img/test2.jpg" width="30px"> </span>
   <span> <img src="../private/imgs/test1.jpg" width="30px"> </span>

//php try

<?php
    $directorio = "../private/imgs/";

    function printImagesDir($dir){
        $files = glob($dir.'*.{jpg,JPG,jpeg,JPEG,png,PNG}', GLOB_BRACE);
        foreach($files as $filename){
            $imgsrc = basename($filename);
            echo "<img src='{$dir}/{$imgsrc}' />";
        }        
    }

    printImagesDir($directorio);
?>

RecursiveDirectoryIterator: Access is denied

I’m trying to deploy a site with laravel on Aruba, it’s the first time with this serve provider and for the first time I have got this error:

RecursiveDirectoryIterator::__construct(D:inetpubwebsmysite): Access is deni (code: 5)

any idea?