PHP SoapClient failed to load WSDL because of their disabled metadata

In the current backend code (PHP), the SoapClient is used to call the web service successfully for long time, but since this web service was recently changed by the other team to disable their metadata for security purpose, it impacts our backend code – SoapClient failed when loading the WSDL. We cannot see any exceptions in logs, just blank when running the PHP application.

Backend in PHP:

class WebService {
var $service;

function __construct() {
    echo 'before createService ';
    $this->createService();
    echo 'after createService ';
}

function createService() {
    echo 'before soapclient ';
    try 
    {
        $this->service = new SoapClient("http://XXXX.svc?wsdl",
           array("trace" => 1,"exceptions"=>0));
        
    } catch (SoapFault $exception) {
                
        echo $exception->getMessage();
    }
    echo 'after soapclient ';
 }
.
.
.
}

Run the application on Chrome. See the logs as below. No exception logs.

enter image description here

The real issue is that the SoapClient failed to load the WSDL because of their metadata disabled. No access to this service.

enter image description here

The team confirmed that this service doesnt involve any Authentication type but involves with TLS stuff.

My question is :

Is there any way to communicate PHP SOAP using TLS ? I’ve googled a lot but could not find any solution yet. Im looking for guideline like step by step and code sample.

Any suggestion?

Using splat to pass and receive function arguments with an associative array

If I do this:

function myfunc(mixed ...$var) {
  dump($var);
}

$param = [
  'one' => 1,
  'two' => 2,
];
myfunc(...$param);

Then the output is:

^ array:2 [
  "one" => 1
  "two" => 2
]

It’s useful that the array keys are preserved, but I don’t see anything about this in the documentation at https://www.php.net/manual/en/functions.arguments.php.

What’s happening here? Is it documented behaviour that’s by design, or a quirk that could vanish in a future version of PHP?

Include tags and categories in AJAX search results in WordPress (no plugin)

We have a search field on our website that uses AJAX. It’s purpose is to let visitors search for specific posts, it works great but, the search seems to only search through the title and contents of the posts, we would like it to also search through categories and tags.

Below you can see our code in functions.php. It only searches through titles ans and contents of posts but not their categories or tags

 ==================
 Ajax Search
======================   
*/
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>
<?php
}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( array( 'posts_per_page' => 8, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('post') ) );
    if( $the_query->have_posts() ) :

...
 

Some of our posts have the tag ‘male’ or ‘female’ and the title might also contain the words male of female. When a visitor searches the word male it should show the posts with the word male in the tag and/or the title ect. But as I said it only searches through titles and and contents of posts but not their categories or tags, so…

We think our problem might be solved by adding/changing something in this area of the code, but we are not sure what or where exactly.

<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

We have searched the internet for the answer to our problem however, the answers we find are either not related or the solution relies on a plugin, and we would like to fix this thought code and not installing more plugins.

We appreciate any help we can get.

We haven’t tried much because we are not sure what we should change in our code.

I’m trying to save the divin image to hosting in javascript but it saves as a blank image

I want to save the image of the div as an image to the hosting with javascript bottleCanvas, it puts the image in a div, but when I want to save it as an image file, it saves it as an empty image. How can I solve this problem?

index.php:

var bottleCanvas = document.getElementById('kanepe');
var dataURL = bottleCanvas.toDataURL("image/png");
var anchor = document.createElement('a');
anchor.href = dataURL;
anchor.download = 'screenshot.png';
anchor.innerHTML = '<img width="100" height="100" src=' + dataURL + '>download';
document.getElementById('output').appendChild(anchor);
                
                
    $.ajax({
        url: "upload.php",
        type: "POST",
        data: 'image=' + dataURL,
        success: function(cikti2){
            alert(cikti2);
        }
    })

upload.php:

if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {    

    // get the dataURL
    $dataURL = $_POST["image"];  

    // the dataURL has a prefix (mimetype+datatype) 
    // that we don't want, so strip that prefix off
    $parts = explode(',', $dataURL);  
    $data = $parts[1];  

    // Decode base64 data, resulting in an image
    $data = base64_decode($data);  

    // create a temporary unique file name
    $file = "resimler/" . uniqid() . '.png';

    // write the file to the upload directory
    $success = file_put_contents($file, $data);

    
    print $success ? $file : "Unable to save this image."; 
}

i want some information about php tools [closed]

What are some PHP best practices that every developer should know? Are there any common mistakes or bad practices that I should avoid when writing PHP code? Additionally, are there any specific tools or frameworks you recommend for implementing these best practices in PHP development?

i have used visual studio and script case

How to create site setting in laravel

I’m trying to create website settings in a Laravel app. To store the settings, I created a table with two columns: “key” and “value”.

My settings data can be of various types, including arrays, strings, booleans, and others. I thought I could use $casts to handle the different data types, but it’s not working as expected. For example, if I set the column to cast as an array, the data stored in that column should always be an array, but that’s not the case.

Can you help me figure out how to handle different data types for my website settings in Laravel?

Thank you.

Remove the unwanted array levels

After created my file tree, I have got this result which is shown as below :

Here,In This image, the orange boxes shows the unwanted array for only directories, except files.

The function which has been created for now as shown below:

public function addresourceTree(Resource $r) {
        $currentNode = &$this->filesTree;
        $exploded = explode('/', $r->getPath());

        if (! $r->getPath()) {
            return;
        }

        if ($r->isDirectory()) {
            $lastIndex = count($exploded) - 2;
            $resourceName = $exploded[$lastIndex];
        } else {
            $lastIndex = count($exploded) - 1;
            $resourceName = $exploded[$lastIndex];
        }

        for ($index = 1; $index < $lastIndex ; $index++) {
            $cur = $exploded[$index];
            $currentNode = &$currentNode[$cur]['children'];
        }

        $resourceDescr = [];
        $resourceDescr['fpath'] = $r->getPath();            

        if ($r->isDirectory()) {
            $resourceDescr['children'] = [];
        }
        
        $currentNode[$resourceName] = $resourceDescr;
    }

How to remove that unwanted level for clear file tree structure ?

How can I efficiently load images on a website [closed]

I have a website where users can upload products with images and other users can search for them on a search page. My search page currently have 50 products per page (and some ads in between) and each of these product cards have an image on it.

First I tried to put the image src straight into HTML like you usually do:

<img src="my_image.jpg">

This made the search page load slowly before showing any content (I hide the content and show a spinner until body is loaded).

Then I tried to put the source as a placeholder attribute, which on document load then was switched to the src attribute in JS to reveal the image:

<img placeholder-src="my_image.jpg">

$(document).ready(function() {
    $('[placeholder-src]').each(function() {
        var imageSource = $(this).attr('placeholder-src');
        $(this).attr('src', imageSource);
    }); 
});

This made the page itself load almost instantly but with no images. And then you could see the images load from top to bottom slowly, around the same time it took before to load them I guess (but now you could see when they loaded).

What I have done so far

I tried to speed up images by:

  • Limit the size of the images that users can upload. They will now before upload compress to a max height or width of 550px since I never show it in larger formats on my site. Still the largest images are around 1Mb in size.
  • I was thinking of saving them in an even smaller format to show as thumbnails on my search page. They could then have a max width/height of 300px and should load almost double speed (?). However, this will increase my image storage by 50% which is not good since I will have LOTS of images.

Question

What is the best way to load images on a webpage to improve the experience and make the site load faster?

how to transfer old database to new laravel database

I have an old database that I don’t want to use for the new Laravel based system.

The previous database is relatively heavy and it takes a lot of time to transfer through query by migration.

Is there an optimal way to transfer information from the previous database to the new database? In such a way that information is extracted from the previous database and transferred to the new database in a sorted form by us

Please guide me

Currently, I use migration to query the old database and insert information into the new database. But this mode causes disruption in the main server due to high timeout.

Laravel – The requested resource was not found on this server

I am trying to display the profile pictures for users on their posts as part of my website I am creating. However, for some reason it is not displaying the image, in spite of the path being valid.

This is my img tag:

<img class="rounded-full object-cover h-16 w-16" src="{{ url('images/profile_pictures/'.$post->user->id.'.'.$post->user->pfp_file_extension) }}" onerror="this.onerror=null; this.src='images/profile_pictures/default.jpg'"  alt="">

And when I open the image in the browser, I get the url:

http://localhost:8000/images/profile_pictures/

With the error:
The requested resource /images/profile_pictures/ was not found on this server.

This is very confusing, because when users visit their profile page, they can see their profile picture just fine, and if it does not exist they see the default.jpg as expected. My img tag for that is very similar:

<img src="{{ url('images/profile_pictures/'.Auth::user()->id.'.'.Auth::user()->pfp_file_extension) }}" onerror="this.onerror=null; this.src='images/profile_pictures/default.jpg'" class="rounded-circle">

And the url it takes me to is the same:

http://localhost:8000/images/profile_pictures/1.jpg

I have tried all the fixes from this post Image not displaying in view. Laravel , but to no avail. I am still hit with the same error.

I was expecting the image to display in the profile picture, however it cannot find the image. It works just fine on the profile page despite using an almost identical src path. Any ideas?

How to configure folder rights to execute the command

Since several month, i m trying to user exec command in order to launch a file import in a business management application.
The software name is EBP, we must use a .exe file to do import.
Here is the command

"C:\Program Files\EBP\Invoicing11.0FRFR40\EBP.Invoicing.Application.exe"
/Gui=false;"C:INTERFACES_TESTALKORlogs20230307112630.txt " /Database="C:UsersPublicABPOST_TEST.ebp";USR;PASSWORD
/Import="C:INTERFACES_TESTALKORtodo230306151623_CDE_A638-00005912.csv";SaleOrders;SDK_ImportAlkorShop

If i launch it in a terminal, it works.
I would like to launch it with PHP. So in Symfony, i add a controller to do the import, in this controller i add the following lines:

$commande = escapeshellarg($this->ebpImportExecutable)
    . ' /Gui=false;' . escapeshellarg($this->urlImportArkor.'logs\'.date('YmdHis').'.txt" ')
    . ' /Database=' . escapeshellarg($this->database).';USR;PASSWORD'
    . ' /Import=' . escapeshellarg($this->urlImportArkor . 'todo\' . $nomdufichier) . ';SaleOrders;SDK_ImportAlkorShop';
//echo $commande;exit();

exec($commande, $output, $retCode);

With Postman i tryed to to the import, the output of the exec command is an empty array.

In the Windows Application Log, i found the following error:

Application : EBP.Invoicing.Application.exe Version du Framework : v4.0.30319 
Description : le processus a été arrêté en raison d'une exception non gérée. 
Informations sur l'exception : System.ArgumentException à System.Security.Util.StringExpressionSet.CreateListFromExpressions(System.String[], Boolean) 
    à System.Security.Permissions.FileIOPermission.AddPathList(System.Security.Permissions.FileIOPermissionAccess, System.Security.AccessControl.AccessControlActions, System.String[], Boolean, Boolean, Boolean) 
    à System.Security.Permissions.FileIOPermission..ctor(System.Security.Permissions.FileIOPermissionAccess, System.String) 
    à System.Environment.InternalGetFolderPath(SpecialFolder, SpecialFolderOption, Boolean) 
    à EBP.Framework.Common.FoldersHelper+<>c.<.cctor>b__11_5() 
    à System.Lazy`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].CreateValue() 
    à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    à System.Lazy`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_Value() 
    à EBP.Framework.Common.FoldersHelper+<>c.<.cctor>b__11_4() 
    à System.Lazy`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].CreateValue() 
    à System.Lazy`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].LazyInitValue() 
    à EBP.Framework.Common.Log.LogHelper.GetIsLoggingEnabled() 
    à EBP.Framework.Common.Log.LogHelper.get_IsLoggingEnabled() 
    à EBP.Framework.Common.Log.LogHelper.Log(EBP.Framework.Common.Interfaces.Host.ISharedHostedApplication, Int16, System.Exception) 
    à EBP.Framework.Windows.Host.WinHost.CurrentDomain_UnhandledException(System.Object, System.UnhandledExceptionEventArgs) 
Informations sur l'exception : System.TypeInitializationException 
    à 8xM=.BRQ=.TxQ=() à 8xM=.BRQ=.OBQ=() à EBP.Framework.BusinessLogic.Host.DataHostedApplication.Initialize(Boolean) 
    à EBP.Framework.Windows.Host.WinHostedApplication.Initialize(Boolean) 
    à EBP.Invoicing.Application.HostedApplication.Initialize(Boolean) 
    à EBP.Framework.Common.Host.HostBase.InitializeApplication(EBP.Framework.Common.Interfaces.Host.ISharedHostedApplication, Boolean) 
    à EBP.Framework.Windows.Host.WinHost.InitializeApplication(EBP.Framework.Common.Interfaces.Host.ISharedHostedApplication, Boolean) 
    à EBP.Framework.Common.Host.HostBase.Run(EBP.Framework.Common.Host.IHostedApplication, Boolean, System.String[]) 
    à EBP.Invoicing.Application.Program.Main(System.String[]) 

There seems to be a permission error.
Does anybody have an idea ?
I tryed shell_exec and system command. i ve got the same issue.
Should i modify folder permission ?

Thank you

Socket Server on PHP

I want to write a PHP server that will provide connection between clients using Socket.IO v4.5.1 . It must be written entirely on PHP with no JS. At first I used Ratchet and parsed messages to pass format(Socket.IO v2). But after migrating to Socket.IO v4 on client side the messages are not recognised.

I probed to find some emitters but most of them are written for a client side or support v0-v2. Socket.IO official page gives advice for JS + NodeJs servers. I can mimic a socket server but can not find any passing format and client side recognises by me only 1 type of events (“ping”-“pong”)

If it is not possible at all -> then give please advise how to rewrite the server with less JS

cURL error 7: Failed to connect to ***** upon running a functional test method on codeception

Now I’m working on a monolith on PHP + YII and encountered with a problem.

Specifically, I took a job ticket, made it and some tests failed upon deployment. The testing engine is CodeCeption.

To debug these tests, I set up their execution in PHPStorm.

But when I try to run Functional tests that contains commands sending requests to web-server, for example, send GET, the execution catches exception and shows errors

failure message: cURL error 7: Failed to connect to my-monolith.local port 443: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html):

The monolith is in docker containers, is external port is 8443, whereas internal port is 443.

If I run tests inside docker containers via console, they work without these exceptions, but in case of running in PHPStorm, there are errors.

Could you clarify me or even surmise, what settings I could watch and fix?

Thanks in advance.

PHP DB Connections & Select operations

I am looking for some guidance on best practice wrt DB operations in a PHP dynamic web site.

To be clear, this web site makes no changes to the data (that happens elsewhere).

It seems to me there are four distinct operations.

  • Defining the DB Connection
  • Opening the DB Connection
  • Selecting data from the DB
  • Closing the DB Connection

The question is when (in the flow of building each page) to perform each of them.

It’s not really a question of performance, I’ve tried Open once and Open for every select, there seems to be negligible impact on performance (although I’ve not tried to measure at scale). Rather it’s a question of best practice for future code maintenance.

Thank you.