Results 1 to 14 of 14
  1. #1
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed

    [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.




     


     


     



    The Most complete application MPGH will ever offer - 68%




  2. #2
    Alen's Avatar
    Join Date
    Oct 2007
    Gender
    male
    Location
    Liquid Generator
    Posts
    27,920
    Reputation
    2548
    Thanks
    4,224
    My Mood
    Fine
    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

  3. #3
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed
    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]
    Last edited by NextGen1; 03-10-2011 at 06:12 PM.


     


     


     



    The Most complete application MPGH will ever offer - 68%




  4. The Following 3 Users Say Thank You to NextGen1 For This Useful Post:

    cosconub (02-06-2011),flameswor10 (12-23-2010),Paul (04-19-2011)

  5. #4
    Paul's Avatar
    Join Date
    Mar 2011
    Gender
    male
    Posts
    6,296
    Reputation
    473
    Thanks
    1,061
    My Mood
    Sleepy
    @NextGen1 wow, thank you DD <3

    i'm learning PHP at the moment for my job and it's kinda weiird :S


  6. #5
    maltray's Avatar
    Join Date
    Apr 2011
    Gender
    male
    Posts
    31
    Reputation
    10
    Thanks
    3
    My Mood
    Drunk
    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...

  7. The Following User Says Thank You to maltray For This Useful Post:

    Paul (08-27-2011)

  8. #6
    KushxOrangeJuice's Avatar
    Join Date
    Jul 2011
    Gender
    male
    Location
    Crossfire/CombatArms/MPGH Story
    Posts
    428
    Reputation
    4
    Thanks
    321
    My Mood
    Bashful
    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!

    MPGH MapleStory Private Server Information Check it out!!


    Currently Learning PHP And C++
    PHP: [||||||||||]
    C++: [||||||||||]

    Read the Thread before you post.
    Need help, ask or pm me.
    Press the thanks button, dont say it.

    [IMG]https://i1210.photobucke*****m/albums/cc417/shmorgoo/forlol.png[/IMG]
    Forum Rules and Etiquette.

    .:Guides&Tools:.
    MSVCR100.dll Error, Menu not showing up? READ THIS GUIDE.
    Need a simple working undetected injector? Click Here


  9. #7
    Paul's Avatar
    Join Date
    Mar 2011
    Gender
    male
    Posts
    6,296
    Reputation
    473
    Thanks
    1,061
    My Mood
    Sleepy
    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


  10. #8
    Paul's Avatar
    Join Date
    Mar 2011
    Gender
    male
    Posts
    6,296
    Reputation
    473
    Thanks
    1,061
    My Mood
    Sleepy
    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


  11. #9
    Shane Thompson's Avatar
    Join Date
    Feb 2012
    Gender
    male
    Posts
    8
    Reputation
    3
    Thanks
    3
    My Mood
    Relaxed
    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...
    <b>Downloadable Files</b> Downloadable Files

  12. The Following 3 Users Say Thank You to Shane Thompson For This Useful Post:

    ariffsj (06-12-2019),Eagle.me (10-22-2012),HalfBajan (01-02-2013)

  13. #10
    Paul's Avatar
    Join Date
    Mar 2011
    Gender
    male
    Posts
    6,296
    Reputation
    473
    Thanks
    1,061
    My Mood
    Sleepy
    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


  14. The Following User Says Thank You to Paul For This Useful Post:

    Battlefieldzocker (03-07-2012)

  15. #11
    Paul's Avatar
    Join Date
    Mar 2011
    Gender
    male
    Posts
    6,296
    Reputation
    473
    Thanks
    1,061
    My Mood
    Sleepy
    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);
    		}
    	}	
    ?>


  16. #12
    jordi.kroon's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Eindhoven
    Posts
    91
    Reputation
    10
    Thanks
    238
    My Mood
    Drunk
    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();
    ?>

  17. #13
    Hackinet's Avatar
    Join Date
    Jun 2014
    Gender
    male
    Posts
    525
    Reputation
    260
    Thanks
    1,024
    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.

  18. The Following 3 Users Say Thank You to Hackinet For This Useful Post:

    prohacku (06-15-2017),thxtesting (06-15-2017),thxtesting2 (06-15-2017)

  19. #14
    MPGBat's Avatar
    Join Date
    Oct 2018
    Gender
    female
    Posts
    17
    Reputation
    10
    Thanks
    5
    My Mood
    Amused

    Snippets

    These snippets are great they help a lot.
    gonna add some to notepad++

Similar Threads

  1. [Collection]Snippets Vault[C#]
    By NextGen1 in forum C# Programming
    Replies: 21
    Last Post: 10-13-2019, 10:48 AM
  2. [Source Code] Snippets Vault
    By NextGen1 in forum Visual Basic Programming
    Replies: 112
    Last Post: 06-14-2019, 07:51 PM
  3. [Collection]Snippets Vault[Assembly]
    By NextGen1 in forum Assembly
    Replies: 5
    Last Post: 11-05-2012, 01:10 AM
  4. [Collection]Snippets Vault[Flash]
    By NextGen1 in forum Flash & Actionscript
    Replies: 3
    Last Post: 10-14-2011, 03:08 AM
  5. [Collection]Snippets Vault[D3D]
    By NextGen1 in forum DirectX/D3D Development
    Replies: 0
    Last Post: 09-28-2010, 08:36 AM