How can I seek in a video outputted by PHP?

For outputting a big video (duration 20m46s, size 1.34 GB),
I use the following code (file video.php):

<?php
define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk
// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt    = 0;
    $handle = fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($handle);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }

    return $status;
}

$filename = 'video.mp4';
$mimetype = 'video/mp4';
header('Content-Type: '.$mimetype );
readfile_chunked($filename);

?>

The video is watched in a HTML page with the following code:

<video controls>

<source src='video.php' type='video/mp4'>
  
</video>

However, seeking in the video doesn’t work correctly.
For example, if I move the play cursor for seeking to the 18:00 timestamp, it will
instead seek to the 0:58 timestamp.

How can I solve this?

pass multiple params from function to funtion and access inputs -Laravel

$myCourseData['points'] = "1";                 
 $myCourseData['totalPoints'] = "2";

$this->update($myCourseData,$myCourseId);

i wanted to pass points & totalPoints from a function to the function update() and access points in update() as $request->points;.How can i do that? Only points & totalPoints are passed from the above function , other params in the update() function input are getting from somewhere else.

function update($request,$id){

 $validator = Validator::make(
            $request->all(),
            [
                'course_id'       => 'nullable|integer',  
                'exam_numbers'    => 'nullable|integer',
                'points'          => 'nullable|integer', 
                'subscription' => 'nullable|boolean',
                'totalPoints'=>'nullable|integer'
            ]
        );     

$points =  $request->points;
}          
    

    

HOW TO GET QUERY IN SQL USING PHP IN SQL TIGGERING

This is my code my $sql variable didn’t give query plese help me for this I try this but I couldn’t please help me with that

<?php 
    $connect = mysqli_connect("localhost", "root", "", "finger");
    $f= "";
    $l= "";
    $sql = "CREATE TRIGGER `ersdmmmmecv` AFTER INSERT ON `event` FOR EACH ROW  SELECT fname,Lname INTO $f,$l  FROM user WHERE id=NEW.id;"
    $result = mysqli_query($connect, $sql);
?>

PHP Doctrine DTO integer id to uuid from ResultSetMapping

I am fetching results from doctrine native query and want to convert the id into uuid using result set mapper,I am using the below code:

$rsm = new ResultSetMapping();
    $rsm->addScalarResult('id', 'id', 'uuid_magic_optimised');
    $rsm->addScalarResult('title', 'title');
    $rsm->addScalarResult('vendor', 'vendor');
    $rsm->addScalarResult('icon_name', 'icon_url');

But getting the following error:

Doctrine  DBAL  Types  ConversionException
Could not convert database value "1" to Doctrine Type uuid_binary_ordered_time

Why can you call a private method on a new instance made inside a public method of the same class type, in PHP?

Why can you call a private method on a new instance made inside a public method of the same class type?

class Foo
{
    private function thePrivateMethod()
    {
        echo 'can not be called publicly?';
    }

    public function thePublicMethod()
    {
        $clone = new Foo;
        $clone->thePrivateMethod();
    }
}

$foo = new Foo();
$foo->thePublicMethod();
$foo->thePrivateMethod();

The above results in the following output when run in PHP 7.3.18

can not be called publicly?

Fatal error:  Uncaught Error: Call to private method Foo::thePrivateMethod() from context

Intuitively, I would expect the first call to Foo::thePrivateMethod() to also cause a fatal error. But I’m not able to find in the documentation that this behaviour would be allowed?

How to delete original after converting image with Spatie Media Library (laravel)

I am using Laravel 8 and I was wondering if there is anyway to automatically delete original image after it has converted in Spatie Media Library? it’s currently taking up my storage space so I want to be able to delete original images.

here’s the model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use SpatieImageManipulations;
use SpatieMediaLibraryHasMediaHasMedia;
use SpatieMediaLibraryHasMediaHasMediaTrait;
use SpatieMediaLibraryModelsMedia;

class Profile extends Model implements HasMedia
{
    use HasMediaTrait, softDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'theme_id',
        'name',
        'username',
        'location',
        'bio',
        'views',
    ];

    protected $appends = [
        'avatar_url',
        'route',
    ];

    protected $with = [
        'links',
        'theme',
    ];

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'username';
    }

    /**
     * @return mixed
     */
    public function getAvatarUrlAttribute()
    {
        if ($this->hasMedia('avatar')) {
            return $this->getFirstMedia('avatar')->getUrl('cropped');
        }

        return asset('/images/avatar.png');
    }

    /**
     * @return mixed
     */
    public function getRouteAttribute()
    {
        return route('profiles.show', $this);
    }

    /**
     * @return mixed
     */
    public function getKeywordsAttribute()
    {
        $keywords = $this->links
            ->map(function ($link) {
                return "{$link->name} {$this->name}";
            })
            ->toArray();

        $keywords[] = $this->name;

        return implode(',', $keywords);
    }

    /**
     * Get all of the profile's links.
     *
     * @param string $order
     *
     * @return IlluminateDatabaseEloquentRelationsMorphMany
     */
    public function links($order = 'asc')
    {
        return $this->morphMany(Link::class, 'linkable')->orderBy('order', $order);
    }

    /**
     * Get profile theme.
     *
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function theme()
    {
        return $this->belongsTo(Theme::class);
    }

    /**
     *
     */
    public function viewed()
    {
        $this->increment('views');
    }

    /**
     *
     */
    public function registerMediaCollections()
    {
        $this->addMediaCollection('avatar')->singleFile();
    }

    /**
     * @param Media|null $media
     *
     * @throws SpatieImageExceptionsInvalidManipulation
     */
    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('cropped')
             ->crop(Manipulations::CROP_CENTER, 200, 200)
             ->nonQueued()
             ->performOnCollections('avatar');
    }
}

Anyone know any method to do this so I can save storage space?

How to connect ZKTeco attendance to google sheet or online php server

I don’t have any idea of it how can i get attendance data directly to google sheet from ZKTeco attendance device. I searched many way to connect to php server but there is no clear information, how can I get access to the device attendance log. There also no HTTP request from the device also. So can any share there experience and how can I solve that issue ? I am using ZKTeco K40 and F18

Select all data from database MySQL not working php but the inserting working

First I have the insertion part here it’s getting data from json file then insert then select

  $mysqli  = new mysqli($servername, $username, $password,$db) or die("Connect failed: 
  %sn". $mysqli  -> error);
  echo "Connected successfully";

 $json = file_get_contents("https://raw.githubusercontent.com/SeteMares/full-stack-test/master/feed.json") ;
    $json = json_decode(  $json,true);
    $content= array();
    $TITLE = array();
    $CONTENT = array() ;
    $MEDIA = array() ;
    $SLUG = array() ;
    $categories = array() ;
    foreach ($json as $key => $value){
      
        $TITLE[] = $json[$key]['title'] ;
      
       
        $CONTENT[] = $json[$key]['content'];
        $MEDIA[] = $json[$key]['media'];
        $SLUG[] = $json[$key]['slug'];
        $categories[] = $json[$key]['categories'];
    }
    
    for($s=0;$s<sizeof($TITLE);$s++){

        $url_string =  $CONTENT[$s][0]['content'];
        $res = urldecode($url_string);
        $Cataggory = $categories[$s]['primary']; 
        echo gettype($Cataggory );
        $slug = $SLUG[$s] ;
        echo gettype($slug );

         $sqlquery = "INSERT INTO `jsondata` (`title`, `slug`, `content`, `categories`, `media`) VALUES (  '$TITLE[$s]',   ? ,   ?, ?,  '$TITLE[$s]' )" ;
         $stmt = $mysqli->prepare($sqlquery);
         $stmt->execute(array($slug,$res,$Cataggory));
       
         
    }

when i select the data it doesn’t work it prints

Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in C:xampphtdocsfirstphpindex.php:68 Stack trace: #0 {main} thrown in C:xampphtdocsfirstphpindex.php on line 68

this the select code for sure all the code in the same file



     $sqlquery3 = "SELECT 'title'   FROM jsondata  " ;
     $sth = $mysqli->prepare($sqlquery3);
     $sth->execute();
  
     $result = $sth->fetchAll();
     print_r($result);
    

Conflict between 2 function using ajax in wordpress

I have written this code here

  add_action('wp_head','pageType');
function pageType(){
  
    if (is_product()) {
            global $post;
            $product = wc_get_product( $post->ID );
            $tipo    = $product->get_type();
            echo $product->get_name();
            echo $product->get_price();
            echo $product->get_regular_price();
            return $product->get_name();
        }else{    
          return "NOTHING";
        }
    }

add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
  check_ajax_referer( 'my-special-string', 'security' );
  $whatever = intval( $_POST['whatever'] );


 $dataOfProduct = pageType();

  $whatever += 10000;
  echo $whatever . '=>>' . $dataOfProduct .' . ' . '<==== d';
  die(); 
}

The code is working fine

Example when pageType is being added to wp_head with add_action(wp_head,'pageType') the is_product is working fine so it is printing

        echo $product->get_name();
        echo $product->get_price();

But in the second method i have an ajax function because i am trying to send data to a tracking script

add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {

Inside this method when i am calling

 $dataOfProduct = pageType();

It is returning “NOTHING”

What can be the problem why its working is_product() function not working on my_action_callback()

What can be the problem

Here $dataOfProduct = pageType(); i want pageType to return the name of the product

THank you

Finding ocuppations via SQL and/or PHP

I am making a student web app. Amongst other tables, I have a table in which students enroll and enrollments are between two dates.

This app uses MySQL 5.6 and PHP 7.2
It has the following fields:

  • IDStudent
  • StartDate
  • EndDate
  • IDCourse

Each course has a maximum capacity in which it cannot be surpassed.

I want to know, given a start date, end date and IDCourse, how many concurrent students are in a course. I get an approxiumate value just counting rows between two dates

SELECT COUNT(*) FROM enrollments
    WHERE IDCourse = ? 
    AND (
      (StartDate BETWEEN "<start date>" AND "<end date>")
      OR
      (EndDate BETWEEN "<start date>" AND "<end date>")
      OR
      (StartDate <= "<start date>" AND EndDate>= "<end date>")
    )

But that doesn’t take account non overlapping ranges. It counts every enrollment.

For example, I have this very simple case:

Want to find how many students are enrolled between 01/01/2021 and 05/01/2021 at a specified course

And I have those 3 enrollments on that course:

  1. 01/01/2021 – 02/01/2021
  2. 03/01/2021 – 04/01/2021
  3. 20/12/2020 – 01/02/2021

I should get 2 count and not 3, because 1 and 2 don’t overlap while 3 overlaps both.
I tried to search online but I didn’t found something similar, maybe I am not using the correct keywords!

Many thanks for your help
Regards

how can i run PHP functions with query to database from javascript [duplicate]

How can i run php functions with query to the database from the level of the javascript function?

</script>
function databaseUpdate() {

}

</script>


<?php
function databaseUpdatePHP () {

    $sqlUpdateVocabulary = "UPDATE users SET number='$number+20' WHERE email='" . $_SESSION['username'] . "'";
    if(mysqli_query($conn, $sqlUpdateVocabulary)){
        echo "updated successfully.";
    } else {
        echo "ERROR";
    }

}
?>

php router passing parameters to call_user_func_array

<?php 
    class Router {
        protected $conn;
        protected $currentController = "";
        protected $currentMethod = "";
        protected $params = [];

        public function __construct(PDO $conn){
            $this->conn = $conn;
        }

        public function dispatch(){
            $url = $this->getUrl();
            if(isset($url[4])){
                switch($url[4]){
                    case "events":
                        $this->currenController = "EventController";
                        $this->currentMethod = "getEvents";
                        break;
                    case "event":
                        $this->params = $url[5];
                        $this->currentController = "EventController";
                        $this->currentMethod = "getEvent";
                        break;

                }
            }
            $this->currentController = new AppControllersEventController($this->conn);
            call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
            $this->currentController->display();
        }

        public function getUrl(){
            $uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
            $url = explode("/", $uri);
            return $url;
        }
    }
?>

$url[5] is supposed to be a numeric id for selecting an event or a string namely “?id=1” how can I pass this value to call_user_func_array I’ve seen doing it with preg_match expressions unfortunately I didn’t understand how it works

Download a local file using `<a href= "file://link/to/my/file" ` not working on chrome [duplicate]

The link How can I create a link to a local file on a locally-run web page? doesn’t help me, since the problems are not the same

I have the folowwing html code

<a href = "file://link/to/my/local/file/my file.xltx" target="_blank"> Download my file </a>

written inside index.php file

In IE, it works fine, but when coming to Chrome, it doesn’t work

I want to force Chrome (or any other browser) to download the file using php script only, whithout using chrome extension or configuration

Can any one help me ? Thanks in advance

Remarks

  • I tried curl method, but the problem is that the php script is server side, so the target location will be relative to server not to client
  • When I copy paste file://link/to/my/local/file/my file.xltx the the chrome adress bar, it works fine

Integrating Coldfusion and Pay360

Does anyone have any experience with integrating a Coldfusion website with Pay360? Basically our online shop needs to direct the user to a payment screen on Pay360 using the hosted cashier. The documentation is a bit vague but essentially we have to pass an API username and password, and json string to their request URL and they should return a response with a URL to a payment form. Should be straightforward using cfhttp but I get an error:

{“status”:”FAILED”,”reasonCode”:”exception.request.content”,”reasonMessage”:”Invalid request content: Unexpected character (‘/’ (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature ‘ALLOW_COMMENTS’ not enabled for parser)”}

No one at Pay360 seems to be able to help. I’ve also tried using PHP (having only found one example on bronco.co.uk by doing a Google search) but that doesn’t work for me either.

This is my code. If anyone can give any advice (or has a working CF or PHP script that could point me in the right direction) that would be great, thanks!

<cfset variables.username = "xxxxxx">
<cfset variables.password = "xxxxxx">
<cfset stFields = {
  "session": {
    "preAuthCallback": {
      "url": "http://www.example.com/callback/preAuth?status=SUSPEND",
      "format": "REST_XML"
    },
    "returnUrl": {
      "url": "http://www.example.com/transactionResult?MERCHANTREF=761585761585"
    }
  },
  "transaction": {
    "merchantReference": "761585761585",
    "money": {
      "amount": {
        "fixed": 100
      },
    "currency": "GBP"
    }
  },
  "customer": {
    "identity": {
      "merchantCustomerId": "1111111111111"
    },
    "details": {
      "name": "given1 Family1",
      "address": {
        "line1": "matched",
        "line2": "initialCustomer1AddresssLine2",
        "city": "initalCustomer1City",
        "region": "initalCustomer1Region",
        "postcode": "AVS111",
        "countryCode": "GBR"
      },
      "telephone": "0044111111111",
      "emailAddress": "[email protected]",
      "ipAddress": "1.1.1.1",
      "defaultCurrency": "GBP"
    }
  },
  "financialServices": {
    "dateOfBirth": "19870818",
    "surname": "Smith",
    "accountNumber": "123ABC",
    "postCode": "BS20"
  }
}>   

<cfhttp url="https://api.mite.pay360.com/hosted/rest/sessions/5309398/payments" method="post" username="#variables.username#" password="#variables.password#" result="httpResp" timeout="60">
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
    <!--- failed attempt to pass username and password in the body
<cfhttpparam type="formField" name="username" value="#variables.username#">
    <cfhttpparam type="formField" name="password" value="#variables.password#">--->
    <cfhttpparam type="body" value="#serializeJSON(stFields)#">
</cfhttp>

<cfdump var="#httpResp#"/>