/r/PHPhelp

Photograph via snooOG

This subreddit is for anyone who has questions about their PHP code.

Please read and understand the rules before creating a post.

Post specific problems or questions you have about PHP or your code.

Review our github to see if your question already has a great answer.

If someone answers your question, please mark your post as SOLVED.


/r/PHPHelp RULES:

1. Help us help you! Provide details about your question and be as specific as possible. When supplying code, preferably use PasteBin or similar.
2. Be nice Golden rule, people. If you believe someone is wrong, kindly inform them why you think so. It's possible you are also wrong. BE NICE!
3. Participate Posts that are only intended to get others to solve your problem add nothing to the community. Actively participate when you make a post by answering questions and sharing solutions.
4. Use a meaningful title Titles like: "PHP Help", "Help please", "Beginner question", or "I need some help with resolving this issue" are not good and not meaningful. Please include relevant info.
5. Don't delete an answered post People may be searching to solve a similar problem in the future. Don't take the provided answers away from them!
6. No malicious/illegal software Don't ask for help with phishing software, for example.
7. Self-promotion and/or linkdropping rules Our community adheres to the Reddit Self-Promotion Guidelines. Please become familiar with these guidelines as we, as moderators, will use them to remove content that we deem to violate these guidelines.
8. No job postings (For Hire or Hiring)
9. MARK YOUR POST AS SOLVED If your post has been solved, mark it as so by clicking Flair -> Solved.


CODE FORMATTING:

For inline code, use `backticks` to look like this.

For a moderate amount of code, put it on separate lines, and prepend each line with four spaces, like this:

<?php /* code goes here */ ?>

For a lot of code, use PasteBin or something similar.


Upcoming PHP Conferences:

For a full list of conferences see the list on php.net.


Learning:

  • PHP The Right Way
  • Treehouse
  • CodeAcademy
  • SymfonyCasts
  • Laracasts
  • PHP Academy
  • Software Mentors
  • Examples:

    Related subreddits:

    /r/PHPhelp

    26,626 Subscribers

    0

    Need assignment help regarding of where to start and what steps should i follow because i'm actually lost...

    " -Description of the assignment

    You are to develop a web application for a local business located in a City that offers a services

    or products for university students. The web application should reflect the main and actual

    business processes of the selected business in addition to offering new services such as e-selling,

    e-payment, or any other web-based activities.

    • Tasks

    The web application should include multiple webpage(s)- at least 4 web pages- designed by using

    relevant tools, such as: HTML, CSS, JavaScript, PHP and MySQL. The web application should at

    least meet the following criteria:

    1. Acquire data from the users to be stored in database, such as, name, age, gender, e-mail, and

    others, through a Sign-up/Registration form.

    1. Generate different types of reports, such as the total of registered users, current orders and

    sales.

    1. The web application should maintain validation aspects both on client and server side.

    2. The web application should have nice look and feel aspects"

    11 Comments
    2024/05/20
    19:29 UTC

    0

    How to query a field that is in a different format?

    In Laravel, if I have a phone number in the format of 1234567890 and I have a Customers table/model with a phone column that has the phone in the format of (123) 456-7890, what's the best way to query the Customers table?

    $phone = 1234567890

    $customer = Customer::where('phone', $phone)->first();

    4 Comments
    2024/05/20
    18:12 UTC

    5

    Return PHP data on HTML site

    Hey guys

    I have a HTML file and a separate PHP file witch a function.

    I want to have a HTML button which is triggering a PHP script which returns the data to the HTML file and displays the output.

    • My first try was to include_once the PHP function in the HTML. But like this it will display the PHP function return always, not only if I press the HTML button.

    • My second try was to use a method (post or get), but then it will display the data in the separate PHP file and not return it back to the HTML site on which I want to display.

    Best regards

    14 Comments
    2024/05/20
    08:50 UTC

    3

    Structuring a composer package into modules?

    How does one structure a composer package that has a few or several methods under one class but have each method as its own PHP file?

    In JS, you can struture a NPM package into modules which are seperate files. Each file is usally a method and then have a index.js file to put it all togeather into a JS object and the JS object has all the methods inside of it.

    Is this possible for PHP composer packages, by putting all of the methods inside of a class but having each method code in their own PHP script files?

    This is my setup so far. I know how to create a composer package and have seperate files for each function/method or ow to create a composer package and have seperate files for each class.

    File structure

    - composer.json
    - src/
       - functionA.php
       - functionB.php
       - myClass.php

    composer.json

    {
        "name": "test/test-package",
        "type": "library",
        "version": "1.0.0",
        "license": "MIT",
        "autoload": {
            "psr-4": {
                "": "src/"
            }
        }
    }

    functionA.php

    <?php
    
    function functionA() {
        return 'functionA';
    }

    functionB.php

    <?php
    
    function functionB() {
        return 'functionB';
    }

    myClass.php (Syntax is invalid)

    <?php
    
    require 'functionA.php';
    require 'functionB.php';
    
    class myClass {
        public function functionB()
    
        public function functionA()
    }
    5 Comments
    2024/05/19
    20:00 UTC

    2

    Xero Practice Manager API Integration with Laravel

    Hey all!

    I'm about to integrate Xero Practice Manager API with our Laravel app. We have OAuth2 set up and can attach a practice, but now I need to handle API communications.

    Looking for advice on:

    • Pitfalls to avoid while working with the Xero Practice Manager API
    • Best practices for handling XML responses and requests in Laravel
    • Efficiently creating jobs via the API

    Any tips, resources would be greatly appreciated!

    Thanks!🙏

    0 Comments
    2024/05/19
    11:53 UTC

    2

    Hello I am learning php and I am having issue with md5 encoding

    the code is this
    ```

    if(md5($param) == '0')

    ```
    and I have no idea how to find value that could be after md5 encryption a "0"

    8 Comments
    2024/05/19
    08:26 UTC

    3

    Is it ok or best practice for a php file to loop itself like this?

    I'm still pretty new to PHP and, forgive me for my vague title to this post, I just don't exactly know how to describe what I'm doing here, or if it's even advisable. Basically, this is the "front" php page that serves as a starting point: the user enters some information, and hits the "Let's Go!" button.

    <html>
    <head>
        <title>Testing something</title>
    </head>
    <body>
    
    <center>
    
    <p>Please use this form to test if an INC can call itself.
    
    <!-- the "post" method keeps the information in the form private instead of showing up in the URL -->
    <form action="includes/TEST.inc.php" method="post">
        <input type="text" name="initialText" placeholder="enter some text">
        <p><input type="checkbox" name="firstOption" value="1"><label for="firstOption"> option One</label>
        <p><input type="checkbox" name="secondOption" value="1"><label for="secondOption"> option Two</label>
        <p><input type="submit" name="initialSubmit" value="Let's Go!">
    </form>
    
    </center>
    </body>
    </html>

    After that, the user is shown a sort of "confirmation" of the information they entered, and they can make any last edits before they hit the "Final Selection!" button.

    <?php
    
    # takes me back to where the form was
    if (isset($_POST["takeMeBack"])) {
        header("location: ../TEST.php");
        exit();
    }
    
    # final pass, after the "Final Selection!" button is pressed
    if (isset($_POST["finalSubmit"])) {
        # insert some code here that uploads something, or adds something to a database now that everything has been confirmed
    
        echo "<center><p>The finalized values that were just submitted are as follows...<p>";
        echo "The text entered was... " . $_POST["finalText"] . "<p>";
        
        if (isset($_POST["firstOptionConfirm"])) {
            echo "Option 1 was selected.<p>";
        } else {
            echo "Option 1 was NOT selected.<p>";
        }
    
        if (isset($_POST["secondOptionConfirm"])) {
            echo "Option 2 was selected.<p>";
        } else {
            echo "Option 2 was NOT selected.<p>";
        }
    
        # go back to the very beginning
        echo '<form action="TEST.inc.php" method="post"><p>';
        echo '<p><input type="submit" name="takeMeBack" value="Ok thanks">';
        echo '</form></center>';
    }
    
    # first pass, after the Let's Go! button is pressed
    if (isset($_POST["initialSubmit"])) {
        # the initial submit was pressed
        echo "<center>The initial submit works!<p>";
    
        $option1 = "";
        $option2 = "";
    
        # was the first option selected?
        if (isset($_POST["firstOption"])) {
            # option 1 was selected
            echo "Option 1 was selected!<p>";
    
            # change option 1 to be true
            $option1 = " checked";
        }
    
        # was the second option selected?
        if (isset($_POST["secondOption"])) {
            # option 2 was selected
            echo "Option 2 was selected!<p>";
    
            # change option 2 to be true
            $option2 = " checked";
        }
    
    
        # create the confirmation form
        echo '<form action="TEST.inc.php" method="post"><p>';
        echo 'Please confirm your selections...<p>';
        echo '<input type="text" name="finalText" placeholder="enter some text" value="' . $_POST["initialText"] . '">';
        echo '<p><input type="checkbox" name="firstOptionConfirm" value="1"' . $option1 . '><label for="firstOptionConfirm"> please confirm option One</label>';
        echo '<p><input type="checkbox" name="secondOptionConfirm" value="1"' . $option2 . '><label for="secondOptionConfirm"> please confirm option Two</label>';
        echo '<p><input type="submit" name="finalSubmit" value="Final Selection!">';
        echo '</form></center>';
    }

    This also shows the user what was finally submitted, and then they can click the "Ok thanks" button after viewing what was just submitted, and it brings them back to the "front" php page again.

    Is it ok to do this sort of thing?

    8 Comments
    2024/05/19
    04:24 UTC

    2

    Problem with isset()

    Hi guys. Using php and html, I've created a form that links to a member area page when completed. But if the form isn't completed, the page should display an error message (such as "please complete the form"). In the php file I've written the following :

    if(isset($_POST["name"])){

    echo "Hi".$_POST["name"] ;

    } else {

    echo "Please complete the form";

    };

    For simplicity, the form only asks for the name. The name of input associated with the name is “name”. The problem is that whether the "name" input field is completed or not, the form always leads to the member page, where it just says "Hi". Could you explain me why ? I mean, shouldn't " isset($_POST["name"]" be "false" when the "name" input field is empty ? I know I can use "empty()", but I'd like to understand why it doesn't work this way. Thank you guys !

    10 Comments
    2024/05/19
    02:10 UTC

    4

    This is a dumb question.

    Date("l") is returning Sunday, it's Saturday. Ran the full code to give me date and time and it echos about 8 hours ahead. I'm very new, and this baffling me. Guessing it's something with my xxamp server. I'm working on something that will require date and time, and when I run it on the real server it may not matter. But if it happens there, I'd like to understand how to fix it.

    13 Comments
    2024/05/19
    01:42 UTC

    3

    Website .php file not updating in browser

    *SOLVED- answer at bottom* I've been working on my 1st PHP website making a simple login page. Everything has been going fine until yesterday where suddenly the php files stopped updating in the browser. If i load my webpage through local host it just shows me an old version. I can delete the content from the php file and it still shows me content on the browser.

    If I preview the website through dreamweaver on firefox, I can see the updated file. If I load it from localhost/myfile.php it shows me the old file.

    I'm using: Firefox, dreamweaver, XXAMP, mySQL and Apache.

    If I do ctrl+f5 no difference.

    Tried to change the php.ini file on Apache to ;opcache.enable = 0 , no difference.

    Tried deleting cache from Apache, mySQL, and localhost in my browser, no difference.

    Tried opening from a different browser, no difference.

    What is going on? This is so frustrating. I've probably spent hours messing around with code thinking I've done something wrong only to realise nothing is changing anyway. Now I've spent hours trying to figure how to just clear cookies essentially!? I'm not sure what to do now! I don't think I should have to start a whole new server or change file names! Please help!!!

    * update:

    i've checked the file names and they all add up. I've even made a new .php file, and tried to preview it through localhost and it's not working, giving me 404 not found.

    When I check Apache admin, I can see the directory does not show any updated files, or new ones i have created since this problem occured.

    Why is Apache not updating the directory now then?

    SOLVED: The issue seemed to be the directory was not updating its content. I just worked around it by changing the directory manually to my website folder not it's default setting.

    XXAMP> Apache> Admin> httpd.conf

    Ctrl F: DocumentRoot

    Change: DocumentRoot "C:/xampp/htdocs" to DocumentRoot "C:/wherever_your_website_is"

    Underneath that, change:

    <Directory "C:/xampp/htdocs"> to the same path as above.

    Thanks all for your help.

    8 Comments
    2024/05/18
    21:15 UTC

    2

    Why are network requests to my PHP app taking a minimum of 250ms for an empty page?

    I’m using my own PHP MVC with some other dependencies with composer.

    Cachegrind “.gz” file contents is here: https://pastebin.com/SiEcWpU0

    At a real loss.

    Thanks!

    26 Comments
    2024/05/18
    08:22 UTC

    2

    exif_read_data do not get lensid

    I try to use exif_read_data to read some exif tags, including the lensid or any other tag, which identify the used lens. But I could not find any reliable way to find the right tag.

    On the other hand, if I use exiftool -lensid, I get successfully the lens from the image file.

    Is there any way by using exif_read_data()? I don't want to use exec(exiftool).

    2 Comments
    2024/05/18
    06:30 UTC

    2

    Undefined variable 'followers' in laravel 11

    I'm implementing followers and following section in Laravel. But while I want to display the following and follow section in blade file, Undefined variable error 'followers' is showing at the blade file line no 2. Note that I am using Laravel 11. Here are my codes: UserController.php:

    private function getSharedData($user) { $currentlyFollowing = 0;

    if (auth()->check()) {
        $currentlyFollowing = Follow::where([['user_id', '=', auth()->user()->id], ['followeduser', '=', $user->id]])->count();
    }
    
    View::share('sharedData', ['currentlyFollowing' => $currentlyFollowing, 'avatar' => $user->avatar, 'username' => $user->username, 'postCount' => $user->posts()->count()]);

    }

    public function profile(User $user) { $this->getSharedData($user); return view('profile-posts', ['posts' => $user->posts()->latest()->get()]); }

    public function profileFollowers(User $user) { $this->getSharedData($user); $followers = $user->followers()->latest()->get(); return view('profile-posts', compact('followers')); }

    public function profileFollowing(User $user) { $this->getSharedData($user); $following = $user->followingTheseUsers()->latest()->get(); return view('profile-posts', compact('following'));

    } Model User.php:

    public function posts(){ return $this->hasMany(Post::class, 'user_id'); }

    public function followers() { return $this->hasMany(Follow::class, 'followeduser'); }

    public function followingTheseUsers() { return $this->hasMany(Follow::class, 'user_id'); } Model Follow.php:

    public function userDoingTheFollowing() { return $this->belongsTo(User::class, 'user_id'); }

    public function userBeingFollowed() { return $this->belongsTo(User::class, 'followeduser'); } Blade File profile-post.blade.php to show the values:

    <div class="list-group"> @foreach($followers as $follow) <a href="/profile/{{$follow->userDoingTheFollowing->username}}" class="list-group-item list-group-item-action"> <img class="avatar-tiny" src="{{$follow->userDoingTheFollowing->avatar}}" /> {{$follow->userDoingTheFollowing->username}} </a> @endforeach </div><div class="list-group"> @foreach($following as $follow) <a href="/profile/{{$follow->userDoingTheFollowing->username}}" class="list-group-item list-group-item-action"> <img class="avatar-tiny" src="{{$follow->userDoingTheFollowing->avatar}}" /> {{$follow->userDoingTheFollowing->username}} </a> @endforeach </div> Web.php:

    Route:: get('/profile-posts', [UserController::class, 'profileFollowers']); Route:: get('/profile-posts', [UserController::class, 'profileFollowing']);

    3 Comments
    2024/05/17
    23:20 UTC

    1

    How do you port your code to your server

    How do you guys do it? I have a bare metal server setup on my home server for my website. But I get compatibility issues with the SQL and having to use composer when its over there. And then reset up your catchpha keys are any other client side keys you need is an absolute headache.

    Not to mention when you dev a local environment. And you then need to changeless all the links over to your domain for email registration doing this every change gets frustrating. I'm mostly sat in my nano editor fixing it all lol 😆

    19 Comments
    2024/05/17
    18:08 UTC

    12

    I don't understand what "yield" is used for.

    Hi. Just started coding a week ago. I'm on php. In the course I'm taking, the author talks about generators and "yield" but explains very badly. I looked on the internet and didn't understand what "yield" was used for either. It seems to me that every time the sites present a program to explain what yield is for, the code could be written “more simply” using a loop "for" and " echo" for example (It's just an impression, I'm a beginner so I guess I'm totally wrong).

    Is this really useful for me right now? I mean, can I do without it in the early stages and come back to it when I've made some progress ? If not, do you have a video or web page that provides a “simple” explanation? Thank you guys !

    21 Comments
    2024/05/17
    15:08 UTC

    0

    I need help figuring out fixing this error in my PHP code.

    SOLVED: Thanks to u/benanamen, I simply switched this code:

    $sql = "UPDATE quality" .   
    "SET color = '$color', temperature = '$temperature', 'size = $size', weight = '$weight' " .   
    "WHERE id = $id";  

    To their revised code:

    $sql = "UPDATE quality 
                    SET 
                    color = '$color', 
                    temperature = '$temperature', 
                    size = '$size', 
                    weight = '$weight' 
                    WHERE id = $id";

    This is the error:

    Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= 'pale purple', temperature = '30c', 'size = small', weight = '250g' WHERE i...' at line 1 in D:\xampp\htdocs\produce\edit.php:62 Stack trace: #0 D:\xampp\htdocs\produce\edit.php(62): mysqli->query('UPDATE qualityS...') #1 {main} thrown in D:\xampp\htdocs\produce\edit.php on line 62

    This is line 62: $result = $connection->query($sql);
    You can find it in the code below, I even "marked" it, this code's function is to edit certain variables of a row in a table. The rows are:
    Color
    Temperature
    Size
    Weight

    I tried editing the size from "small" to "large" and the error came out. This code is actually copied from this video (but I changed certain variable names) because I'm currently learning SQL and HTML programming and I'm a student. I almost copied the code from the video down to a T but I guess there's still something I've glanced over. video

    Please note that I'm a learning student so I may not understand complex explanations but I'll try my best to understand them as best as I can.

    Also don't ask me why there's a bunch of '/' in the code where they shouldn't be. I directly copy pasted this from Visual Studio Code and the slashes appeared by themselves. There's too many of them so I didn't bother erasing them. Just know that they're not part of the actual code.

    <?php  
    $servername = "localhost";  
    $username = "root";  
    $password = "";  
    $database = "eggplant";  
      
    $connection = new mysqli($servername, $username, $password, $database);  
      
    $id = "";  
    $color = "";  
    $temperature = "";  
    $size = "";  
    $weight = "";  
      
    $errorMessage = "";  
    $successMessage = "";  
      
    if ( $_SERVER['REQUEST_METHOD'] == 'GET') {  
      
    if (!isset($\_GET\["id"\])) {  
    header("location:/index.php");  
    exit;  
    }  
      
    $id = $\_GET\["id"\];  
      
    $sql = "SELECT \* FROM quality WHERE id=$id";  
    $result = $connection->query($sql);  
    $row = $result->fetch\_assoc();  
      
    if (!$row) {  
    header("location:/index.php");  
    exit;  
    }  
      
    $color = $row\["color"\];  
    $temperature = $row\["temperature"\];  
    $size = $row\["size"\];  
    $weight = $row\["weight"\];  
      
    }  
    else {  
      
    $id = $\_POST\["id"\];  
    $color = $\_POST\["color"\];  
    $temperature = $\_POST\["temperature"\];  
    $size = $\_POST\["size"\];  
    $weight = $\_POST\["weight"\];  
      
      
    do {  
      
    if ( empty($id) || empty($color) || empty($temperature) || empty($size) || empty($weight)) {  
    $errorMessage = "All the fields are required";  
    break;  
    }    
      
      
    $sql = "UPDATE quality" .   
    "SET color = '$color', temperature = '$temperature', 'size = $size', weight = '$weight' " .   
    "WHERE id = $id";  
    $result = $connection->query($sql);  <- THIS IS LINE 61!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      
    if (!$result) {  
    $errorMessage = "Invalid query: " . $connection->error;  
    break;  
    }  
      
    $successMessage = "Produce updated correctly";  
      
    header("location:/index.php");  
    exit;  
      
    } while (false);  
    }  
    ?>  
    
    <!DOCTYPE html>  
    
    <html>  
    <head>  
    <meta charset="utf-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=edge">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">  
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>  
    <title>Eggplant Quality Checker</title>  
    </head>  
    <body>  
    <div class="container my-5">  
    <h2>New Eggplant</h2>  
    
    <?php  
    if ( !empty($errorMessage)) {  
    echo "  
    <div class='alert alert-warning alert-dismissible fade show' role='alert'>  
    <strong>$errorMessage</strong>  
    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>  
    </div>  
    ";  
    }  
    ?>  
    
    <form method="post">  
    <input type="hidden" name="id" value="<?php echo $id; ?>">  
    <div class="row mb-3">  
    <label class="col-sm-3 col-form-label">Color</label>  
    <div class="col-sm-6">  
    <input type="text" class="form-control" name="color" value="<?php echo $color; ?>">  
    </div>  
    </div>  
    <div class="row mb-3">  
    <label class="col-sm-3 col-form-label">Temperature</label>  
    <div class="col-sm-6">  
    <input type="text" class="form-control" name="temperature" value="<?php echo $temperature; ?>">  
    </div>  
    </div>  
    <div class="row mb-3">  
    <label class="col-sm-3 col-form-label">Size</label>  
    <div class="col-sm-6">  
    <input type="text" class="form-control" name="size" value="<?php echo $size; ?>">  
    </div>  
    </div>  
    <div class="row mb-3">  
    <label class="col-sm-3 col-form-label">Weight</label>  
    <div class="col-sm-6">  
    <input type="text" class="form-control" name="weight" value="<?php echo $weight; ?>">  
    </div>  
    </div>  
    
    <?php  
    if (!empty($successMessage)) {  
    echo "  
    <div class='row mb-3'>  
    <div class='offset-sm-3 col-sm-6'>  
    <div class='alert alert-success alert-dismissible fade show' role='alert'>  
    <strong>$successMessage</strong>  
    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>  
    </div>  
    </div>  
    </div>  
    ";  
    }  
    ?>  
    
    <div class="row mb-3">  
    <div class="offset-sm-3 col-sm-3 d-grid">  
    <button type="submit" class="btn btn-primary">SUBMIT</button>  
    </div>  
    <div class="col-sm-3 d-grid">  
    <a class="btn btn-outline-primary" href="/index.php" role="button">CANCEL</a>  
    </div>  
    </div>  
    </form>  
    </div>  
    </body>  
    </html>
    16 Comments
    2024/05/17
    03:05 UTC

    3

    Problem with function

    Hi. Could someone explain me why this program:

    function f($x,$y):float{

    echo $x + $y;

    };

    echo f(1.1,2.3);

    returns the result (3.4) but also an error message: Fatal error: Uncaught TypeError: f(): Return value must be of type float, none returned in C:\Xampp\htdocs\Test\test.php:12 Stack trace: #0 C:\Xampp\htdocs\Test\test.php(13): f(1.1, 2.3) #1 {main} thrown in C:\Xampp\htdocs\Test\test.php on line 12.

    When I define a variable $z=$x+$y and write "returns $z" at the end of the function, the problem is fixed but I don't understand why. Thank you guys !

    5 Comments
    2024/05/17
    00:36 UTC

    7

    For those of you on Windows, how have you set up your personal development environment?

    At work we're using Windows and our development process is to edit locally and push up to a remote dev server. After everything is good, we copy the code over into production.

    I would really like to get a more modern development practice. I'd like to be able to debug locally within PHP storm. I would also like to have git pull down code and push up and have a good solid PR process.

    Can someone give me some suggestions or pointers?

    24 Comments
    2024/05/16
    15:24 UTC

    3

    How to access non global variables in a nested scope

    Hopefully the title is clear enough. I'm currently writing a one-off script and I ran into a little issue that I don't quite get. A couple notes for clarification:

    • this is just a simplified version of more complex code that I'm doing
    • the $myArray value coming in from a JSON file
    • I'm aware that in the example, I can do the multiplication after the array_reduce but in the real code I can't
    • I'm also aware that this can be accomplished without array_reduce and using a callback, but since I started down this path I just want to make sure I understand scope correctly

    Given this nested array

        $myArray = [
        [
            "factor" => 10,
            "values"=>[1,3,5]
        ],
        [
            "factor" => 2,
            "values" => [2,4,6]
        ],
    ];

    if I wanted to add the values, and multiply each value by the "factor" value, I can do this:

        foreach($myArray as $vals) {
    
        $reduction = array_reduce($vals['values'], function($carry,$item) { 
            global $vals;
            $factor = $vals['factor'];
            return $carry += ($item * $factor);
        },0);
        echo "Reduction: " . $reduction . PHP_EOL;
    }

    This works, when I'm in the global scope. I need global to access $vals here.

    This just had me thinking, if I was going to need this functionality in a separate file, and wanted to create a function I could call, I'm not sure how I would do it. If I try this:

        function multiReduction(array $arr)
    {
        foreach($arr as $v) {            
            $reduction = array_reduce($v['values'], function($carry,$item) {
                global $v;
                $factor = $v['factor'];
                return $carry += ($item * $factor);
            },0);
    
            echo "Function Reduction: " . $reduction . PHP_EOL;
        }
    }

    and call it with multiReduction($myArray); I get an warning for trying to access an array offset on value of type null for the line $factor = $v['factor']; because global $v; is not valid here. I can't send it to the callback here, because that only accepts two parameters. Is there any way to access that value from within the callback?

    I know this seems like a lot for a little, I just want to make sure I understand this in case I ever run into a real issue with this in the future. Nearly all of my PHP Coding so far has been "scripting" within a global scope, with a few includes for functions I use throughout my app. I've never used callbacks in this way and when I ran into this, it just didn't behave how I expected.

    TIA for any help.

    8 Comments
    2024/05/15
    23:45 UTC

    2

    PHPUnit: Mock Class being used in Tested Method

    Edit:

    The solution is to use the ‘overload’ prefix

    Hi,

    How can I mock a class being used in a tested method?

    The class being used is from a library not being loaded when the unit tests are run. The method creates a new instance of the class, passing data through the constructor and setting a public property.

    I want to test my method creates the correct object, and the correct data is set on the object.

    Example library class:

    class LibraryResponse {
        public __construct(public array $data) {}
    }

    Example method being tested:

    namespace MyNamespace;
    use LibraryResponse;
    
    function methodToTest(): LibraryResponse {
        return new LibraryResponse([1, 2, 3]);
    }

    Example test (that is not working):

    $responseMock = Mockery::mock('LibraryResponse');
    $responseMock->shouldReceive('__construct')
        ->once()
        ->andSet('data', [1, 2, 3]);
    
    $response = methodToTest();
    static::assertInstanceOf('LibraryResponse', $response);
    static::assertIsArray($response->data, 'Response should be an array');
    static::assertEquals(3, count($response->data));

    The errors:

    Mockery\Exception\InvalidCountException: Method __construct(<Any Arguments>) from Mockery_4__LibraryResponse should be called exactly 1 times but called 0 times.

    or

    Undefined property: LibraryResponse::$data

    If I print the class names, they are different: Mockery_4__LibraryResponse on my mock, LibraryResponse within the method being tested.

    If I var_dump() them, $mockResponse looks how you would expect but the return value appears to be a plain object.

    Composer:

    "require-dev": {
        "phpunit/phpunit": "^9.5",
        "10up/wp_mock": "dev-trunk"
    },

    Thanks.

    8 Comments
    2024/05/15
    22:10 UTC

    0

    Guessing shows up before the answers are given

    <!DOCTYPE html>
    <html>
    <head>
    <title>Indovina il personaggio STEAM</title>
    </head>
    <body> <h1>Indovina il personaggio STEAM</h1> <p>Rispondi alle seguenti domande per indovinare il personaggio STEAM.</p> <form method="post"> <label>È vissuto prima del 1900?</label> <input type="radio" name="pre1900" value="yes"> Sì <input type="radio" name="pre1900" value="no"> No <br> <label>È nato in Italia?</label> <input type="radio" name="italian" value="yes"> Sì <input type="radio" name="italian" value="no"> No <br> <label>È stato uno scienziato?</label> <input type="radio" name="scientist" value="yes"> Sì <input type="radio" name="scientist" value="no"> No <br> <label>Ha vinto un premio Nobel?</label> <input type="radio" name="nobel" value="yes"> Sì <input type="radio" name="nobel" value="no"> No <br> <input type="submit" name="submit" value="Indovina"> </form> <?php // Processa le risposte dell'utente e determina il personaggio STEAM. $pre1900 = $_POST["pre1900"]; $italian = $_POST["italian"]; $scientist = $_POST["scientist"]; $nobel = $_POST["nobel"];
    if ($pre1900 == "yes") {
      if ($italian == "yes") {
        if ($scientist == "yes") {
          if ($nobel == "yes") {
            $character = "Galileo Galilei";
          } else {
            $character = "Leonardo da Vinci";
          }
        } else {
          $character = "Michelangelo";
        }
      } else {
        if ($scientist == "yes") {
          if ($nobel == "yes") {
            $character = "Isaac Newton";
          } else {
            $character = "Benjamin Franklin";
          }
        } else {
          $character = "George Washington";
        }
      }
    } else {
      if ($italian == "yes") {
        if ($scientist == "yes") {
          if ($nobel == "yes") {
            $character = "Enrico Fermi";
          } else {
            $character = "Alessandro Volta";
          }
        } else {
          $character = "Guglielmo Marconi";
        }
      } else {
        if ($scientist == "yes") {
          if ($nobel == "yes") {
            $character = "Albert Einstein";
          } else {
            $character = "Alexander Graham Bell";
          }
        } else {
          $character = "Thomas Edison";
        }
      }
    }
    
    // Visualizza il personaggio STEAM indovinato.
    if (submit == "Indovina") {
          echo "Il personaggio STEAM che hai indovinato è $character.";
          }
    } ?>
    </body>
    </html>

    Sorry for the dumb question (and for the foreign language). I've been making for a small project to train myself on html. It's a type of guess who game, but with historical characters, mostly scientists. The questions are yes/no, but that is not the problem. The problem is that it immediately shows "Il personaggio STEAM che hai indovinato è $character." before actually sending the answers. I tried fixing it with a condition and using an if, but it doesn't work. What is the problem and how should I fix it? The guys at r/HTML told me that the HTML part is fine

    37 Comments
    2024/05/15
    15:00 UTC

    2

    Generate token for specific db entry for user

    Hey so I want to do something like send a user an email with a link to a specific db entry let's say id=5. I also want to attach a token of sorts to the end of the url so that only the user who received the email can view and interact with that entry. So let's say I email you www.mysite.com?id=5+token=abcd. So i want you to only be able to see entry 5 when you have a valid token.  So not for authentication purposes, I'm using apache for that. Is it possible to do something like that? Is there some sort of module or something like that I can use?

    Thanks for any help!

    8 Comments
    2024/05/15
    14:26 UTC

    2

    I'm getting the Error Fatal error: Uncaught mysqli_sql_exception

    I am a newbie in PHP, so I wanted to code, but I got this Fatal error even after copying everything except values on the YouTube video. So, here is the video referense: *click*

    Full appeared error on Microsoft edge browser:

    Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''classmates' ('Name', 'LastName', 'Email', 'TelephoneNumber', 'Birthdate') VA...' at line 1 in C:\xampp\htdocs\Demo\connect.php:13 Stack trace: #0 C:\xampp\htdocs\Demo\connect.php(13): mysqli_query(Object(mysqli), 'INSERT INTO 'cl...') #1 {main} thrown in C:\xampp\htdocs\Demo\connect.php on line 13

    And here is my code:

    <?php
        if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
            $conn= mysqli_connect('localhost', 'root', '', 'classmates_data') or die("Connection Failed:" .mysqli_connect_error());
            if(isset($_POST['Name']) && isset($_POST['LastName']) && isset($_POST['Email']) && isset($_POST['TelephoneNumber']) && isset($_POST['Birthdate'])) {
                $Name= $_POST['Name'];
                $LastName= $_POST['LastName'];
                $Email= $_POST['Email'];
                $TelephoneNumber= $_POST['TelephoneNumber'];
                $Birthdate= $_POST['Birthdate'];
                
                $sql= "INSERT INTO 'classmates' ('Name', 'LastName', 'Email', 'TelephoneNumber', 'Birthdate') VALUES ('$Name', '$LastName', '$Email', '$TelephoneNumber', '$Birthdate')";
                
                $query = mysqli_query($conn, $sql);
                if($query) {
                    echo 'Entry Successfull';
                }
                else {
                    echo 'Error Occurred';
                }
            }
        }
    ?>
    7 Comments
    2024/05/15
    12:33 UTC

    0

    hello humans why is my update function not running

    problem solved thanks to u/Big-Dragonfly-3700

    // well all my crud function are working except update.php , yes chk it no typo all names are correct

    mysql database name php_practical_db

    UPDATE `php_practical_tbl` SET `id`='[value-1]',`NAME`='[value-2]',`EMAIL`='[value-3]',`PASSWORD`='[value-4]',`IMAGE`='[value-5]' WHERE 1

    unsolved code
    <!doctype html>
    <html lang="en">
        <head>
            <title>Title</title>
            <!-- Required meta tags -->
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
            <!-- Bootstrap CSS v5.2.1 -->
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"/>
        </head>
    <style>
         body{
            background-color:lightblue;
            
        }
        header{
            display: flex;
            justify-content: space-around;
        }
    </style>
        <body>
        <header>
            <div class="mt-3 mb-3 ">
            <a href="create.php"><button type="button" class="btn btn-primary"><h5>Home</h5></button></a>
            </div>
            <div class=" mt-3 mb-3">
            <a href="read.php"><button type="button" class="btn btn-primary"><h5>view</h5></button></a>
            </div>
            </header>
           <?php
           include("connect.php");
           $id = $_GET['id'];
           $que = "select * from php_practical_tbl where id= $id ";
           $query = mysqli_query($con,$que);
           $run = mysqli_fetch_array($query);
           ?>
           <div class="container mt-4 justify-content-center">
            <form action="" class="border border-primary border-2 rounded-2 bg-light" method ="post" enctype=multipart/form-data>
                <input name="name" type="text" placeholder="Enter Your Name" class="form-control        mt-3 w-50" value="<?php echo $run['NAME']?>">
                <input name="email" type="email" placeholder="Enter Your Email" class="form-control mt-3 w-50" value="<?php echo $run['EMAIL']?>">
                <input name="pass" type="password" placeholder="Enter Your Password" class="form-control mt-3 mb-3 w-50" value="<?php echo $run['PASSWORD']?>">
                <img src="<?php echo $run['IMAGE']?>" alt="" width="100">
                <input name="img" type="file" class="form-control mt-3 w-50">
                <button name="upd" type="submit"class="btn btn-primary mt-3 mb-3 "> Update Data</button>
            </form>
           </div>
           <?php
           if(isset($_POST['upd']))
           {
            $name = $_POST['name'];
            $email = $_POST['email'];
            $pass = $_POST['pass'];
            $image = $_FILES['img']['name'];
            $temp = $_FILES['img']['tmp_name'];
            $saveimg = 'images/';
            $locationsave = $saveimg.$image;
    
            if(move_uploaded_file($temp,$locationsave))
            {
                $upd = "update php_practical_tbl set NAME='$name',EMAIL='$email',PASSWORD='$pass',IMAGE='$locationsave' WHERE id = '$id'";
                $run = mysqli_query($con,$upd);
            }
    
           }
           ?>
            <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"
    crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
        </body>
    </html>
    
    solved code
    different mysql db all col name small letters
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Title</title>
        <!-- Bootstrap CSS v5.2.1 -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"/>
        <style>
            body {
                background-color: lightblue;
            }
            header {
                display: flex;
                justify-content: space-around;
            }
        </style>
    </head>
    <body>
        <header>
            <div class="mt-3 mb-3">
                <a href="create.php"><button type="button" class="btn btn-primary"><h5>Home</h5></button></a>
            </div>
            <div class="mt-3 mb-3">
                <a href="read.php"><button type="button" class="btn btn-primary"><h5>View</h5></button></a>
            </div>
        </header>
    
        <?php
    
        // Include database connection
        include("connect.php");
    
        // Function to sanitize input data
        function sanitizeInput($data) {
            return htmlspecialchars(stripslashes(trim($data)));
        }
    
        // Check if form submitted via POST method
         if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
            // Validate and sanitize form inputs
            $name = sanitizeInput($_POST['name']);
            $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ?  
            sanitizeInput($_POST['email']) : '';
            $pass = sanitizeInput($_POST['pass']);
    
            // Handle image upload
            if ($_FILES['img']['error'] === UPLOAD_ERR_OK) {
                // Handle file upload
                $image = $_FILES['img']['name'];
                $temp = $_FILES['img']['tmp_name'];
                $saveimg = 'images/';
                $locationsave = $saveimg . $image;
            }
    
            // Prepare update query
            $upd = "UPDATE `php_practical_tbl` SET `name`=?, `email`=?, `password`=?, `image`=? WHERE `id`=?";
            $stmt = mysqli_prepare($con, $upd);
    
            // Bind parameters
            mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $pass, $locationsave, $_GET['id']);
    
            // Execute query
            mysqli_stmt_execute($stmt);
    
            // Close statement and connection
            mysqli_stmt_close($stmt);
         }
        ?>
    
        <div class="container mt-4 justify-content-center">
            <?php
            // Retrieve existing data from database
    
            $id = $_GET['id'];
            $que = "SELECT * FROM php_practical_tbl WHERE id= $id";
            $query = mysqli_query($con, $que);
            $run = mysqli_fetch_array($query);
            ?>
      <form action="" class="border border-primary border-2 rounded-2 bg-light" method="post" enctype="multipart/form-data">
      <input name="name" type="text" placeholder="Enter Your Name" class="form-control mt-3 w-50" value="<?php echo $run['name']?>">
      <input name="email" type="email" placeholder="Enter Your Email" class="form-control mt-3 w-50" value="<?php echo $run['email']?>">
      <input name="pass" type="password" placeholder="Enter Your Password" class="form-control mt-3 mb-3 w-50" value="<?php echo $run['password']?>">
      <img src="<?php echo  $run['image']?>" alt="image" width="100">
      <input name="img" type="file" class="form-control mt-3 w-50">
      <button name="upd" type="submit" class="btn btn-primary mt-3 mb-3">Update Data</button>
            </form>
        </div>
    
        <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
    </body>
    </html>
    
    
    
    7 Comments
    2024/05/15
    05:32 UTC

    1

    Possible bug in PHP itself? All properties of object are deleted after comparison (===) is called.

    I am running into a REALLY odd issue, and my best guess is that it's a bug within PHP itself. When comparing (===) the value of a property on one object with the value of a property on another object, all the values of the properties on one of the objects are deleted.

    • PHP 8.3.2-1+0~20240120.16+debian11~1.gbpb43448
    • Laravel Framework 11.4.0
    • mySQL 8.0.33-0ubuntu0.20.04.2

    From the top

    I'm editing a Post model, and running the update method on form submit

    Routing

    Route-model binding works as expected, and the correct controller method is called.

    Route::patch('/posts/{id}/update', [PostController::class, 'update'])
        ->name('post.update');

    PostController@update

    public function update(UpdatePostRequest $request, Post $post) :RedirectResponse
    {
       	// A quick test here that will become relevant in a moment
       	// dd(request()->user()->id === $post->user_id); // true
    
        // Results in 403
        if (request()->user()->cannot('edit', $post)) 
            abort(403);
        .
        .
        .
    }

    PostPolicy@edit

    The cannot() method will call the PostPolicy class to check if the user can "edit" the $post. The if statement is false despite the fact that the values being compared are identical.

    /**
     * Determine if "$user" can perform "edit" on "$post"
     */
    public function edit(User $user, Post $post) :bool
    {
        if ($post->user_id === $user->id) {
    	    // Expecting this to return
            return $user->can('edit.own_posts');
        }
        else{
    	    // Always gets returned
    	    return $user->can('edit.posts');
        }
    }

    Note: I have verified all roles and permissions are properly assigned, although that isn't really relevant to the issue I'm seeing.

    The Problem

    In the above function, checking the value of $user and $post BEFORE the if statement yields exactly the values that are expected ... $post->user_id is strictly equal (===) to $user->id.

    However, checking the value of $post from within the if statement block, reveals that all the properties on $post are empty. They all just disappeared.

    Here are the results of various dd() (dump() and die()) calls.

    public function edit(User $user, Post $post) :bool
    {
        dd($user->id);					    // int 112
        dd($post->user_id); 				// int 112
        dd($user->id == $post->user_id);	// true
        dd($user->id === $post->user_id);	// true
    
        // What if accessing the property is what causes it to become null?
        // Let's dump it twice.
        dd($post->user_id, $post->user_id)	// int 112, int 112
    
        // After the comparison, all properties of 
        // $post are empty                           	
        if ($post->user_id === $user->id) {
    
            return $user->can('edit.own_posts');
        }
        else{
    	    dd($user->id);				        // int 112
            dd($post->user_id); 			    // null
            dd($user->id == $post->user_id);	// false
            dd($user->id === $post->user_id);   // false
                                         	
    	    return $user->can('edit.posts');
        }
    }

    It Gets Weirder

    This one is really throwing me off. If, and only if, I place a dd() inside the if block, it will execute as if the comparison resulted in true, but will not execute if I remove the dd().

    public function edit(User $user, Post $post) :bool
    {
        if ($post->user_id === $user->id) {
    	
    	    // This line executes when present. Removing it will cause
    	    // the `else` block to execute.
    	    dd($user->id, $post->user_id);		// int 112, null
    	
            return $user->can('edit.own_posts');
        }
        else{
    	    // This line only executes if you remove the dd() above
    	    return $user->can('edit.posts');
        }
    }

    No matter what I do, the second return statement is the only one I can get to execute. But just for fun, let's try inverting the logic.

    public function edit(User $user, Post $post) :bool
    {
        if ($post->user_id !== $user->id) {
    	    // Always executes
            return $user->can('edit.posts');
        }
        else{
    	    return $user->can('edit.own_posts');
        }
    }

    For visual reference, here is the dd($post) result before the comparison call.

    https://i.sstatic.net/gzA8RkIz.png

    And here it is again called from within the if block.

    https://i.sstatic.net/4aYluG9L.png

    Has anyone ever seen anything like this before, or have any ideas what could be causing it? Thanks in advance for your help.

    14 Comments
    2024/05/15
    05:10 UTC

    1

    Is there a tool like Codepen for PHP where I can embed the code alongside the rendered result?

    Hello friends,

    I'm trying to write case studies for PHP projects on my personal website (built with 11ty SSG). For past case studies that were only HTML, CSS and JS I would use Codepen to show examples with the code side-by-side with the rendered result.

    So... my questions is: Is there something like Codepen for PHP? Where I can display the code alongside the rendered result and embed on my personal website?

    Thank you!

    10 Comments
    2024/05/14
    15:59 UTC

    0

    Please help me

    How to solve this kind of error?

    Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''login' (name,email,password) VALUES (','...' at line 1 in C:\xampp\htdocs\login\Signup.php:18 Stack trace: #0 C:\xampp\htdocs\login\Signup.php(18): mysqli_query(Object(mysqli), 'INSERT INTO 'lo...') #1 {main} thrown in C:\xampp\htdocs\login\Signup.php on line 18

    8 Comments
    2024/05/14
    11:52 UTC

    0

    Is it Possible to Force a SQL Pulled String Displayed in FPDF to have Different Sizing to Another String in the Same Double Quotes/Cell?

    Context

    This project is for an invoice application that generates a pdf from a button click. Its plain and simple, approched with the MVP concept. Over time, I did add a few details but they do not interfere with the PDF generation.

    My Tool Belt

    The tools I've used for R&D are:

    • M1 with Sonoma 14.3.1,
    • Visual Studio Code Version: 1.89.1 (Universal),
    • Latest PHP version (8.2),
    • FPDF (1.86),
    • Latest MySQL (8.X),
    • Brave, FireFox and Safari (Latest Version),
    • Perplexity AI (GPT 3.5)

    Problem

    In the latest FPDF version, I want to change the words thats coming from a MySQL database to be bigger in size AND displayed in the same CELL. This means displaying the following:

    <?php
      include('PATH/TO/FPDF');
    
      class PDF extends FPDF 
      {
        function Info($data) {
          $this->Cell(190, 5, "NAME:       " . $data['name'], "B", 0, "L");
        }
      }
    ?>

    where the name column (from MySQL), should be bigger in font size than "NAME: " in the output.

    What I Tried

    I've used the following methods (from FPDF), with no success:

    1. MultiCell
    2. SetFont
    3. GetY
    4. GetX
    5. Ln
    6. SetFontSize
    7. SetX
    8. SetY
    9. SetXY
    10. Write

    Yes, I did look on StackOverFlow and Googled it, and as similar as the titles are to solving my problem, they do not provide the actual solution. I also verfied just now if there are any answers out there to answer my question as my last chance. There are none :( . I need to make the data from MySQL bigger like in the PDF from Acrobat where you're filling out a form. Imagine filling out a PDF form for the goverment or scholarships, they make the user inputs bigger that the hard-coded string.

    The mentioned methods used were also the ones I've implemented to solve this problem. I've used many more methods that aren't mentioned, and they obviously lead to nowhere.

    What I Got

    I am currently stuck on the Cell method and from researching article, youtube videos and blog posts, have gotten no where near to my goal.

    Quick Review

    Heres the documentation:

    14 Comments
    2024/05/14
    04:35 UTC

    5

    What Controller package do you use when rolling your own small framework?

    Long ago I made a small project that combined Idiorm ORM, Paris Active Record ( https://j4mie.github.io/idiormandparis/ ), Klein router+template system ( https://github.com/klein/klein.php ), and various components from The PHP League ( https://thephpleague.com/#packages ). I remember not being able to find any kind of pre-made controller class popular with the community. Is there one?

    4 Comments
    2024/05/14
    03:01 UTC

    1

    Could you show me some psudo-code for how to an advanced search form with lots of options?

    I've got this old php5 project using mysql_* functions.

    99% of the project could be easily ported to some kind of small/minimal framework (front controller, routes, template system, models) but the advanced search form just literally glues together optional fragments of sql query text and I'm having trouble imagining how to evolve that to use a framework's query classes or the PDO in php. Does anyone have an example they could point me to or even just a simplified outline of what they code would work/look like with make believe example code?

    13 Comments
    2024/05/13
    22:06 UTC

    Back To Top