r/PHPhelp • • Aug 31 '22

When to use LDAP?

7 Upvotes

Hey everyone,

My buddy and I are working on a project, he's more of an IT solutions guy and I'm a programmer/designer. The app we're building has a user registration system and the app also enables them to upload files. We would like to host the application on our own servers, that's where his role comes into play.

He came back to me suggesting we utilize Active Directory or LDAP whereas I already started building everything in MySql. After digging into Active Directory/LDAP, I must admit that it seems like a nice package but is it secure, safe & supported? Are these technologies better served in certain environments than others? Are thee any advantages for using LDAP overa SQL database to manage user credentials/authentication in addition to storing files? If we use LDAP for those things, would I be better off writing the entirety of my DB schema in LDAP or does a hybrid with MySql make sense?

Appreciate any insight - I'm a hobbyist PHP dev who works professionally in other languages so some of these more nuanced topics aren't as familiar to me.

Thanks!


r/PHPhelp • • Jun 28 '22

Solved "foreach" in PHP 8

7 Upvotes

Hi all,

today i wanted to change the PHP version, because joomla told me that version 7.4 is no longer supported. So i changed to PHP 8. Joomla is still running fine.

Unfortunately my hoster does not support different versions for different subdomains. So, another small script that i need, does not run anymore with PHP 8.
Error 500.
I walked through the code line for line and found that the script stops at this lines:
$zusatzfelder = "";

foreach($preset[zusatzfeld] as $key => $value){

$zusatzfelder .= "<input type='text' value='" .$value ."' name='zusatzfeld[" .$key ."]'>";

}

Any ideas why this will not work anymore?

Thanks Tom


r/PHPhelp • • May 16 '22

Where do you all go for freelance work?

7 Upvotes

I'm looking at Fiverr for PHP related stuff, but it seems kinda cheap, not sure if those are good prices or not that I should be asking.

Mainly looking into WordPress, PHP scripts, editing, creating scripts.


r/PHPhelp • • Apr 06 '22

Friendly URLs

7 Upvotes

Hey PHP Fam!

I'm wracking my brain trying to figure this out. I have a page that has this URL format:

/project/info/index.php?project_id=d98d8500-251a-11eb-acef-d7bbefd9f4d9

and i'd like the following URL format to work:
/project/info/d98d8500-251a-11eb-acef-d7bbefd9f4d9

This might be more of an htaccess question than a PHP question (or both?)

Any tips would be greatly appreciated!!!!


r/PHPhelp • • Feb 27 '22

Solved Hi! i'm new to laravel and I have a few questions regarding routing, type-hints, and route control groups and others. Please help!

7 Upvotes

Here's what I learned so far regarding the different syntaxes for writing routes:

Syntax 1: *simple get without passing any parameters.

Route::get('/users', 'App\Http\Controllers\UserController@getUsers');

Syntax 2: *simple get but with a some kind of anonymous function

Route::get('/users', function () {
    //How do I specify that i'm trying to call the getUsers function here? cause this uses an anonymous function 
    //because unlike syntax 1 and 4, the getUsers function is not specified in this syntax.
});

Syntax 3: *get request with type-hint/dependency injection as specified here: https://laravel.com/docs/9.x/routing#dependency-injection

Route::get('/users', function (GetUser $request) {
    //How do I call the getUsers function here? 
    //because unlike syntax 1 and 4, the getUsers function is not specified in this syntax.
});

Syntax 4:

Route::get('/users', [UserController::class, 'getUsers']);
//How do I use type hint here? Is it possible to specify here that
//the getUsers function requires a GetUser FormRequest same way with syntax 3?

Syntax 5: *I prefer to use this one because our project will be having a ton controllers but I don't know how to use type-hints/dependency injection here.

Route::controller(UserController::class)->group(function () {
    Route::get('/users', 'getUsers');
    //how do I use type-hints here same as syntax 3.
});

As you can see I'm having trouble understanding the different syntaxes.

What I'm trying to do is to write a route that:

  1. defines the function to be called like syntax 4 and 5.

  2. Must use type-hints

  3. Must be inside a route control group.

Please be patient with me I probably have the wrong mindset here or understanding of routes.


r/PHPhelp • • Nov 01 '21

Help noob to understand why 0 is ODD using switch statement and EVEN in if statement

7 Upvotes

Hello, can you please explain to me like i'm five, why switch statement behaves like this?

$num = 0;
if ($num % 2 == 0) {
echo 'Even';
} else echo 'Odd';

If statement returns 0 as Even, as it should be. But switch statement returns 0 as Odd

$num = 0;

switch ($num) {
case $num % 2 == 0:
echo 'Even';
break;
default:
echo 'Odd';
break;
}


r/PHPhelp • • Oct 28 '21

How do you read an array using its keys without a foreach loop?

7 Upvotes

I was trying to get some random elements out of an array and did the following:

$full_array = range(1,100);
shuffle($full_array);
$how_many = 10; //how many to pick
$picked = array_slice($full_array, 0, $how_many);
return $picked;

But that requires shuffling the entire array first, which can become highly inefficient if the full array is very large relative to the number picked. I then looked into array_rand() and don't know how to use its output (keys) without looping.

$full_array = range(1,100);
$how_many = 10;
$picked_keys = array_rand($full_array, $how_many); //10 random non-repeated keys
//I don't want below
$picked = [];
foreach ($picked_keys as $key) {
  array_push($picked, $full_array[$key]);
}
return $picked;

Is there a function like array_foo($full_array, $picked_keys) that picks out the values of the provided keys (2nd arr param) from 1st arr param? So I can do without that loop.


r/PHPhelp • • Oct 12 '21

Solved Beginner PHP

7 Upvotes

Hey guys,

So I tried to make a code which generates a random number then the user has to guess a number then the code tells the user if the randomly generated number is lower or higher.

And there is one more button where the user can generate a new random number but I get an error which says " Undefined variable $rand".

I tried to make this code in a session but I couldn't do it because it always said in the end " array(1) { ["random"]=> int(89) }", that's why I have the var_dump in the end.

I'm just confused how to do it.

<FORM name="form1" method="POST" action="játék.php">

Random <INPUT type="text" name="random"><BR>
<INPUT type="submit" name="submit" value="Submit"><BR>
<INPUT type="submit" name="roll" value="Random number generator"><BR>

</FORM>


<?php
session_start();

if (isset($_POST['roll'])) {
	$rand = rand(1, 100);
	echo $rand.'<BR>';
}	elseif ($_POST['random'] > $rand) {
		echo 'Lower';
	} 	elseif ($_POST['random'] == $rand){
		echo 'Bingo!';
	} else {
		echo 'Higher';	
	}

echo '<PRE>';
var_dump($_SESSION);
echo '<PRE>';
?>

r/PHPhelp • • Sep 17 '21

Making PHP more secure

7 Upvotes

For example a blog website. Is there a way to delete a certain blog that won't need to put a hidden input field containing the id of that blog?

For example:

<form> <input type="hidden" value="<?= $blogId; ?>"> (This is the part I want to remove from my code) <button>Delete</button </form>

On some programming languages such as nodejs, there is no need to do that. Thats why Im asking here if there is also a way in PHP to not do that.

EDIT: Thank you to everybody that answered my question.


r/PHPhelp • • Sep 15 '21

Looking for non leet code style test for senior position...

7 Upvotes

Anyone have any experience or recommendations with an online assessment for senior devs that will test relevant real world skills and not leet code solving capabilities? It's not that I have anything against those - I play around with them for fun in my spare time. I'm just not a fan of using them for weeding out applicants.


r/PHPhelp • • Sep 12 '21

Solved Error Running a Simple SQL Query with PHP

7 Upvotes

Hello,

I am trying to run a very simple query, but I can't quite seem to get it to work. I have tried several variations of StackOverflow answers, but nothing displays beyond my simple "Connected Successfully" echo statement. I am trying to display the query on a webpage at the moment, but eventually I want to display it on a leaderboard through Unity.

Does anyone know what's wrong? Thank you to everyone in advance

$database = 'database';

$username = 'username';

$hostname = 'hostname';

$password = 'password';

// checking connectivity

$con = mysqli_connect($hostname,$username,$password,$database);

if (mysqli_connect_errno()) {

echo "Failed to connect to MySQL: " . mysqli_connect_error();

exit();

}

else {

echo " Connected Successfully ";

}

// running query

$query = "SELECT * FROM TestScores";

if ($result = $mysqli->query($query)) {

while ($row = $result->fetch_assoc()) {

$field1name = $row["col1"];

$field2name = $row["col2"];

echo $field1name;

}

}

Here is another variation I tried to no success:

$sql="Select * from TestScores";

$result=mysql_query($sql) or die(mysql_error());

while($myrow=MySQL_fetch_array($result,MYSQL_ASSOC))

{

extract($myrow);

echo "<td align='left' bgcolor='black'>".$myrow[0]."</td>";

echo "<td align='left' bgcolor='black'>".$myrow[1]."</td>";

}

Thank you


r/PHPhelp • • Sep 03 '21

Solved How do I add PHP to a static HTML site to pull the header and footer to each page?

7 Upvotes

I am rebuilding my website as a static html site, but I would like to pull my header and footer into the pages with PHP the way WordPress does. What would that code look like in a non-WP site? When I Google it I only get WordPress related tuts.

Quick Solution: https://www.w3schools.com/php/php_includes.asp

Complex solution: see reply by hedrumsamongus


r/PHPhelp • • Aug 27 '21

Documentation

7 Upvotes

Every once in awhile I'll see the advice "document your code". What does this mean for a PHP programmer writing a small open source project? To make sure to use the "wiki" tab on GitHub? To make sure to use docblocks above each method?

Is it even worth adding docblocks? Don't @param, @return, etc. just duplicate what the top of the method (e.g. function myFunctionName(string $param1, bool $param2): array {) already tells us?

After one adds docblocks, what is the next step, run some kind of software that turns the docblocks into an HTML website?


r/PHPhelp • • Jul 30 '21

Using PHP To Print A MySQL Table to an HTML Page

7 Upvotes

Hello everyone! I'm trying to use PHP to print a MySQL table to an HTML page. When I run the website, it prints the header of the table but none of the MySQL information. I know that the PHP code is definitely connecting to the database successfully. It's not outputting any errors. If anyone can help, that'd be very appreciated.

PHP (to print the table): https://pastebin.com/GBnJGSUt

HTML: https://pastebin.com/PeEZ2P0e

PHP (to connect to the database): https://pastebin.com/HUVkdrGh

HTML Output: https://gyazo.com/1d6ace8be3a6e56d125cf1a00d513d84


r/PHPhelp • • Jul 28 '21

Looking for php learners chat/group

7 Upvotes

Hey! I’m learning PHP and it would be so helpful to join a chat where people share their progress or just find someone who’s interested in programming too. If you are looking for a learning partner or know any php chats, please help me.

P.S. hope your code works well today!


r/PHPhelp • • May 25 '21

What are things I should request from the previous developer when doing a PHP code base handover?

7 Upvotes

I’m relatively new to PHP development and have been stuck with a codebase transfer. Technically the previous developers had everything standing on the hosting server.

But one missed payment and the hosting service deleted the server entirely so now I have to get the website back up and running. I’m not sure entirely what I need to communicate to the previous devs what I need to get the website back up and running.


r/PHPhelp • • Mar 23 '21

I can't understand the PHP error system.

7 Upvotes

I am using the docker image php:7.4-fpm. I have managed to configure php-fpm even though most of the options I do not understand them.. Here is the configuration:

[global]
error_log = /var/log/php-fpm.log
daemonize = no
log_level = notice
log_limit = 8192
[www]
listen = 9000
clear_env = no
catch_workers_output = yes
decorate_workers_output = no
.....
....

I actually changed the configuration so that I send it to a file (/var/log/php-fpm.log) instead of sending it stdeer and stdout. So far so good.

Now I'm going with the PHP configuration, this is my configuration

php.ini
error_reporting = E_ALL 
display_errors = On 
log_errors = On ; 
; error_log = /var/log/php-errors.log

I have commented the error_log directive to know the behavior of this system, obviating the Syslog type because I don't want to go into that. I want to know what happens when you do not put anything in error_log, the documentation says that it is

errors are sent to the SAPI error logger

No idea what that is, but I searched with this explanation. https://stackoverflow.com/a/23286225/2046442,

In summary it says that it sends it to the parent system of the logs such as Apache or Nginx in my case, well that only see errors on the screen, how can I do to see it in Nginx or send it to another system like Monolog?

Nginx configuration

server{error_log /var/log/nginx/web_error.log;

access_log /var/log/nginx/web_access.log;

}

None of these files contain the PHP errors that I am causing.I do NOT know if you can help me to orient in the right path.


r/PHPhelp • • Dec 29 '20

question about mixing php and html

7 Upvotes

I currently have a php page set up that consists of mainly html codeI would like to have 1 php chunk dedicated to database queryingI would like to use the variables from that chunk in other php chunks in the same PHP file

example:

some html

<?php include "databasequery.php"; ?>

some html

<?php echo $queryvariable; ?>

some html

Is this an illegal move because it does seem to work, although my IDE doesn't appreciate it?


r/PHPhelp • • Dec 16 '20

I'm a PHP beginner and I have made a basic login system. Can you please review it and also help me assign the user's first name and last name to a SESSION variable? I highly appreciate your help

7 Upvotes

Hi

I am a PHP beginner and after some online research I have written the following login function. It works but I don't know if it's 100 fool-proof (I'm not using password_verify at the moment and the passwords aren't hashed or salted at the moment. I will implement that later).

I have the following columns in the table:

  • user_id

  • user_first_name

  • user_last_name

  • user_email

  • user_password

if (isset($_POST['login'])) {

    $email = htmlspecialchars($_POST['user_email']);
    $password = htmlspecialchars($_POST['user_password']);
    $conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

    function loginUser($conn, $email, $password) {

    $sql = "SELECT user_email from users WHERE user_email = ? AND user_password = ?";

    $stmt = mysqli_stmt_init($conn);

    if (!mysqli_stmt_prepare($stmt, $
        header("location: ../index.php?error=stmtfailed-7vjhv5");
        exit();
    }

    mysqli_stmt_bind_param($stmt, "ss", $email, $password);

    mysqli_stmt_execute($stmt);

    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) == 1) {
        session_start();

        $_SESSION["USER_LOGGED_IN"] = true;
        $_SESSION["EMAIL_ADDRESS"] = ?????;
            $_SESSION["FIRST_NAME"] = ?????;
        $_SESSION["LAST_NAME"] = ?????;

        mysqli_stmt_close($stmt);
        mysqli_close($conn);

        header('location: ../index.php');
    } else {
        header('location: ../login.php?error=invalid');
    exit();
    }
    }
}

What I need to know also is how to assign the user's email address, first name and last, to the $_SESSION variables?

Thank you so much


r/PHPhelp • • Nov 16 '20

Correct placeholder for NULL?

7 Upvotes

If I were to use a sprintf type of function where i would use %s for strings (for example), what would I use if I need to pass NULL?


r/PHPhelp • • Nov 13 '20

Solved Help to get PHP8 w/ xdebug in Docker on OSX running for local dev (phpunit) via PhpStorm in a checkout project

7 Upvotes

SOLVED

See https://www.reddit.com/r/PHPhelp/comments/jti8i2/help_to_get_php8_w_xdebug_in_docker_on_osx/gc7g8j5/?utm_source=reddit&utm_medium=web2x&context=3 for the summary

Thanks everyone!


I've never really used docker before and I'm hitting so many walls that I stopped counting, I think today (Friday 13th) is my lucky day.

What I currently have:

  • Host OSX

  • PHP 7.4 installed via brew

  • git clone of my project

  • phpunit tests are running, also inside PhpStorm

  • I can also debug, I've xdebug installed via pecl

What I'm trying to achieve:

  • same as above but with PHP 8 without replacing my brew PHP 7.4; this is intended only for local dev

  • I don't need webserver etc., just CLI

  • PHP 8.0 (e.g. the php:8.0.0RC4-cli image I guess?)

  • being able to install the composer dependencies via PHP within docker, important for package version resolving (this project will install different version on different PHP version to be compatible)

  • run phpunit (ideally also via PhpStorm)

  • super bonus: also get xdebug working in the docker image (probably need to add further install steps with pecl in Dockerfile?) so it also works via PhpStorm

In fact, I don't know how, I got it working that I can run phpunit and it runs it in the docker image; but I'm too stupid to figure out how to also run composer inside the image. I don't even know of composer is available in this image 🤷‍♀️

Dockerfile I have (don't laugh):

FROM php:8.0.0RC4-cli

ADD ./ /app

WORKDIR /app

Docker composer (because no idea, tutorials and stuff):

version: '3'

services:
    php:
        build: .
        volumes:
            - ./:/app
        working_dir: '/app'

I then did docker-compose build and the resulting image I selected in PhpStorm (remote interpreter) and managed to get phpunit running.

It "works" but the vendor files are still from my local host PHP composer installation and they contain incompatible code with PHP8 (e.g. classes like Match 💥), thus I need fix that but no idea (aka run composer in Docker with PHP 8).

Is anyone willing / has the energy and time to help me moving forward? Would be much appreciated :)

Thanks


r/PHPhelp • • Sep 13 '20

Does anyone know how to completely remove XAMPP from a computer running Windows 10?

7 Upvotes

Long story short XAMPP didn't work one day, I tried fixing it using recommended online methods appropriate to my situation, it only made it worse and now I just want to delete it and start over. I have tried getting rid of it (following online tutorials for this aswell) but it still remembers me and it keeps giving me the same errors. I have no time left for this and I just want to continue working on PHP.

So please if anyone can help me I would greatly appreciate it.


r/PHPhelp • • Aug 23 '20

How to loop this JSON object from php?

7 Upvotes

From my blade controller, i get this

$data = PageResult::make($result->answers);

return $data;

{"data":[             
            {                
                 "section":"Technology",                 
                 "weighting":"0.15",                          
                    "questions":[                                
                                  {
                                     "id":"1",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }, 
                                   {
                                     "id":"2",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }
                       ]
                },
                {                
                 "section":"Data",                 
                 "weighting":"0.15",                          
                    "questions":[                                
                                  {
                                     "id":"1",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }, 
                                   {
                                     "id":"2",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }
                       ]
                }
}

I want to loop through the jSON object, to get the weighting of each question, of each section i have tried something like this..

foreach ($data as $array) {        
    $sections = $array['section'];           
        foreach ($questions as $question) {                        
            $question = $section['questions']                 
         } 
}  

return view('save-results', ['weighting' => $weighting]); 

any ideas?


r/PHPhelp • • Aug 19 '20

Stuck on "Very Easy" PHP challenge on Edabit. What am I overlooking?

7 Upvotes

Hello PHPHelp community, I'm a total n00b to PHP and programming in general. I am using Edabit.com to sort get the basics down and I am working my way through the (very) easy challenges. I'm doing well on the math challenges but I am stuck on this string one:

https://edabit.com/challenge/RTEiB6WTEPwjfvF9o

It says

Write a function that returns the string

"something"

joined with a space

" "

and the given argument

a

So I write this code but fail the check. I know I'm overlooking something very basic.

function giveMeSomething($a) {

`echo "something" . " " . "$a";`	

`return true;`

}

Every code needs to end with "return true;". Thank you in advance for any input!