r/PHPhelp • • Aug 27 '17

How do you read this?

7 Upvotes

isset($_POST['name']) ? $_POST['name'] : null;


r/PHPhelp • • Aug 19 '17

Code Review: Login form

7 Upvotes

Working to expand my PHP skills and move to more advanced development.

Here is an experiment I did with regards to a login form where instead of using a username in addition to a password, it is set up where the site will send a randomized authorization token upon successful matching of the email address $admin_email.

The code works as intended but wanted to know if the code has any flaws that would make it vulnerable on a production environment.

https://pastebin.com/uDnrnhTr

Thanks in advance!


r/PHPhelp • • Jun 09 '17

How to store & process data for "collectors"

7 Upvotes

I'm building a site for collection trading. Let's use baseball cards as an example. I'm not entirely sure how to structure the data or process it. I've been away from coding for a while so I'm a bit rusty. Ideally, the user would have a list of what the have for trade and what they want. My original idea is to have a table for users and a table for cards. Users would have a field like "CardsHave" that would be a CSV field that references IDs from the cards table. Then I'd have PHP process that CSV field as an array and loop through it to display details for the cards they have. Is there a better way to do that? What would you do?


r/PHPhelp • • Jun 02 '17

PHP 5 Website Updating to PHP 7 - 500 Internal Server Error

7 Upvotes

Total PHP newb here, and learning more daily, but an old friend who is no longer accessible helped make a site for me many years ago, back in the PHP 5 days, and now after PHP 7 is out and 5 is losing support, I was forced to update to PHP 7 for some of my other sites on the shared hosting, but now that one old site is completely broken and I was wondering if anyone might be able to help me out with getting it running again on PHP 7. :( Thanks in advanced for anyone willing to help.


r/PHPhelp • • Feb 24 '17

Solved What would the TWIG equivalent of <?php the_field('field_name'); ?> be?

7 Upvotes

Newbie question: I'm using Wordpress with the "Advanced Custom Fields" plugin, and I'm trying to call variables from the plugin into my TWIG file.

The documentation for the plugin says to use <?php the_field('field_name'); ?> in the PHP, but I can't figure out how to translate that code to TWIG.

  • I tried the code as is, but it appears TWIG doesn't run pure PHP.

  • I tried {% post.the_field('my_fields_name') %}, but to no avail

  • I also tried {{ post.my_fields_name }}, but it printed/logged "Array" to the frontend.

Any help is greatly appreciated


r/PHPhelp • • Feb 11 '17

Confused about arrays

7 Upvotes

I am trying to pull data from a database and store it in an array The structure of the array that I want is this: array[index of array][key][value]

So I need many indexes, many keys, and one value assigned to each key.

For example:

array1[0]["A"]["apple"] array1[0]["B"]["banana"] array1[0]["C"]["coconut"]

array1[1]["A"]["all"] array1[1]["B"]["bongo"] array1[1]["C"]["cart"]

As I loop through the rows of information in the database, I want to assign each row an index in the array, and each column header in the database as the key in the array and then the values from each row in the database to the value associated to it's corresponding column in the database (and key in the array).

I've been struggling with this concept all day and I'm just confused now - Can anyone explain how I can do this? It doesn't need to be efficient - I am basically just doing it for a single use purpose. I know this is possible in javascript

One other point is that as I am creating the array, I am using logic to determine if I will be creating a row so the number of rows in the database are going to be a lot more than the size of my array.


r/PHPhelp • • Jan 27 '17

Apache using wrong version of PHP on Mac

7 Upvotes

I'm trying to get Laravel going locally on a Mac with PHP and Apache.

I started with PHP version 5.5, and upgraded to 5.6, because for some reason PHP 5.5 wouldn't play nice with Laravel. Some sort of infinite loop dependency autoloading.

I upgraded PHP versions and got to where it was carping about that, and am now stuck trying to get Apache to use PHP.

phpinfo() gives PHP Version 5.5.30

php -v in terminal gives PHP 5.6.29 (cli) (built: Jan 14 2017 21:05:20)

So, the problem is, 5.6 is installed, but Apache is still using 5.5.

I tried updating the httpd.conf file to no avail (ServerRoot defined):

LoadModule php5_module libexec/apache2/libphp5.so

I tried to update entropy-php.conf, also to no avail.

LoadModule php5_module /usr/libexec/apache2/libphp5.so

Sometimes if I have both these lines going, I'll get this warning. So I can only have one or the other, but don't know which.

[Tue Jan 24 20:13:27.285064 2017] [so:warn] [pid 19843] AH01574: module php5_module is already loaded, skipping

I can't seem to make Apache use the newest version of PHP. I've searched all over, for different variations of updating symlinks, like so:

me$ ls -l
lrwxr-xr-x   1 me  admin     38 Jan 24 19:56 php5 -> /usr/local/php5-5.6.29-20170114-210819
drwxr-xr-x  14 root  wheel    476 Jan 23 20:08 php5-5.6.29-20170114-210819

Commenting out and uncommenting lines, and pointing to different versions of libphp5.so, to no avail. So, any help would be appreciated.

Thanks!


r/PHPhelp • • Jan 16 '17

My "User" class

7 Upvotes

Can I ask for a critique of this class I've written?

http://pastebin.com/BgKTyb6i

Bunch of functions, I'll explain:

User creates an account on the login form which just asks for email address, password, and to verify that password ($email, $password and $verify).

That all gets passed to the validateUser() function, which spits out a true or false after checking if the email address is acceptable (after sanitizing it and validating it), unique, whether the password and verification match, and if the password is over a certain number of digits long (6 for now, but i'll make that bigger).

If all of those pass, we then:

run the email through the sanitize and verify again, hash the password, create a UUID and put that all in the database with the createUser function.

I sanitize and validate the email a second time because the first function only returns true or false, nothing else.

Once that occurs, I select the UUID from the database based on the email address that was just inserted (getUserValidationKey()), and send email that to that same address (using PHPMailer).

Finally, the recipient receives that email with a link to activate.php?key=xxxxx - xxxx is the $uuid I sent them - if that UUID exists then the user becomes activated by calling the activateUserByKey() function.

Of course, I think I've done this alright. All the database interactions are done with parameters and prepared statements. The UUID is seeded with a random string from OpenSSL. And I am ASSSUMING that people won't be able to cram garbage into the email address field to turn my machine into a spammer thanks to it refusing to proceed if the email address isn't valid.

On thing I noticed is if someone puts a (space) in an email address, the validation function removes it. I think that's acceptable, probably a typo. And if it was a typo and gets sent to the wrong address, they'll just get one email by mistake.

So... Any suggestions? Particularly nervous since this is sending emails, but any other suggestions would be great.

Or.... Is it finally time to scrap standard PHP and move to a framework?


r/PHPhelp • • Dec 10 '16

simple array reference (&) confusion

7 Upvotes

Can someone explain this to me?
I figured it out, but it might be helpful / refresher for others.

$myArray = array(
	'sub' => array( 'foo' => 'bar' ),
);
$sub = &$myArray['sub'];   // this is the only assignment by reference
                           // both sides become references.. not to each other, but to the value
$copy = $myArray;
$copy['sub']['foo'] = 'WTF';
var_dump($myArray);

Why do $myArray['sub'] and $copy['sub'] point to the same place?
ie, why does the above output array(1) { ["sub"]=> &array(1) { ["foo"]=> string(3) "WTF" } }

The relevant PHP documentation: What references do:

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments.

I can't believe I've never run into this "issue" before / can't believe my understanding of php references has been so flawed..

by assigning by reference $sub = &$myArray['sub'], both sides of the operator become references, not to each other, but to "location c", where the value is actually stored)
That reference gets copied when the array is copied.

SHAZBOT


r/PHPhelp • • Oct 24 '16

Solved Am I vulnerable?

7 Upvotes

Hi there,

I just finished preparing my registration page with PDO, and wanted to make sure that I am not vulnerable to SQL Injection. If someone could look over what I have here: http://pastie.org/10949079 it would be much appreciated. I think (hopefully) that I am good, but would like a second opinion.

Thanks!


r/PHPhelp • • Oct 05 '16

PHP OOP. When and Why?

7 Upvotes

Ok, so I just have a question regarding object oriented programming that I have been pondering for the better part of the last few days.

I'm currently working on a personal project that essentially involves reverse engineering a website to create essentially a clone that I can use for a private server of a game. I know it sounds incredibly strange but it's a long story as to why I'm doing it and it basically boils down to me being bored, and now I intend to finish it as a challenge in my free time. Anyhow, basically I know how every aspect of the site functions, which pages call which and how (it uses AngularJS and handles most I/O using JSON). So, piece by piece I've been rebuilding the back end of each aspect of the site to function how they do on the real thing (login, registration, user settings, etc) and I actually have probably 75% of the site functional.

This is where the question comes into play. I've designed each back end file separately and procedurally, however, reading a documentation online for various aspects of PHP has shown me that a vast majority of projects are done in the OOP style and not procedurally. Now, I'm totally new to OOP (I'm in my 3rd of year of a CS degree) but a ton of the examples online do not make it clear as to why OOP is considered a better practice.

All I see are posts discussing about how you should use objects in PHP when you are dealing with multiple sets of similar data. That's fine and all, but now I don't see when that really occurs on a webpage. If you are handling user data, you are dealing with a single user accessing the page, so why create an object to hold and manage that data when you are dealing with one user? Why not simply collect that data into a set of variables and manipulate it how you wish in a procedural fashion, which to me seems much easier than having a separate class file, including the class file, creating and initializing the object with the data and then accessing the object to manipulate it.

I do use a class in my project which acts as a bit of a wrapper for PDO and does some error handling as well as some custom query stuff to simplify querying the database. I actually don't really see why this should be a class either. Why should my custom query function be in a class? I have a globally included file that is required by every document in my project, which sets some variables used site-wide from a configuration file, such as the database server information. So why not in that same globally included file do I not just create a PDO connection and define my query function, which can then be used by anything including that file.

Example

function connectDB($host, $name, $pass, $db)
    //Connect to the database and handle exceptions

function queryDB($statement, ...$params)
    //Query the database with the provided statement and parameters to be bound to the statement and handle exceptions

So why should I encapsulate those into a class when I could just have them in global.php, included across my project and call them whenever I want. As I have it now, those are in class which means in global.php I have to create and object and then whenever I want to use those functions I have to write $object->connectDB(...), instead of just connectDB(...), which seems so pointless to me when, yes those to functions are related in that they both involve the database, but other than that they do not interact.

An example of one aspect of my project's functionality: The user clicks the 'News' tab, Angular sees the URL is pointing to the news page so it loads /system/news.php which pulls a list of articles from the database, loops through them and generates HTML for them that is displayed in the page by Angular. In what way would something like this be better as an object? Sure I could create a news object that stores each part of the article (title, body, date, author, etc) but then I'm just outputting them after anyways so I don't see the point. I could also create an object that holds each news articles data and has methods for generating and outputting HTML, which again seems like I'm needlessly creating a class and moving my code into another file, to basically call it from one other file, since that code is only ever used on the news page.

At the end of the day, my question is, why do people insist on using OOP, which splits up your code into classes which are driven by a main index page, when you can simple write each separate piece of functionality in it's own file and call it when necessary?


r/PHPhelp • • Aug 25 '16

Easiest way to send emails using a external SMTP server with authentification using PHP?

7 Upvotes

Im using DigitalOcean and I want to send emails when a PHP script I have does certain things. I know I can do it locally but I want to send it to external emails and use a third party SMTP server and needs auth.

I only need to send; Do not need to recieve.

What is the easiest way to set this up?


r/PHPhelp • • Jun 30 '16

Does anyone know of a good resource for learning in depth about parallel processing in php?

7 Upvotes

I've found several options through googling:

  • php7 pthreads

  • something like exec(), proc_open(), pcntl_fork() to start multiple scripts in the background

  • making multiple ajax requests from browser to an api to kick off several processes at once

  • gearman?

However, I don't know anything about these options beyond a brief 1 sentence summary, or if I'm missing other possible solutions. I want to have a solid understanding of how each options works. for example:

  • how many tasks can I run in parallel using the exec() and similar methods? hardware requirements?

  • how does the performance compare when running in parallel using these methods vs sequential

  • even basic questions like difference between multithread, multiprocess?

  • maybe examples of situations when each option makes the most sense/limitations of each method.

  • plenty of coding examples!

I have a ton more questions but I think you get the gist of what I'm looking for? Just a very in depth background on everything parallel processing in php. maybe a textbook, or online class? Thanks!


r/PHPhelp • • Jun 21 '16

Would love you guys to review this!

7 Upvotes

I made a pastebin clone, which I think is a bit easier to use, and would love feedback both on presentation and the underlying code.

Basically, you paste your code, add a note (optional) and click two buttons to paste it on the site.

Everything will automatically expire after a user selected amount of time (currently, the posts just expire and are no longer visible, but once I'm confident everything is working properly, I'll just delete them from the database).

It uses what I believe is the same rendering engine as Pastebin (GeSHI, which I added a little to recognize additional CSS definitions), and saves both the raw post data and the formatted/syntax-highlighted code separately.

It just uses a shortcode format, where each post is assigned a unique 8 digit ID, so the URL structure is like bit.ly's (site.com/kjkjk32o) - that's currently a kludge, where I have to rely on .htaccess to catch every 404 request and search the database to see if there's a match.

Overall I'm pretty happy with it, I know it's pretty basic work, but just wanted to share and get your thoughts/feedback.

The site is at www.manyeyes.org

The source is at www.github.com/lucasjkr/manyeyes.org.

Here is the source of the code viewing page, for example:

http://manyeyes.org/1d4f9037

I know there's still work to do, need to move more of the PHP off the main pages and into a library, I think, need to do a lot more work on the CSS side (especially for mobile/narrow screens), but overall am happy enough with it ask this subs opinion.


r/PHPhelp • • Jun 03 '16

Alternative to many parent classes?

7 Upvotes

I'm getting an inspection notice about a class of mine having 3 or more parent classes. I am extending an extended controller in a framework, so there is a chain of 5 classes total, starting with an abstract class.

It seems fine to me, but I'm interested in thoughts on alternatives. The usual sources aren't superhelpful here.


r/PHPhelp • • Feb 05 '14

Started first job as php/MySQL developer and I am lost

7 Upvotes

Hi! I am a lurker on this subreddit and now I need some advice. I finished uni a few months ago and now I started a job as a software developer. The company I work for is at the moment working on a pretty big and complex system for a big company. It's basically php and MySQL (they are planning on switching to PostgreSQL). My problem is have no professional experience with php and MySQL, so the huge amount of code I need to look into is overwhelming. Today I had to 'familiarise' myself with a smaller php page that generates a report and eventually play around with it. I started looking through it and I might have gotten sidetracked as I started looking into all the functions and classes (that were defined in other php files and used in the php page above) so there is a mess in my head right now. Do you have any advice for me on how to start familiarising myself with the current application? Thank you very very much for any advice you can give to me as I feel lost.


r/PHPhelp • • Nov 07 '13

How to make dynamic URLs?

7 Upvotes

I'm not sure if I'm really even asking my question correctly.

If you look here: http://www.pro-football-reference.com/players/M/MannPe00.htm you will see a database where each player ends up getting a unique URL. I can't believe that the programmers are actually writing up a unique HTML page for each player.

I assume that somehow there is a script that queries the database and creates a URL based on the database record.

I'm sure I could do something similar using the $_GET function, to create something like: ../players/profile.php?MannPe00

But how would it be done like they do at Pro Football Reference?


r/PHPhelp • • Nov 27 '12

PHP JQuery/AJAX Help

7 Upvotes

Trying to get a list from a table to be clickable to show child items next to it from another table.

I'm learning PHP at the moment and have very little knowledge of JS. Here's the code I got from another place. When I click an item in the first list nothing shows up. Anyone know what's going on?The parent ID isn't been sent on click so the sql query returns nothing.

<div id='container'>
<div id='header'>
</div>
</div> 
<?php require ('./includes/connection.inc.php');

/* AJAX request */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$query = sprintf('SELECT * FROM listitems WHERE parent=%d',
        mysql_real_escape_string($_REQUEST['parent']));
$listitems = mysql_query($query)
        or die(mysql_error()); 
printf('<h3>List %d Items</h3>', $_REQUEST['parent']);
while($info = mysql_fetch_array( $listitems )) 
{ 
    echo $info['itemName']."<br />";
}
exit;
}


/* Normal request */
?>

<div id="lists">
<h3>Lists</h3>
<?php      
$lists = mysql_query("SELECT * FROM lists") 
        or die(mysql_error());
while($info = mysql_fetch_array( $lists )) 
{  
    echo "<a href=\"\">".$info['listName']."</a><br />";
} 

?>      
</div>  

<div id='listitems'>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>jQuery(function($)){
 $('#lists').delegate('a', 'click', function(){
     $('#listitems').load(window.location.pathname, {parent: $(this).text()});
     return false;
 });
}
</script>