PHP fopen security risk?

After reading this blog post I realized that getimagesize() doesn’t provide absolute safety so I decided to use imagepng based on this answer. However to be able to use imagepng from image that is uploaded via xmr request, I need to use first this:

$input = fopen("php://input","r");
$temp = tmpfile();
$target = fopen($path,"w")
fseek($tamp,0,SEEK_SET)
stream_copy_to_stream($temp,$target_file_name)

Then I can use

$sourceImg = @imagecreatefromstring(@file_get_contents($source));
if ($sourceImg === false) {
  throw new Exception("{$source}: Invalid image.");
}
$width = imagesx($sourceImg);
$height = imagesy($sourceImg);
$targetImg = imagecreatetruecolor($width, $height);
imagecopy($targetImg, $sourceImg, 0, 0, 0, 0, $width, $height);
imagedestroy($sourceImg);
imagepng($targetImg, $target);
imagedestroy($targetImg);

If image contains some malicious code, could in this case using fopen and stream_copy_to_stream posses any risk? If so, is there any better way if image is uploaded with xmr?

PHP website: How to restrict uploaded files to only the requesting student in an online school document processing system?

good day. I am a total noob but I would like to ask for you help by asking this question. We are currently building a php website from scratch which is an Online School Documents Processing system where the students can request for their files online and the admin will approve the request by uploading the file and the student can see and download the file. My problem is when the admin uploads the requested file, all students who have signed up can see the file. I want it to be exclusive to the student who requested the file. How should I do that? THank you so much.

THis is the code for the uploading of the document in the admin:

   <?php include('main_header/header.php');?>
     <?php include('left_sidebar/sidebar.php');?>
    <div class="dashboard-wrapper">
        <div class="container-fluid  dashboard-content">
            <div class="row">
                <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="page-header">
                         <h2 class="pageheader-title"><i class="fa fa-fw fa-file-word"></i> Add Document </h2>
                        <div class="page-breadcrumb">
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="#" class="breadcrumb-link">Dashboard</a></li>
                                    <li class="breadcrumb-item active" aria-current="page">Document</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>                
                <div class="row">
                    <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                                <div class="card influencer-profile-data">
                                    <div class="card-body">
                                         <div class="" id="message"></div>
                                        <form id="validationform" name="docu_form" data-parsley-validate="" novalidate="" enctype="multipart/form-data" >
                                            <div class="form-group row">
                                                <label class="col-12 col-sm-3 col-form-label text-sm-right"><i class="fa fa-file-word"></i> Document Info</label>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-12 col-sm-3 col-form-label text-sm-right">Upload Document</label>
                                                <div class="col-12 col-sm-8 col-lg-6">
                                                    <input data-parsley-type="alphanum" type="file" alt="document_name" id="document_name" accept=".docx, .doc, .pptx, .ppt, .xlsx, .xls, .pdf, .odt" required="" placeholder="" class="form-control">
                                                    <footer style="font-size: 11px"><b>File Type:</b><font color="red"><i>.docx .doc .pptx .ppt .xlsx .xls .pdf .odt</i></font></footer>
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label class="col-12 col-sm-3 col-form-label text-sm-right">Description</label>
                                                <div class="col-12 col-sm-8 col-lg-6">
                                                    <input data-parsley-type="alphanum" alt="document_decription" type="text" required="" placeholder="" class="form-control">
                                                </div>
                                            </div>

                                            </div>
                                            <div class="form-group row text-right">
                                                <div class="col col-sm-10 col-lg-9 offset-sm-1 offset-lg-0">
                                                    <input type="text" alt="student_id" value="<?= $_SESSION['student_id'];?>" class="form-control" hidden>
                                                    <button type="button" class="btn btn-space btn-primary" id="btn-docu">Submit</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                        </div>
                    </div>
                </div>
       
        </div>
    </div>
</div>

<script src="../assets/vendor/jquery/jquery-3.3.1.min.js"></script>
<script src="../assets/vendor/bootstrap/js/bootstrap.bundle.js"></script>
<script src="../assets/vendor/parsley/parsley.js"></script>
<script src="../assets/libs/js/main-js.js"></script>
<script>
$('#form').parsley();
</script>
 <script type="text/javascript">
    $(document).ready(function(){
      var firstName = $('#firstName').text();
      var lastName = $('#lastName').text();
      var intials = $('#firstName').text().charAt(0) + $('#lastName').text().charAt(0);
      var profileImage = $('#profileImage').text(intials);
    });
</script>
<script>
(function() {
    'use strict';
    window.addEventListener('load', function() {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');
        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>

                    <script>
       document.addEventListener('DOMContentLoaded', () => {
          let btn = document.querySelector('#btn-docu');
          btn.addEventListener('click', () => {

          const document_name = document.querySelector('input[id=document_name]').value; 
          const document_decription = document.querySelector('input[alt=document_decription]').value;
          const student_id = document.querySelector('input[alt=student_id]').value;

         var data = new FormData(this.form);

            data.append('document_name', $('#document_name')[0].files[0]);
            data.append('document_decription', document_decription);
            data.append('student_id', student_id);


            if (document_name === '' || document_decription === '') {//continue niyo nalang ito
              $('#message').html('<div class="alert alert-danger"> Required All Fields!</div>');
              } else {
                  $.ajax({
                      url: '../init/controllers/add_document.php',
                      type: "POST",
                      data: data,
                      processData: false,
                      contentType: false,

                      async: false,
                      cache: false,

                      success: function(data) {
                          $('#message').html(data);

                      },
                      error: function(data) {
                          console.log("Failed");
                      }
                  });
              }     

          });
      });
  </script>

            

Trying to Understand Push Notifications Hybrid

I try to make a simple script to send a push notification to a device. Somehow, I know people have to “accept” notifications in the browser, but I also want it to be possible to send the push notification directly to their phone, and not only “in the browser”.

Can any help me with the following code, and tell me, how I can receive that information to move forward with my idea?

<!-- Install Firebase ?? -->

<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-analytics.js";
  // TODO: Add SDKs for Firebase products that you want to use
  // https://firebase.google.com/docs/web/setup#available-libraries

  // Your web app's Firebase configuration
  // For Firebase JS SDK v7.20.0 and later, measurementId is optional
  const firebaseConfig = {
    apiKey: "XXXXXXX",
    authDomain: "remindly-30fb7.firebaseapp.com",
    projectId: "remindly-30fb7",
    storageBucket: "remindly-30fb7.appspot.com",
    messagingSenderId: "xxxxxxxxx",
    appId: "1:632795751581:web:0075b5505db3872df9e074",
    measurementId: "G-GWQCRDQDHV"
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);

  console.log(app);
  console.log(analytics);
</script>


<?php
error_reporting(E_ALL);

$API_ACCESS_KEY = "AXXXX"; //this one i got
$passphrase = "?????=??????????"; //Dont know what to put here
$channelName = "?????=??????????"; //Dont know what to put here

/** Push notification data **/
$push_title = "Jesper has birthday in 7 days!!";
$push_text =
    "your co-worker has birthday in 7 days - find the perfect present here!";



function android($reg_id)
{
    global $API_ACCESS_KEY;
    global $push_text;
    global $push_title;

    $url = "https://android.googleapis.com/gcm/send";
    $message = [
        "title" => $push_title,
        "message" => $push_text,
        "subtitle" => "",
        "tickerText" => "",
        "msgcnt" => 1,
        "vibrate" => 1,
    ];

    $headers = [
        "Authorization: key=" . $API_ACCESS_KEY,
        "Content-Type: application/json",
    ];

    $fields = [
        "registration_ids" => [$reg_id],
        "data" => $message,
    ];

    return useCurl($url, $headers, json_encode($fields));
}

function WP($uri)
{
    global $push_text;
    global $push_title;

    $delay = 2;
    $msg =
        "<?xml version="1.0" encoding="utf-8"?>" .
        "<wp:Notification xmlns:wp="WPNotification">" .
        "<wp:Toast>" .
        "<wp:Text1>" .
        htmlspecialchars($push_title) .
        "</wp:Text1>" .
        "<wp:Text2>" .
        htmlspecialchars($push_text) .
        "</wp:Text2>" .
        "</wp:Toast>" .
        "</wp:Notification>";

    $sendedheaders = [
        "Content-Type: text/xml",
        "Accept: application/*",
        "X-WindowsPhone-Target: toast",
        "X-NotificationClass: " . $delay,
    ];

    $response = useCurl($uri, $sendedheaders, $msg);

    $result = [];
    foreach (explode("n", $response) as $line) {
        $tab = explode(":", $line, 2);
        if (count($tab) == 2) {
            $result[$tab[0]] = trim($tab[1]);
        }
    }

    return $result;
}

function iOS($devicetoken)
{
    global $passphrase;

    $deviceToken = $devicetoken;

    $ctx = stream_context_create();
    // ck.pem is your certificate file
    stream_context_set_option($ctx, "ssl", "local_cert", "ck.pem");
    stream_context_set_option($ctx, "ssl", "passphrase", $passphrase);

    // Open a connection to the APNS server
    $fp = stream_socket_client(
        "ssl://gateway.sandbox.push.apple.com:2195",
        $err,
        $errstr,
        60,
        STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,
        $ctx
    );

    if (!$fp) {
        exit("Failed to connect: $err $errstr" . PHP_EOL);
    }

    // Create the payload body
    $body["aps"] = [
        "alert" => [
            "title" => $push_title,
            "body" => $push_text,
        ],
        "sound" => "default",
    ];

    // Encode the payload as JSON
    $payload = json_encode($body);

    // Build the binary notification
    $msg =
        chr(0) .
        pack("n", 32) .
        pack("H*", $deviceToken) .
        pack("n", strlen($payload)) .
        $payload;

    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));

    // Close the connection to the server
    fclose($fp);

    if (!$result) {
        return "Message not delivered" . PHP_EOL;
    } else {
        return "Message successfully delivered" . PHP_EOL;
    }
}

function useCurl($url, $headers, $fields = null)
{
    // Open connection
    $ch = curl_init();
    if ($url) {
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarily
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        if ($fields) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        }

        // Execute post
        $result = curl_exec($ch);
        if ($result === false) {
            die("Curl failed: " . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        return $result;
    }
}

//Send notification to android device? ((Where to find 'reg_id' id?? ))
android("reg_id???????? where to find?");

//Send notification to iOS device? (where to find 'devicetoken' ?? ))
iOS("devicetoken??? where to find??");

//Send notification to Windows device? (Where to find '$uri'? parameters? What is that?)
WP("uri, where to find ???");

?>

Can any guide me through the process to get this working? Where should i apply, etc?

Acquiring login details for squirrel mail target [closed]

Acquiring login details for squirrel mail

Target: Squirrel mail 1.4.22 running on apache http 2.4.7 Ubuntu

I’m running Kali Linux on a virtual machine

I’ve been tasked with exploiting a machine running squirrel mail.

I’ve tried metasploit modules for exploitation and nothing is working. There are tutorials on how to gain access to the machine after passing the login page but I can’t understand how to pass login.

I’ve tried researching exploits but I can’t understand the terms used in exploit databases.

Any help is appreciated!

php pipeline function what the wrong in this code [closed]

what the problem in this code anyone please resolve this code I try to resolve this code many times this code written in PHP Laravel framework and I cant understand what can I do I don’t know what I do wrong in this code

    public function pipeThrough($pipes)
    {
        return static::make($pipes)->reduce(
            function ($carry, $pipe) {
                return $pipe($carry);
            },
            $this,
        );
    }

Loading a SQL table into a tree

I have a SQLite database with a table of 8000 entries. Each row in this table has a “parent” column which refers to another element in the same table.

What would be the most efficient way to load this table into an easier to access tree-variable?

The “recursive” way is too slow:

function BuildMap($top = 0)
{
    global $allmap;
    if ($top == 0)
    {
        $q1 = Q("SELECT * FROM ORGCHART WHERE PARENT = 0 ORDER BY NAME ASC");
        while($r1 = $q1->fetchArray())
        {
            // Save to an array code here
            ...            
            BuildMap($r1['ID']);
        }
    }
    else
    {
        $q2 = Q("SELECT * FROM ORGCHART WHERE PARENT = ? ORDER BY NAME ASC",array($top));
        while($r2 = $q2->fetchArray())
        {
            // Save to an array code here
            ...            
            BuildMap($r2['ID']);
        }
    }
}

How can I fix a PHP script that isn’t updating input selection branch_status in a database table?

Using the given below php script, I connect to database and insert data in it. But the data getting inserted in my database table Except Status insput. It is also not throwing any error. Where is my code wrong?
Suggest me Changes.

localhost/index.php?branch_id=1
index.php Code:

<?php

<form action="index.php" method="POST">
    <?php
    if (isset($_GET['branch_id'])) {
        $branch_id = $_GET['branch_id'];
        $query = "SELECT * FROM branch_list WHERE branch_id='$branch_id' LIMIT 1";
        $query_run = mysqli_query($con, $query);
        foreach ($query_run as $row) {
            ?>
            <input type="hidden" name="b_id" value="<?php $row['branch_id']; ?>">
            <input type="text" value="<?php echo $row['branch_name']; ?>" name="b_name">
            <input type="email" value="<?php echo $row['branch_email']; ?>" name="b_email">
            <input type="number" value="<?php echo $row['branch_phone']; ?>" name="b_phone">
            <input type="text" value="<?php echo $row['branch_address']; ?>" name="b_address">
            <select name="b_status" class="form-select">
                <?php
                if ($row['branch_status'] == 1) {
                    ?>
                    <option selected>Active</option>
                    <option>Deactivated</option>
                <?php } else {
                    ?>
                    <option>Active</option>
                    <option selected>Deactivated</option>
                <?php } ?>
            </select>
            <button type="submit" name="edit_office"> Update Details</button>
        <?php }
    } ?>
</form>

Trying to code a simple script which alter already present data in a Database table, but Data is Not getting Update Can Someone Pls Check the Code and Suggest me Changes.

Which frameworks/languages use to build decent website? [closed]

So as my final uni project I have chosen to program a website which will include:

  • databse (probably MySQL),

  • register and login system with validation,

  • real-time notification system,

  • some charts probably with chart js.

I’ve been studying PHP for a while and it won’t be difficult to do the task but as I heard it’s better to use frameworks insted of raw PHP these days. I decided to learn at least one for now and make my project using MVC pattern (and to do it properly I probably need some framework like Laravel?or not?).

So here’s my question: is it better to stick to raw PHP, learn and use basic Laravel (for MVC pattern and better code organization) or maybe learn and use something else like Node js with Express? Thanks for the answers in advance 🙂

WordPress Error on XAMPP: An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration

When I try to install a theme or a plugin on WordPress (on XAMPP), I get this error:

An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration.

I have checked the XAMPP port settings and the ports used by Apache (80, 443) and MySQL (3306) are not being used by anything else:

XAMPP Netstat

P.S. MySQL starts successfully.

Why am I getting ‘Unable to find the wrapper https’ error with file_get_contents on Apache, despite openssl config in php.ini?

I get an error: “Unable to find the wrapper https” when i execute file_get_contents via apache.
I have already configured extension=openssl in php.ini.
i try to dump the wrappers by using

echo var_dump(stream_get_wrappers());

and the result shows

screenshot from apache.

It seems that the https wrapper is indeed missing.

but file_get_contents works well under php interactive shell and stream_get_wrappers shows wrapper has been loaded as

screenshot from php interactive shell

what could be the reason for those different behaviours between apache and php shell?
many thanks in advance for any hints

Environment: Apache 2.4.57 Win64 + PHP 8.2 (8.2.6) VS16 x64 Thread Safe

Get Users with meta query filtering on foreach loop from ACF Users field

I’m hoping that someone can help me.

I’m trying to work out why my loop isn’t working.

I’m wanting to loop through all users on the site and then use a meta query to display only the users that have the current users name in a user field. Essentially like if someone added you as a friend/connection, but you didn’t add them. So the the current user can see who’s added them to their connections.

Does that make sense?

I’m using an ACF user field to do this.

The code i’m using that isn’t working is below:

<div class="connectedtoyou usersloop teamloop" style="margin-top:40px!important;margin-bottom:40px!important;display:none!important;">
<hr>
<div class="users">
<h3 class="center centered">Users connected to you</h3>
<?php 
$current_user = wp_get_current_user();
//$connect_user = 'user_'.$current_user->ID;
//$connect_field = get_field('user_follows');

$args = array(
        //'role' => 'subscriber',  
        'orderby' => 'display_name',
        'order'   => 'ASC',
        'meta_query' => array(
            array(
                'key' => 'field_63d0017ab088f',
                'value' => $current_user->ID,
                'compare' => '=='
            )
         )
        );
$users = get_users($args);
if( $users ): ?>
<div class="row isotope">
    <?php foreach( $users as $user ): ?>
    <div class="col fade-up item">
            <div class="item-container"><a href="<?php echo get_author_posts_url( $user->id ); ?>" style="text-decoration:none!important;">
                <?php if ('health' == get_user_meta($user->ID, 'mepr_select_ident', true)) { ?><img src="<?php echo get_home_url(); ?>/wp-content/uploads/2023/01/D4HGN_Logo_2.png" alt="Health">
                <?php } elseif ('design' == get_user_meta($user->ID, 'mepr_select_ident', true)) { ?><img src="<?php echo get_home_url(); ?>/wp-content/uploads/2023/01/D4HGN_Logo_1.png" alt="Design">
                <?php } elseif ('research' == get_user_meta($user->ID, 'mepr_select_ident', true)) { ?><img src="<?php echo get_home_url(); ?>/wp-content/uploads/2023/01/D4HGN_Logo_3.png" alt="Research">
                <?php } elseif ('global' == get_user_meta($user->ID, 'mepr_select_ident', true)) { ?><img src="<?php echo get_home_url(); ?>/wp-content/uploads/2023/01/D4HGN_Logo_4.png" alt="Global">
                <?php } elseif ('network' == get_user_meta($user->ID, 'mepr_select_ident', true)) { ?><img src="<?php echo get_home_url(); ?>/wp-content/uploads/2023/01/D4HGN_Logo_5.png" alt="Network">
                <?php } else { ?>
                <?php } ?>
                <h4 class="darkgrey"><?php echo esc_html( $user->first_name ); ?> <?php echo esc_html( $user->last_name ); ?></h4>
            </a></div>
            </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<p>No users are connected to you. <a href="https://d4hgn.com/network/network-users/">Click here to see who's on the network</a>.</p>
<?php endif; wp_reset_postdata(); ?>
</div>
</div>

Can anyone help me work this out?

How do I implement Google Sign-In for @cisstudent.no and @cisteacher.no domains on my web project with PHP, Javascript, and CSS?

Im making a website in my design class, and I need to add a log in so that only specific google domains to our school can view the pages I make and not the rest of the world.

It would need to be google log in where the domains @cisstudent.no and @cisteacher.no are the ones who access the pages. I am using PHP, Javascript and CSS from beforehand. is anyone willing to help me?

How to prevent WordPress update notification from being displayed in plugin admin page?

Tried add those to main php file of plugin, did not help:

I would also prevent any other notification.


function tiketwp_handle_php_errors()
{
    // Turn off the display of PHP errors
    ini_set('display_errors', 0);

    // Log PHP errors to a file
    ini_set('log_errors', 1);
    ini_set('error_log', WP_CONTENT_DIR . '/php_errors.log');

    // Set the error reporting level
    error_reporting(E_ALL);
}

function disable_plugin_update_notification() {
    remove_action('admin_notices', 'update_nag', 3);
}

add_action('init', 'TiketWP\twppwr\tiketwp_handle_php_errors');
add_action('admin_menu', 'disable_plugin_update_notification');

enter image description here

Multidimensional array is not returned correctly in Magneto 2 item

I want to read out a multidimensional array which is set in an item and requested by API. But in my browser the array is always returned like this:

items:
 products:
  0: "{"id":"1","name":"first product"}"
  1: "{"id":"2","name":"second product"}"

Instead it should look like this:

items:
 products:
  0:
   id: 1
   name: first product
  1:
   id:2
   name:second product

My multidimensional array looks like this:

products[] = [
'product1' => [
 'id' => 1,
 'name' => 'first product'
],
'product2' => [
 'id' => 2,
 'name' => 'second product'
]]

Therefore I added my new variable/array also in the interface of this item:

/**
* @return array
*/
public function getProducts();

/**
* @param array $products
* @return $this
*/
public function setProducts($products);

In my php code I add the data in the following way to my item:

$item = $this->itemFactory->create();
$item->setData([
 'products' => $products
])

Does anybody know why the multidimensional array is formatted in this way?

Display data through api after submitting and checking a specific parameter

never worked on APIs.
The thing is I have an API and my need is, user will submit three parameters

  1. electricity_bill
  2. roof_area
  3. pincode

after submitting these parameters, the api will be called and then there will be checking against another parameter -> “resident_serviceable”.
Now if it’s value is “YES” then I have to show some data otherwise there will be an error message.

As I described earlier never worked on APIs, I am unable to do this.
Please help!!
Thank you

API Details

API Type: POST
Endpoint: http://3.108.0.8:5000/sunedison_solar_sense_api
Bearer Token: aHVic3BvdC1jb25zdW1lcjpibHVlb3NoYW4

Body
form-data
electricity_bill 15000

roof_area 200

pincode 560025