Skip to content
MPGHThe Dark Arts
/
RegisterLog in
Forum
Community
What's NewLatest posts across the boardTrendingHottest threads right nowSubscribedThreads you follow
Discussion
GeneralIntroductionsEntertainmentDebate FortFlaming & Rage
Board
News & AnnouncementsMPGH TimesSuggestions & HelpGiveaways
More Sections
Art & Graphic DesignProgrammingHackingCryptocurrency
Hacks & Cheats
Games
ValorantCS2 / CS:GOCall of Duty / WarzoneFortniteApex LegendsEscape From Tarkov
+14 moreLeague of LegendsGTA VMinecraftRustROTMGBattlefieldTroveBattleOnCombat ArmsCrossFireBlackshotRuneScapeDayZDead by Daylight
Resources
Game Hacking TutorialsReverse EngineeringGeneral Game HackingAnti-CheatConsole Game Hacking
Tools
Game Hacking ToolsTrainers & CheatsHack/Release NewsNew
Submit a release →Share your cheat, tool, or config with the community.
AINEW
AI Tools
General & DiscussionPrompt EngineeringLLM JailbreaksHotAI Agents & AutomationLocal / Open Models
AI × Gaming
AI Aimbots & VisionML Anti-CheatGame Bots & Automation
Create
AI Coding / Vibe CodingAI Art & MediaAI Voice & TTS
The AI frontier →Where game hacking meets modern machine learning. Jump in.
Marketplace
Buy & Sell
SellingBuyingTradingUser Services
Trust & Safety
Middleman LoungeMarketplace TalkVouch Copy Profiles
Money
Cryptocurrency TalkCurrency ExchangeWork & Job Offers
Start selling →List accounts, services, and goods. Use the middleman to trade safe.
MPGH The Dark Arts

A community for offensive security research, reverse engineering, and AI.

Community

ForumMarketplaceSearch

Account

RegisterLog in

Legal

Privacy PolicyForum RulesHelp & FAQ
© 2026 MPGH · All rights reserved.Built by the community, for the community. For educational purposes onlyContent is shared for security research and education — we don't condone illegal use. You're responsible for complying with applicable laws. Use at your own risk.
Home › Forum › Programming › Other Programming › PHP Programming › [Collection]Snippets Vault[PHP]

[Collection]Snippets Vault[PHP]

Posts 1–14 of 14 · Page 1 of 1
NextGen1
NextGen1
[Collection]Snippets Vault[PHP]
Use this format for submitting snippets

It may be used later to parse the snippets to a application (like the one in the VB Section)

If you're going to post a snippet in this thread then you should be posting it in the following format:

Snippet Name: ____________________
Keywords: ____,____,____ ...
Description(Optional): _______________________
Code:
Code:
Your Code Here...
This is to be used for any small bit of code you would like to share.


#1 · 15y ago
Alen
Alen
Why not just make a full site rip of phpclasses? / Otherwise nice idea, but this section is dead, nobody seems to care about good old web dev
#2 · 15y ago
NextGen1
NextGen1
I care, and at some point, all the sections in programming will be alive

I care, and at some point, all the sections in programming will be alive

Snippet Name: User Sign Up
Keywords: PhP, User,Sign,Up,Form



[highlight=php]
<?php
if(isset($_POST['submit'])){
$query = sprintf("SELECT * FROM users WHERE user_name='%s' LIMIT 1",mysql_real_escape_string($_POST['user_name']));
$sql = mysql_query($query);
$row = mysql_fetch_array($sql);
if($row||empty($_POST['user_name'])|| empty($_POST['fname'])||empty($_POST['lname'])|| empty($_POST['email'])||empty($_POST['password'])|| empty($_POST['re_password'])||$_POST['password']!=$_POST['re_password']){
$error = '<p>';
if(empty($_POST['user_name'])){
$error .= 'User Name can\'t be empty<br>';
}
if(empty($_POST['fname'])){
$error .= 'First Name can\'t be empty<br>';
}
if(empty($_POST['lname'])){
$error .= 'Last Name can\'t be empty<br>';
}
if(empty($_POST['email'])){
$error .= 'Email can\'t be empty<br>';
}
if(empty($_POST['password'])){
$error .= 'Password can\'t be empty<br>';
}
if(empty($_POST['re_password'])){
$error .= 'You must re-type your password<br>';
}
if($_POST['password']!=$_POST['re_password']){
$error .= 'Passwords Do Not Match<br>';
}
if($row){
$error .= 'User Already In Database<br>';
}
$error .= '</p>'
}else{
$query = sprintf("INSERT INTO users_table(`user_name`,`f_name`,`l_name`,`email`, `password`)
VALUES('%s','%s','%s','%s',PASSWORD('%s'))",
mysql_real_escape_string($_POST['user_name']),
mysql_real_escape_string($_POST['fname']),
mysql_real_escape_string($_POST['lname']),
mysql_real_escape_string($_POST['email']),
mysql_real_escape_string($_POST['password']))or die(mysql_error());
$sql = mysql_query($query);
header("Location: login.php");
exit;
}
}
if(isset($error)){
echo $error;
unset($error);
}
?>

<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>User:<br /><input type="text" name="user_name" <? if(!$row){echo 'value="'.$_POST['user_name'].'"';} ?>/></p>
<p>FirstName:<br /><input type="text" name="fname" <? echo 'value="'.$_POST['fname'].'"'; ?>/></p>
<p>LastName:<br /><input type="text" name="lname" <? echo 'value="'.$_POST['lname'].'"'; ?>/></p>
<p>Email Address:<br /><input type="text" name="email" <? echo 'value="'.$_POST['email'].'"'; ?>/></p>
<p>Chosen Password:<br /><input type="password" name="password" /></p>
<p>Re-Type Password:<br /><input type="password" name="re_password" /></p>
<p><input type="submit" name="submit" value="Sign Up" /></p>
</form>
[/highlight]
#3 · edited 15y ago · 15y ago
Paul
Paul
@NextGen1 wow, thank you DD <3

i'm learning PHP at the moment for my job and it's kinda weiird :S
#4 · 15y ago
maltray
maltray
May I contribute a bit here?, this is a contact form I made for a webpage some while ago.

Snippet Name: My contact form?
Keywords: contact, form, err, is, this, like, bloggin?
Description(Optional): read above :P

Its with AJAX, also, its posted on a blog (not yet, I was just working on it :P) where im user, i wont put the link as I dont want to have the name "spammer" on my head so.

So... we will have these files:

index.php <- Will show up the HTML and that stuff
contactform.js <- Will send the AJAX (also, some stuff with jQuery)
jquery.js <- For effects and that stuff
contactform.php <- Will be the file that will be called by contactform.js
loading.gif <- A gif that will replace the form while the message is sent

We will just use 3 fields, so the code doesnt get messy; Name, email, and message (finally, lol).

Alright so, I would like first to start with index.php file:

Code:
<?php
session_start();
$_SESSION['token']=md5(rand()); // We add this so we get "protected" from bots
?>
<html>
   <head>
      <title>My contact form</title>
      <script type="text/javascript" src="jquery.js"></script>
      <script type="text/javascript" src="contactform.js"></script>
   </head>
   <body>
   <div id="form">
      <p>Name:<input type="text" id="name"></p>
      <p>Email:<input type="text" id="email"></p>
      <p>Message:<textarea id="message"></textarea></p>
      <input type="hidden" value="<?php echo $_SESSION['token']; ?>" id="token">
      <a href="#" id="send">Send</a>
   </div>
   <div id="loading" style="display: none;">
      <img src="loading.gif">
    </div>
   <div id="mess" style="display: none;">
   </div>
   </body>
</html>
Alright, now its time for contactform.js:

Code:
$(document).ready(function(){
    var sending = false;
    // we define the var "sending" so we can check that the user doesnt click the send button many times.
    var showmess = false;
    // this is to hide the "mess" div
    
    $('#send').click(function(){
        // when any item with the id send is clicked;
        if(sending==false){
            if(showmess){
               $('#mess').slideToggle();
               // we hide it.
            }
            // we check that the "form" isnt beeing "submited"
            sending = true;
            var name = $('#name').val();
            var email = $('#email').val();
            var message = $('#message').val();
            var token = $('#token').val();
            // we take the vals from the inputs (also, the token so we can verify it on contactform.php)
            var send = jQuery.parseJSON('{"name":"'+name+'","email":"'+email+'","message":"'+message+'","token":"'+token+'"}');
            // "prepare" the Json
            $.ajax({
                 type: "POST",
                 url: "contactform.php",
                 data: send,
                 dataType: "json",
                 beforeSend: function(obj){
                    // before send, we will want to slide the div with ID form, and show the loading one (wich is actually hidden)
                     $('#form').slideToggle();
                     $('#loading').slideToggle();
                 },
                 success: function(json){
                    // we check here what we got from the server side, and depending on what happened, what we will show.
                     $('#loading').slideToggle();
                     if(json.status==1){
                         $('#form').html('Message sent.');
                         $('#form').slideToggle();
                     }else{
                        showmess = true;
                         $('#form').slideToggle();
                         sending = false;
                         $('#mess').html(json.message);
                         $('#mess').slideToggle();
                     }
                 }
            });
        }
    });
});
Now contactform.php:

Code:
<?php
// we start the session and get the headers for the "return"
session_start();
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 10 Jul 2000 02:00:00 GMT');
header('Content-type: application/json');

// we add this, as im running this script on my localhost, it takes ms to load and i cant see the js effects
sleep(1);

if(!isset($_SESSION['token'])){
// if token isnt there, then.. probably, a bot, or someone trying to play around, we show him what we got!
    die();
}else{
// if not.. then we check that the token we got from the html, is the same that we got in the session
    $token = isset($_POST['token'])? $_POST['token'] : '';
    if($token != $_SESSION['token']){
// if its not the same, then we kick him back.
        $return['status'] = 0;
        $return['message'] = 'Invalid token.';
        echo json_encode($return);
        die();
    }else{
// but if not, we start getting the variables via POST (the json did this possible)
        $name = isset($_POST['name'])? trim($_POST['name']) : '';
        $phone = isset($_POST['phone'])? trim($_POST['phone']) : '';
        $email = isset($_POST['email'])? trim($_POST['email']) : '';
        $message = isset($_POST['message'])? trim($_POST['message']) : '';
// we get a $return variable, that will be an array (json.message on the js is $return['message'])
        $return = array();
        $return['message'] = '';
        $return['status'] = 0;
// we make some validations
        if(!preg_match('/^[a-zA-ZáéíóúÁÉÍÓÚÀÈÌÒÙàèìòù ]{2,20}$/', $name)){
            $return['message'].='Name\'s not valid!.<br>';
        }
        
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
            $return['message'].='Invalid email.<br>';
        }
        
        if(strlen($message)<10 || strlen($message)>500){
            $return['message'].='Invalid message.';
        }
// if $return['message'] == '', means that theres no errors; we send the message
        if($return['message']==''){
// $to would be changed by the email u want the mail to head.
            $to = 'my@Email.com';
// well.. the rest of it.. read about mail() function lol.
            $title = 'New message';
            $mess = '<html><head></head><body>' .$name . ' sent a message, the email is: '.$email.'.'.'<br>Message was:<br>'.$message.'</body></html>';
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headers .= 'From: w.e' . "\r\n" . 'Reply-To: ' . $email . "\r\n";
            @Mail($to,$title,$mess,$headers);
            $return['status'] = 1;
        }
        
// and now, we do an echo with the encoded json of $result, then die.
        echo json_encode($return);
        die();
    }
}
Im guessing i dont need to post the entire jquery.js code, so, im just gonna attach the code working (just tested it, again )

Cheers!

BTW: on my localhost it will say Message sent, even if it wasnt, as im using @ in the mail function, it wont show me that it couldnt do it...
#5 · 15y ago
KushxOrangeJuice
KushxOrangeJuice
Quote Originally Posted by NextGen1 View Post
Use this format for submitting snippets

It may be used later to parse the snippets to a application (like the one in the VB Section)

If you're going to post a snippet in this thread then you should be posting it in the following format:

Snippet Name: ____________________
Keywords: ____,____,____ ...
Description(Optional): _______________________
Code:
Code:
Your Code Here...
This is to be used for any small bit of code you would like to share.


Hi im trying to learn php and become more familiar with html, do you think youd be willing to mentor/teach me php in your spare time that would be greatly appreciated!
#6 · 15y ago
Paul
Paul
Quote Originally Posted by KushxOrangeJuice View Post
Hi im trying to learn php and become more familiar with html, do you think youd be willing to mentor/teach me php in your spare time that would be greatly appreciated!
go to W3Schools Online Web Tutorials for great html and css tuts
#7 · 15y ago
Paul
Paul
Quote Originally Posted by Paul View Post


go to W3Schools Online Web Tutorials for great html and css tuts

here is a nice snippet i have found:

Snippet Name: PhP Calculator by RageD
Keywords: Calculator, php, snppet, code, simple...
Description(Optional): this code is not by me, it's made by RageD
Code:

Code:
<?php 
// Calculator Script v1 
// Copyright (C) 2007 RageD 

// Define to make this all one document 
$page = $_GET['page']; 

// Defining the "calc" class 
class calc { 
     var $number1; 
     var $number2; 

          function add($number1,$number2) 
          { 
                   $result =$number1 + $number2; 
                    echo("The sum of $number1 and $number2 is $result<br><br>"); 
                    echo("$number1 + $number2 = $result"); 
                    exit; 
           } 

          function subtract($number1,$number2) 
          { 
                   $result =$number1 - $number2; 
                    echo("The difference of $number1 and $number2 is $result<br><br>"); 
                    echo("$number1 &#045 $number2 = $result"); 
                    exit; 
           } 

          function divide($number1,$number2) 
          { 
                   $result =$number1 / $number2; 
                    echo("$number1 divided by $number2 is $result<br><br>"); 
                    echo("$number1 ÷ $number2 = $result"); 
                    exit; 
           } 

          function multiply($number1,$number2) 
          { 
                   $result =$number1 * $number2; 
                    echo("The product of $number1 and $number2 is $result<br><br>"); 
                    echo("$number1 x $number2 = $result"); 
                    exit; 
           } 
} 
$calc = new calc(); 
?> 
<TITLE>PHP Calculator v1</TITLE> 
<form name="calc" action="?page=calc" method="POST"> 
Number 1: <input type=text name=value1><br> 
Number 2: <input type=text name=value2><br> 
Operation: <input type=radio name=oper value="add">Addition <input type=radio name=oper value="subtract">Subtraction <input type=radio name=oper value="divide">Division <input type=radio name=oper value="multiply">Multiplication</input><br> 
<input type=submit value="Calculate"> 
</form> 
<?php 
if($page == "calc"){ 
$number1 = $_POST['value1']; 
$number2 = $_POST['value2']; 
$oper = $_POST['oper']; 
     if(!$number1){ 
          echo("You must enter number 1!"); 
          exit; 
     } 
     if(!$number2){ 
          echo("You must enter number 2!"); 
          exit; 
     } 
     if(!$oper){ 
          echo("You must select an operation to do with the numbers!"); 
          exit; 
     } 
     if(!eregi("[0-9]", $number1)){ 
          echo("Number 1 MUST be a number!"); 
          exit; 
     } 
     if(!eregi("[0-9]", $number2)){ 
          echo("Number 2 MUST be a number!"); 
          exit; 
     } 
     if($oper == "add"){ 
          $calc->add($number1,$number2); 
     } 
     if($oper == "subtract"){ 
          $calc->subtract($number1,$number2); 
     } 
     if($oper == "divide"){ 
          $calc->divide($number1,$number2); 
     } 
     if($oper == "multiply"){ 
          $calc->multiply($number1,$number2); 
     } 
} 
?>
i hope you like it
#8 · 15y ago
SH
Shane Thompson
I knocked up a few tutorials for my old Comp Sci teacher not long ago - these are more advanced than what's covered here - simple database interaction and object-oriented PHP. Hope it is of use...
PHP+MySQL+object-oriented.zip
#9 · 14y ago
Paul
Paul
Snippet Name: Ip Grabber [MySQL]
Keywords: Ip Grabber,E-Mail,MySQL ...
Description(Optional): A Script wichs grabs the Ip if a someone enters his email
Requirements: Webhost, Database
Code:

Add this SQL-Code into your DB:

Code:
CREATE TABLE `test_mysql` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
`ip` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=0 ;
save those 2 files and upload them after it

insert.php
Code:
<html>
<head>
</head>
<body>	

<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="insert_ac.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>Insert Data Into mySQL Database </strong></td>
</tr>
<tr>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="name" type="text" id="name"></td>
</tr>
<tr>
<td>Lastname</td>
<td>:</td>
<td><input name="lastname" type="text" id="lastname"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>

</body>
</html>
insert_ac.php
Code:

<?php

$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name=""; // Database name 
$tbl_name="test_mysql"; // Table name

//test

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form 
$name=$_POST['name'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$ip=$_SERVER['REMOTE_ADDR'];

// Insert data into mysql 
$sql="INSERT INTO $tbl_name(name, lastname, email, ip)VALUES('$name', '$lastname', '$email', '$ip')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful". 
if($result){
echo "Redirecting - Please wait...";
}

else {
echo "ERROR";
}

// close connection 
mysql_close();
?>

That should be all
#10 · 14y ago
Paul
Paul
Snippet Name: Random Number generator
Keywords: Generate random number
Description(Optional): Generates a random number between The minimum int and the maximum int.
Requirements: Copy and Paste skills, a webhost or a xampp installation


Code:
<form action="?generate" method="post">
	<!-- Input Field for the minimum char. -->
	Minimum Char:
	<input id="int1" name="int1" type="text" /><br />
	
	<!-- Input Field for the maximum char. -->
	Maximum Char:
	<input id="int2" name="int2" type="text" /><br />
	
	<input type="submit" value="Generate" />
</form>

<?php
	//checking if form has been submitted
	if(isset($_REQUEST["generate"])) {
		//setting variables.
		$int1 = $_REQUEST["int1"];
		$int2 = $_REQUEST["int2"];
		
		//making sure that there are only numbers
		$int1 = floatval($int1);
		$int2 = floatval($int2);
		
		
		//checking if min int is bigger than max int
		
		
		if($int1 >= $int2) {
			echo "The Minimum char has to be lower than the Maximum char (Make sure that there are no letters).";
		}
		else {
		
			//Will Print out a random number between int1 and int2
			echo "Your random Number: " . rand($int1, $int2);
		}
	}	
?>
#11 · 14y ago
jordi.kroon
jordi.kroon
Code:
<?php
 
class ArrayToXML {

	private $xml;
	private $root;
	
	public function parseXML($array, $api) {
		
		$this->root = new SimpleXMLElement('<?xml version="1.0"?><' . $api . '></' . $api . '>');
		$this->toXML($array,$this->root);
	}	
	
	public function toXML($array, $root) {
	    foreach($array as $key => $value) {
	        if(is_array($value)) {
	            if(!is_numeric($key)){
	                $subnode = $this->root->addChild($key);
	                $this->toXML($value, $subnode);
	            }
	            else{
	                $this->toXML($value, $this->root);
	            }
	        }
	        else {
	            $this->root->addChild($key,$value);
	        }
	    }
	}
	
	public function render() {
		return $this->root->asXML();
	}

}
Usage:

Code:
<?php
	$array = array('status' => 1, 'message' => 'success!');
		
	$xml = new ArrayToXML;
	$xml->parseXML($array, 'result');
		
	return $xml->render();
?>
#12 · 13y ago
HA
Hackinet
Quote Originally Posted by NextGen1 View Post
I care, and at some point, all the sections in programming will be alive
hmm, it's been 7 years since your post and this section is still dead as fuck and PHP section is still empty.
#13 · 9y ago
MP
MPGBat
Snippets
These snippets are great they help a lot.
gonna add some to notepad++
#14 · 7y ago
Posts 1–14 of 14 · Page 1 of 1

Post a Reply

Similar Threads

  • [Collection]Snippets Vault[C#]By NextGen1 in C# Programming
    21Last post 6y ago
  • Snippets VaultBy NextGen1 in Visual Basic Programming
    112Last post 7y ago
  • [Collection]Snippets Vault[Assembly]By NextGen1 in Assembly
    5Last post 13y ago
  • [Collection]Snippets Vault[Flash]By NextGen1 in Flash & Actionscript
    3Last post 14y ago
  • [Collection]Snippets Vault[D3D]By NextGen1 in DirectX/D3D Development
    0Last post 15y ago

Tags for this Thread

None