I was trying to make a signup, login, logout php program all by myself for sometime now. Finally i think i made it. As i am a newbie in php coding, i would love if you guys can check it out and give me critics. Like where i can improve, what are the security threats that my code can result in or whatever:P/>.

This is all you gotta do:
1) Download all the 7 php and html files. (When i applied my logic i came out with 7 files!! :(/> All are small small codes prolly you guys can make it into one program lol)
2) Run the createdatabase.php first to create the database.
3) Use wamp or xampp or whatever u got to compile php and open homepage.html.
4) Yeah thats it, u have to register before you login anyways.
5) You might need to change the mysql_connect details in login.php and signup.php. I use the default localhost, root, (no password) to connect.

Or if you dont wanna download just see this code below:

Createdatabase.php

This is the form that has login and signup forms.
UBER COOL WEBSITE

UBER COOL WEBSITE

Sign Up

Username:
Password:
Confirm Password:
 

Login

Username:
Password:
 

"; else echo "Invalid Username
"; echo " Go back to login page "; } /* 1) We shouldnt allow similar usernames. (Y) 2) make the go back to login page work. (Y) 3) We shouldnt allow null usernames and passwords.(Y) */ ?>

Go back to login page "; } else { $_SESSION["access"]=1; $_SESSION["user"]=$_POST; header("Location: website.php"); } mysql_close($con); /* 1) Currently, just a message is printed when u type a correct password and another one, when its a wrong password. What i want in the future is a message when its wrong password and a NEW PAGE WHICH IS NOT ACCESSIBLE WITHOUT THE PASSWORD IN ANYWAYS if its a correct password. If the link to that page is written directly without logging in, you will be redirected to the login page. No one can no way access a profile without having an account in the website.(Y) 2) Give a password to the server. 3) The new page into which the user goes when they type the correct password is the user profile. 4) There should be an option for deleting the profile in the profile page. Also u can upload a display picture, write about me and stuff. */ ?>

Access.php

Website.php (The website to which a user who login connects to. It also contains the logout button.

UBER COOL WEBSITE

Welcome to the uber-cool-website

Thanks a lot to everyone who says hello in this thread:D/>

Over the past few years, web hosting has undergone a dramatic change. Web hosting services have changed the way websites perform. There are several kinds of services but today we will talk about the options that are available for reseller hosting providers. They are Linux Reseller Hosting and Windows Reseller Hosting. Before we understand the fundamental differences between the two, let’s find out what is reseller hosting.

Reseller Hosting

In simple terms, reseller hosting is a form of web hosting where an account owner can use his dedicated hard drive space and allotted bandwidth for the purpose of reselling to the websites of third parties. Sometimes, a reseller can take a dedicated server from a hosting company (Linux or Windows) on rent and further let it out to third parties.

Most website users either are with Linux or Windows. This has got to do with the uptime. Both platforms ensure that your website is up 99% of the time.

1. Customization

One of the main differences between a Linux Reseller Hostingplan and the one provided by Windows is about customization. While you can experiment with both the players in several ways, Linux is way more customizable than Windows. The latter has more features than its counterpart and that is why many developers and administrators find Linux very customer- friendly.

2. Applications

Different reseller hosting services have different applications. Linux and Windows both have their own array of applications but the latter has an edge when it comes to numbers and versatility. This has got to do with the open source nature of Linux. Any developer can upload his app on the Linux platform and this makes it an attractive hosting provider to millions of website owners.

However, please note that if you are using Linux for web hosting but at the same time use the Windows OS, then some applications may not simply work.

3. Stability

While both the platforms are stable, Linux Reseller Hosting is more stable of the two. It being an open source platform, can work in several environments.This platform can be modified and developed every now and then.

4. .NET compatibility

It isn’t that Linux is superior to Windows in every possible way. When it comes to .NET compatibility, Windows steals the limelight. Web applications can be easily developed on a Windows hosting platform.

5. Cost advantages

Both the hosting platforms are affordable. But if you are feeling a cash crunch, then you should opt for Linux. It is free and that is why it is opted by so many developers and system administrators all around the world.

6. Ease of setup

Windows is easier to set up than its counterpart. All things said and done, Windows still retains its user-friendliness all these years.

7. Security

Opt for Linux reseller hosting because it is more secure than Windows. This holds true especially for people running their E-commerce businesses.

Conclusion

Choosing between the two will depend on your requirement and the cost flexibility. Both the hosting services have unique advantages. While Windows is easy to set up, Linux is cost effective, secure and is more versatile.



Back in March of this year, I had a very bad experience with a media company refusing to pay me and answer my emails. They still owe me thousands of dollars and the feeling of rage I have permeates everyday. Turns out I am not alone though, and hundreds of other website owners are in the same boat. It"s sort of par for the course with digital advertising.

In all honesty, I"ve had this blog for a long time and I have bounced around different ad networks in the past. After removing the ad units from that company who stiffed me, I was back to square one. I should also note that I never quite liked Googles AdSense product, only because it feels like the "bottom of the barrel" of display ads. Not from a quality perspective, but from a revenue one.

From what I understand, you want Google advertising on your site, but you also want other big companies and agencies doing it as well. That way you maximize the demand and revenue.

After my negative experience I got recommend a company called Newor Media . And if I"m honest I wasn"t sold at first mostly because I couldn"t find much information on them. I did find a couple decent reviews on other sites, and after talking to someone there, I decided to give it a try. I will say that they are SUPER helpful. Every network I have ever worked with has been pretty short with me in terms of answers and getting going. They answered every question and it was a really encouraging process.

I"ve been running the ads for a few months and the earnings are about in line with what I was making with the other company. So I can"t really say if they are that much better than others, but where they do stand out is a point that I really want to make. The communication with them is unlike any other network I"ve ever worked it. Here is a case where they really are different:

They pushed the first payment to me on time with Paypal. But because I"m not in the U.S (and this happens for everyone I think), I got a fee taken out from Paypal. I emailed my representative about it, asking if there was a way to avoid that in the future.

They said that they couldn"t avoid the fee, but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! When have you ever been able to make a request like that without having to be forwarded to the "finance department" to then never be responded to.

The bottom line is that I love this company. I might be able to make more somewhere else, I"m not really sure, but they have a publisher for life with me. I"m not a huge site and I don"t generate a ton of income, but I feel like a very important client when I talk to them. It"s genuinely a breathe of fresh air in an industry that is ripe with fraud and non-responsiveness.

Microcomputers that have been created by the Raspberry Pi Foundation in 2012 have been hugely successful in sparking levels of creativity in young children and this UK based company began offering learn-to-code startup programs like pi-top an Kano. There is now a new startup that is making use of Pi electronics, and the device is known as Pip, a handheld console that offers a touchscreen, multiple ports, control buttons and speakers. The idea behind the device is to engage younger individuals with a game device that is retro but will also offer a code learning experience through a web based platform.

The amazing software platform being offered with Pip will offer the chance to begin coding in Python, HTML/CSS, JavaScript, Lua and PHP. The device offers step-by-step tutorials to get children started with coding and allows them to even make LEDs flash. While Pip is still a prototype, it will surely be a huge hit in the industry and will engage children who have an interest in coding and will provide them the education and resources needed to begin coding at a young age.

Future of Coding

Coding has a great future, and even if children will not be using coding as a career, they can benefit from learning how to code with this new device that makes it easier than ever. With Pip, even the youngest coding enthusiasts will learn different languages and will be well on their way to creating their own codes, own games, own apps and more. It is the future of the electronic era and Pip allows the basic building blocks of coding to be mastered.
Computer science has become an important part of education and with devices like the new Pip , children can start to enhance their education at home while having fun. Coding goes far beyond simply creating websites or software. It can be used to enhance safety in a city, to help with research in the medical field and much more. Since we now live in a world that is dominated by software, coding is the future and it is important for all children to at least have a basic understanding of how it works, even if they never make use of these skills as a career. In terms of the future, coding will be a critical component of daily life. It will be the language of the world and not knowing computers or how they work can pose challenges that are just as difficult to overcome as illiteracy.
Coding will also provide major changes in the gaming world, especially when it comes to online gaming, including the access of online casinos. To see just how coding has already enhanced the gaming world, take a look at a few top rated casino sites that rely on coding. Take a quick peek to check it out and see just how coding can present realistic environments online.

How Pip Engages Children

When it comes to the opportunity to learn coding, children have many options. There are a number of devices and hardware gizmos that can be purchased, but Pip takes a different approach with their device. The portability of the device and the touchscreen offer an advantage to other coding devices that are on the market. Pip will be fully compatible with electronic components in addition to the Raspberry Pi HAT system. The device uses standard languages and has basic tools and is a perfect device for any beginner coder. The goal is to remove any barriers between an idea and creation and make tools immediately available for use. One of the other great advantages of Pip is that it uses a SD card, so it can be used as a desktop computer as well when it is connected to a monitor and mouse.
The Pip device would help kids and interested coder novice with an enthusiasm into learning and practicing coding. By offering a combination of task completion and tinkering to solve problems, the device will certainly engage the younger generation. The device then allows these young coders to move to more advanced levels of coding in different languages like JavaScript and HTML/CSS. Since the device replicates a gaming console, it will immediately capture the attention of children and will engage them to learn about coding at a young age. It also comes with some preloaded games to retain attention, such as Pac-Man and Minecraft.

Innovations to Come

Future innovation largely depends on a child’s current ability to code and their overall understanding of the process. As children learn to code at an early age by using such devices as the new Pip, they will gain the skills and knowledge to create amazing things in the future. This could be the introduction of new games or apps or even ideas that can come to life to help with medical research and treatments. There are endless possibilities. Since our future will be controlled by software and computers, starting young is the best way to go, which is why the new Pip is geared towards the young crowd. By offering a console device that can play games while teaching coding skills, young members of society are well on their way to being the creators of software in the future that will change all our lives. This is just the beginning, but it is something that millions of children all over the world are starting to learn and master. With the use of devices like Pip, coding basics are covered and children will quickly learn the different coding languages that can lead down amazing paths as they enter adulthood.

In this tutorial, we are going to be creating a user signup form that adds a user to a database, and then sends out a confirmation email that the user must click on before their account will be activated.

Need Some Help?

This tutorial will take you through the process from scratch, but if you prefer, you can use one of the many ready-made email signup forms on Envato Market. Here are a few of the most popular options.

1.

The Simple Signup Form jQuery Plugin will collect the visitor’s email address on your website in an effective, attention-grabbing way. It has a lot of optional customization options that you can set up in minutes.

2. Hype: SmartR Signup Form

Hype is a SmartR Sign Up form, preconfigured and added to any page in only one click. It harnesses the power of your users and their networks to actively increase sign-ups and exponentially grow your user base.

3. Beta Splash Page Email Signup Form

This is a very simple, yet stylish, form for your website where visitors can enter their email address (and name if desired) to be added to a contact list. It uses AJAX to submit and validate email and will also function if the user has JavaScript disabled.

Installation is quick and painless. This form does not require a database to function as it will create and store input into a CSV file.

So, we"ve cleaned up our variables, now let"s check to see if the user forgot any fields.

If(empty($username)){ //put code in me please } if(empty($password)){ //put code in me please } if(empty($email)){ //put code in me please }

Now we have three if statements that are checking if each field is empty. If the field is empty we are going to assign some variables.

To make things clean we are going to create an array that will hold the status of the signup process as well as any text we need to show the user.

Right above that piece of code, let"s create an array and a few variables.

$action = array(); $action["result"] = null; $text = array();

First we are creating a blank array called action and then setting an array value of result. Result is going to hold a value of either success or error. Next we create another blank array called text. This is going to hold any text we want to show the user during the signup.

Right now, our if statements that are checking our variables aren"t executing any code, so let"s go ahead and put some code inside the first if statement.

Put this code inside the username if statement.

$action["result"] = "error"; array_push($text,"You forgot your username");

Let"s say the user submits the form without a username. Our statement is going to run the code above. First it"s going to set the result field of our action array to error.

Then we are going to use array_push() to put some text into our text array. We are going to be using this same piece of code for the final two "if" statements so copy and paste that code into the last two if statements. You"ll probably want to change the text to match the current if statement.

Note: We are using array_push() in case we have multiple errors in the form submission. If all if statements are executed, the text array will looks like:

Array( => "You forgot your username", => "You forgot your password", => "You forgot your email")

We now need to check if we have any errors so we can continue on with the signup process.

Step 6: No Errors, Let"s Signup the User

We are going to check to see if our action array result value is set to error.

If($action["result"] != "error"){ //no errors, continue signup $password = md5($password); } $action["text"] = $text;

We are also running our password through the md5() function. This takes the password and returns a 32 character string that looks something like this: . It"s good practice to run the password through some sort of hashing function before putting it into the database. This prevents people from viewing the users passwords if your database is hacked.

A quick check of our action result value and we can continue on with the signup. If our result is error we will skip over all this code and output the errors to our user so they can make the necessary changes.

The last piece of this code we are putting the values of your text array into our action array.

Step 7: Adding the User to the Database

Place this code inside our last if statement.

If Statement checking for errors ... //add to the database $add = mysql_query("INSERT INTO `users` VALUES(NULL,"$username","$password","$email",0)"); if($add){ //the user was added to the database }else{ $action["result"] = "error"; array_push($text,"User could not be added to the database. Reason: " . mysql_error()); = }

We use mysql_query() and INSERT to insert the users information into the database. Next, we create another if statement checking to see if the user was added to the database. We do this by checking if the $add variable is true or false.

If the user is added we can continue on with the signup; if not we are going to assign some familiar variables and stop the signup.

When working with MySQL queries, we use the mysql_error() function if their are errors because it helps with debugging what is wrong with your queries. It will output text errors when something is wrong. This is good!

Step 8: Confirmation is Needed

The user has submitted the form, everything checks out and they"re now living in the database. We want the user to be able to use their account, so let"s setup the confirmation.

If added check ... //get the new user id $userid = mysql_insert_id(); //create a random key $key = $username . $email . date("mY"); $key = md5($key); //add confirm row $confirm = mysql_query("INSERT INTO `confirm` VALUES(NULL,"$userid","$key","$email")"); if($confirm){ //let"s send the email }else{ $action["result"] = "error"; array_push($text,"Confirm row was not added to the database. Reason: " . mysql_error()); }

To make things easy, let"s assign the new user id to a variable so we can use it later. We do this by using m ysql_insert_id() . This will set $userid to whatever the new user"s ID is.

Next we create the random key for that specific user. We create a variable named key and fill it with a value of the username, email and date. The string will look like [email protected]. After that we use the md5() function to convert it to a random string that is unique to that user.

Using mysql_query() and INSERT again, we put the new user ID, the key and the users email into the database.

Step 9: Setting up the Email Templates

We are going to take a break from the PHP coding and create two new files. For the sake of being quick and easy we are actually going to use two templates that I"ve included with this tutorial. The two files we"re going to be looking at are signup_template.html and signup_template.txt . Swift lets us assign an HTML as well as a TXT version of the email incase the users email client doesn"t support HTML emails.

Open up signup_template.html Note: You can read up on HTML in emails over at carsonified. We aren"t going to be editing this file, i"m just going to explain whats going on and then you can play around with it once the tutorial is complete. The most important part of this file is the tags that look like {USERNAME} and confirm.php?email={EMAIL}&key={KEY} . We are going to write a function that uses this template and replaces those tags with the variables from our form.

Step 10: The Template Function

Open up inc/php/functions.php and place this code inside.

Function format_email($info, $format){ //set the root $root = $_SERVER["DOCUMENT_ROOT"]."/dev/tutorials/email_signup"; //grab the template content $template = file_get_contents($root."/signup_template.".$format); //replace all the tags $template = ereg_replace("{USERNAME}", $info["username"], $template); $template = ereg_replace("{EMAIL}", $info["email"], $template); $template = ereg_replace("{KEY}", $info["key"], $template); $template = ereg_replace("{SITEPATH}","http://site-path.com", $template); //return the html of the template return $template; }

format_email() is taking two variables which will be used in index.php. The first is our form information array and the second is format. We have a format variable so we can re-use this array for both the HTML and TXT versions of the template.

First we set the root. This points to the folder that the templates are hosted.

Next we open up the contents of our template and assign it to a variable.

Now we are going to use ereg_replace() to replace our {USERNAME} tags in our template with the content from our form. It"s basically just a super simple template system.

Lastly we return the template variable which holds all the html.

Explanation: In a nutshell, format_email() opens up our template files, takes the HTML and assigns it to our variable. This is just a cleaner way then assigning all the HTML in the function itself.

Step 11: Sending the Email

We are going to write another function to deal with Swift and sending the emails.

Function send_email($info){ //format each email $body = format_email($info,"html"); $body_plain_txt = format_email($info,"txt"); //setup the mailer $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance(); $message ->setSubject("Welcome to Site Name"); $message ->setFrom(array("[email protected]" => "Site Name")); $message ->setTo(array($info["email"] => $info["username"])); $message ->setBody($body_plain_txt); $message ->addPart($body, "text/html"); $result = $mailer->send($message); return $result; }

Just like format_email() , send_email() takes our info array as a variable. The first part of the function we assign two variables, $body and $body_plain_text . We are using format_email() to assign the HTML values of our template to each variable. Now comes the good part. We have setup the swift instance using Swift_MailTransport:newInstance() and then setup the mailer using Swift_Mailer::newInstance($transport) ;

We create a new instance of the Swift message and start to assign some variables to this instance. We set the subject, from email and to email address and then use setBody() to assign out text version of the email to the mailer instance. To add the HTML version we use addPart() . The send() function takes care of the sending of the email and then we return the result. Alright, we have our email create and send functions written, let"s go back to index.php and start to wrap up the main signup.

Step 12: Did we Send? Shall we Confirm?

Our last bit should"ve been the if statement checking if the confirm row was created.

Let"s send the email and check if everything went though alright.

If confirm ... //include the swift class include_once "inc/php/swift/swift_required.php"; //put info into an array to send to the function $info = array("username" => $username, "email" => $email, "key" => $key); //send the email if(send_email($info)){ //email sent $action["result"] = "success"; array_push($text,"Thanks for signing up. Please check your email for confirmation!"); }else{ $action["result"] = "error"; array_push($text,"Could not send confirm email"); }

Without the Swift class we can"t send out any emails, so in our first line, we are including the swift class. We need to send our information to both of our new functions, so we create a new array and assign our variables to it. I know I know, more if statements, but we need to check for errors to make it easier for the users. You always have to assume that users will make every possible mistake imaginable.

We wrap our send_email() function in another if statement as well as passing the $info array. If the email is sent we assign a value of success and thank the user for signing up. If there are errors we use the familiar variables. So now, we are almost done with the signup, just one last function needs to be created. Even though we are assigning all these error/success variables and text we haven"t displayed this information to the user.

Move back to functions.php and paste this code.

//cleanup the errors function show_errors($action){ $error = false; if(!empty($action["result"])){ $error = "

    "."\n"; if(is_array($action["text"])){ //loop out each error foreach($action["text"] as $text){ $error .= ""."\n"; } }else{ //single error $error .= "

    $action

    "; } $error .= "
"."\n"; } return $error; }

This may seem confusing but it"s really just making our success/errors looks nice.

First it checks to see if the array is empty so we aren"t executing the code when it isn"t needed.

Next it creates a ul tag and applies the result as a class. This will either be success or error and is aesthetic only.

We then check to see if the text variable is an array or simply a string. If it"s a string, we wrap it in an li. If it"s an array we loop through each array item and wrap it in an li.

Lastly, we close the ul and return the entire string.

If we move back to index.php and place this code right after including header.php we can wrap up this section.

Header include ...

A quick little explanation. We are taking all the values of our action array and passing it to the show_errors() function. If there is any content it returns a nice unordered list.

Step 13: Confirming the User

We should have a good grip on how the script is functioning; so for this next script I"m going to give you the entire chunk of code and then go through it with you.

Open up confirm.php and paste this in-between the header include and your show_errors() function.

//setup some variables $action = array(); $action["result"] = null; //quick/simple validation if(empty($_GET["email"]) || empty($_GET["key"])){ $action["result"] = "error"; $action["text"] = "We are missing variables. Please double check your email."; } if($action["result"] != "error"){ //cleanup the variables $email = mysql_real_escape_string($_GET["email"]); $key = mysql_real_escape_string($_GET["key"]); //check if the key is in the database $check_key = mysql_query("SELECT * FROM `confirm` WHERE `email` = "$email" AND `key` = "$key" LIMIT 1") or die(mysql_error()); if(mysql_num_rows($check_key) != 0){ //get the confirm info $confirm_info = mysql_fetch_assoc($check_key); //confirm the email and update the users database $update_users = mysql_query("UPDATE `users` SET `active` = 1 WHERE `id` = "$confirm_info" LIMIT 1") or die(mysql_error()); //delete the confirm row $delete = mysql_query("DELETE FROM `confirm` WHERE `id` = "$confirm_info" LIMIT 1") or die(mysql_error()); if($update_users){ $action["result"] = "success"; $action["text"] = "User has been confirmed. Thank-You!"; }else{ $action["result"] = "error"; $action["text"] = "The user could not be updated Reason: ".mysql_error();; } }else{ $action["result"] = "error"; $action["text"] = "The key and email is not in our database."; } }

Most of this should look very familiar; so I"m going to skip ahead and check if the key is in the database section.

Again, we use mysql_query() to get any rows in the database where the email and key are equal to the keys provided by the users email.

We use mysql_num_rows() to check if the number of rows returned is greater than 0.

If the email and key are in the database we grab all the information from the database using mysql_fetch_assoc() .

Now that the user has confirmed his account, we need to update the database and set the active row to 1.

We use mysql_query() again, but instead of INSERT we use UPDATE to update the active row to 1 where the user ID is the same as our current users ID.

To clean everything up we use mysql_query() and DELETE to remove the confirmation row from the database. This makes sure that the user can"t come back to this page and reconfirm. It also keeps the database nice and clean.

Conclusion

We"ve covered many different areas in this tutorial. We downloaded and included a 3rd party script to deal with sending the emails, implemented simple form validation as well as created a super simple template system to style our emails. If you"re new to MySQL we"ve touched on the three most common functions in MySQL so you should have no problem completing some more advanced tutorials.

Final Notes

  • I"ve used Swift Mailer as our email deployment script which can be downloaded here: http://swiftmailer.org/
  • I"ve also used button styles provided by Zurb. Be sure to check them out and give them some love. http://www.zurb.com/blog_uploads/0000/0485/buttons-02.html

Thanks for reading and be sure to visit me on

Создаем собственную страницу регистрации для мультисайта взамен стандартной wp-signup.php .

В обычной установке WordPress страницу регистрации (авторизации, сброса пароля) выводит файл wp-login.php .

  • /wp-login.php - авторизация
  • /wp-login.php?action=register - регистрация
  • /wp-login.php?action=lostpassword - сброс пароля

Для мультисайта в wp-login.php есть отдельные условия. Так, при переходе по ссылке /wp-login.php?action=register на мультисайте, WordPress сделает редирект на страницу /wp-signup.php . Во многих темах страница выглядит не очень привлекательно, поэтому мы сделаем свою собственную.

Основной сайт сети

По умолчанию, WordPress открывает страницу регистрации (wp-signup.php) на основном домене (сайте) сети. Тем не менее, можно сделать отдельную страницу регистрации для каждого сайта сети, даже если у них разные темы. Мы будем рассматривать случай, когда на всех сайтах сети есть своя собственная страница регистрации, но используется одинаковая тема и сайты различаются лишь языком. Если используются разные темы, потребуется написать больше кода.

functions.php?

Нет. Имя этого файла, кажется, упоминается в любой статье про WordPress. В нашем случае, с учетом того, что функционал регистрации рассчитан на несколько сайтов, имеет смысл вынести его в MU-плагины, которые загружаются при открытии любого сайта.

Лирическое отступление

Стоит отметить, что MU-плагины загружаются раньше обычных плагинов и до полной загрузки ядра WordPress, поэтому вызов некоторых функций может привести к фатальным ошибкам в PHP. Подобная «ранняя» загрузка имеет и свои плюсы. Скажем внутри любой темы нельзя цепляться к некоторым экшенам, которые срабатывают еще до загрузки файла functions.php из темы. Примером этого могут служить экшены из плагина Jetpack вида jetpack_module_loaded_related-posts (related-posts - название модуля) с помощью которых возможно отслеживать активность модулей в Jetpack. К этому экшену невозможно «прицепиться» из файла темы, потому что экшен уже сработал до загрузки темы - плагины загружаются раньше тем. Взглянуть на общую картинку порядка загрузки WordPress можно на странице Action Reference в кодексе .

Порядок в файлах

MU-плагины могут содержать любое количество файлов и любую стуктуру, которая покажется вам логичной. Я придерживаюсь примерно такой иерархии:

|-mu-plugins |-|-load.php |-|-|-selena-network |-|-|-|-signup |-|-|-|-|-plugin.php |-|-|-|-|-... |-|-|-|-jetpack |-|-|-|-|-plugin.php

В файле load.php подключаются все необходимые «плагины» для нашей сети:

// Load Traslates for all addons load_muplugin_textdomain ("selena_network", "/selena-network/languages/"); // Network Signup require WPMU_PLUGIN_DIR . "/selena-network/signup/plugin.php"; // Another plugins // require WPMU_PLUGIN_DIR ...

Внутри папки selena-network хранятся папки плагинов, в каждой есть свой plugin.php , которые мы и подключаем в load.php . Это дает гибкость и возможность быстро отключать и включать некоторые вещи.

Адрес страницы регистрации

Чтобы указать адрес страницы регистрации, используется фильтр wp_signup_location . Его можно найти внутри файла wp-login.php и именно он отвечает за редирект на wp-signup.php .

Case "register" : if (is_multisite()) { wp_redirect(apply_filters("wp_signup_location", network_site_url("wp-signup.php"))); exit;

Добавим свою функцию в mu-plugins/selena-network/signup/plugin.php , которая будет отдавать адрес страницы регистрации на текущем сайте:

Function selena_network_signup_page ($url) { return home_url () . "/signup/"; } add_filter ("wp_signup_location", "selena_network_signup_page", 99);

selena_network - префикс, который я использую в именах всех функций внутри MU-плагинов на своем сайте для избежания коллизий, его следует заменить на свой собственный уникальный префикс. Приоритет добавления фильтра 99, потому что некоторые плагины, например bbPress и BuddyPress могут перезаписать этот адрес на свой собственный (MU-плагины загружаются раньше, чем обычные плагины, см. выше). Обратите внимание, что используется home_url() , вместо network_site_url() , чтобы оставить посетителя на том же домене. В качестве адреса можно использовать любой URL.

Создание страницы

Теперь создадим страницу с адресом site.com/signup/ через обычный интерфейс, а в папке дочерней темы шаблон для нашей новой страницы - page-signup.php . Вместо слова «signup» можно использовать уникальный ID.

Внутри нового шаблона необходимо выполнить вызов функции selena_network_signup_main() , которая будет выводить форму регистрации.

Стоит заметить, что весь процесс с шаблонами не обязателен и вместо этого можно создать свой шорткод, который будет также вызывать функцию selena_network_signup_main() .

wp-signup.php и wp-activate.php

Теперь займемся созданием функции, которая будет выводить форму регистрации. Для этого скопируем файлы wp-signup.php и wp-activate.php из корня WordPress в mu-plugings/selena-network/signup/ (и не забываем их подключить внутри mu-plugins/selena-network/signup/plugin.php). Дальнейшие манипуляции с файлами крайне сложно и долго описывать, поэтому прийдется сделать их самостоятельно. Я лишь опишу что именно надо сделать и опубликую исходные файлы своего проекта:

  1. В начале файла удалить все require , вызов функций и прочий код вне функций.
  2. Переименовать все функции, добавив к именам уникальные префиксы.
  3. Нижнюю часть кода wp-signup.php обернуть в функцию selena_network_signup_main и в ее самом начале написать global $active_signup; .
  4. Заменить верстку на свою собственную в нужных местах.

Внутри wp-activate.php необходимо сделать примерно тоже самое:

  1. Удалить весь код вне функций, обернуть верстку в отдельную функцию.
  2. Изменить верстку в местах, где это необходимо.

Файл wp-activate.php отвечает за страницу активации аккаунта. Как и со страницей регистрации для нее необходимо создать отдельный шаблон, внутри которого вызывать функцию из файла wp-activate.php .

Отправляем письма активации

Страница регистрации отправляет посетителю письмо со ссылкой на активацию аккаунта. По умолчанию этим занимается функция wpmu_signup_user_notification() из файла ms-functions.php . Ее функционал можно заимствовать для своей функции. Причина, по которой необходимо отказаться от использования этой функции - она отправляет ссылку активации аккаунта с wp-activate.php . «Выключить» же эту функцию можно с помощью фильтра wpmu_signup_user_notification отдавая по нему false (если этого не cделать, письмо активации будет отправляться дважды, окей, на самом деле два разных письма).

Function armyofselenagomez_wpmu_signup_user_notification($user, $user_email, $key, $meta = array()) { // ... // Код из функции wpmu_signup_user_notification() wp_mail($user_email, wp_specialchars_decode($subject), $message, $message_headers); return false; } add_filter("wpmu_signup_user_notification", "armyofselenagomez_wpmu_signup_user_notification", 10, 4);

В результате страница регистрации в теме Селена стала выглядеть намного чище и аккуратней.

Заключение

В интернете множество других не очень правильных способов того, как сделать тоже самое - редиректы Apache, AJAX-формы, которые не будут работать без Java Script и т. п. Все это мне не очень понравилось, поэтому я постарался сделать это максимально правильно на своем собственном сайте.

Замечу, что править файлы следует осторожно и стараться не сильно отходить от исходных, чтобы в дальнешйем, в случае если WordPress изменит файлы wp-signup.php и wp-activate.php , их проще было сравнивать между собой для поиска изменений.

Не забывайте смотреть в исходный код всех описанных выше функций, чтобы полностью разобраться с тем, что и как происходит внутри кода.

Бонус. Защита от спамеров

Даже самые маленькие сайты на WordPress часто подвергаются налету спам-регистраций. Можно писать бесконечные условия для фильтрации ботов, зачастую больше похожие на попытку создать искусственный интеллект 🙂 В случае мультисайта мне очень помог обычный редирект в Apache, с помощью которого при открытии /wp-signup.php и /wp-acitvate.php я попросил выдавать 404 (я не эксперт по настройке Apache, поэтому мои правила могут быть не очень правильными).

RewriteEngine On RewriteBase / RewriteRule ^wp-signup\.php - RewriteRule ^wp-activate\.php - # BEGIN WordPress # Правила от WordPress по умолчанию не трогаем:) # ... # END WordPress

P. S. Я стараюсь максимально детально описывать некоторые сторонние вещи, потому что когда начинал я, порой некому было подсказать и объяснить многие вещи. Также я считаю, что подобные небольшие наводки на другие материалы кого-нибудь подтолкнут к изучению чего-то нового и расширению своей области знаний. В записях RewriteRule используются регулярные выражения, они совсем не сложные, например, символ ^ означает начало строки.

Advertisements