How to Use PHP/MySQL to write a simple web server PART1 for iOS apps

Source: Internet
Author: User
Tags php server


Original article: http://www.raywenderlich.com/2941/how-to-write-a-simple-phpmysql-web-service-for-an-ios-app

As an iPhone/iPad developer, it is useful to write a simple web server by yourself.

For example, you may want to display some updates from the server when the software is started, or save some user data on the server. There is nothing beyond your imagination to limit you.

In the first article, we will build a web server step by step, based on the promo code system (Promotion code system), which I used in my first software, Wild Fables. in the second article, we will write an iOS App to interact with it.

To complete this tutorial, you will need a web server with MySQL and PHP installed. If you do not have one, you have the following options:

  • If you want to run on your Mac (free)Apache/MySQL/PHP, there are many tutorials to help you. Here is a tutorial.
  • If you want to rent a server (which requires money), here is a tutorial.
  • Or you are too lazy. If you do not want to do either of the above two, you can use the server that I created in PART2 in this tutorial.

You do not need to have PHP and MySQL experience (of course better) because this tutorial contains all the code you need.

 

What will you do







Id
: Unique Identifier of the app.

App_id: Unique string of the app.

  • W_promo_code: list of available promotion Codes
  • Id: Unique representation.
  • Rw_app_id: Corresponding App.
  • Code: The character of the Promotion Code entered by the user.
  • Unlock_code: The promotional code character returned to the App.
  • Uses_remaining: The remaining number of times the promotion code can be used.
  • Rw_promo_code_redeemed: Save the information after the Promotion Code is redeemed. To prevent a device from being redeemed multiple times with a promotion code.
  • Id: Unique identifier.
  • Rw_promo_code_id: The Promotion Code ID (from rw_promo_code) that has been redeemed ).
  • Device_id: The device ID that has been redeemed.
  • Redeemed_time: The time of the redemption.

  • DROP TABLE  AUTO_INCREMENT PRIMARY ,,255) NOT ,255) NOT , AUTO_INCREMENT PRIMARY ,255) NOT  AUTO_INCREMENT PRIMARY ,,255) NOT ,

    On your web server, you need to create a MySQL database and create these three tables. Here is the complete command:

    Save the above Code to a file named create. SQL, and then:

    rwenderlich@kermit:~$  -u root -: monitor.  Commands  with ; or \g. connection id is 1286: 5.1.37-1ubuntu5.1-'help;' or '\h'  help. Type '\c' to clear the  input statement.
    
    >, 1 row affected (0.00> > grant all privileges on promos.* to 'username'@'localhost' identified by 'password', 0 rows affected (0.00> :~$  -u username -p promos < create.::~$  -u root -: monitor.  Commands  with ; or \g. connection id is 1417: 5.1.37-1ubuntu5.1-'help;' or '\h'  help. Type '\c' to clear the  input statement.
    
    > >+------------------------+
    | Tables_in_promos       |
    +------------------------+
    | rw_app                 | 
    | rw_promo_code          | 
    | rw_promo_code_redeemed | 
    +------------------------+
    3 rows in set (0.00 sec)

    Three empty tables exist. Next, create a test app:

    INSERT INTO rw_app VALUES(1, 'com.razeware.test'1, 1, 'test', 'com.razeware.test.unlock.cake', 10000);

    Okay. Now that the database is connected, you can write it to the PHP server.

    Verify PHP/MySQL

    Before you start implementing the PHP server, first check whether PHP runs properly on your server. Create a folder named promos on your server, and create a file named index. php in it:

    <?     "Hello, PHP!" = ->?>

    You can use the URL of your server for testing, or test it in the command line as follows:

    Ray-Wenderlichs-Mac-mini-2:~ rwenderlich$ curl http:Hello, PHP!

    Next, expand this class to ensure that your server can connect to the database:

      ->db =  mysqli('localhost', 'username', 'password', 'promos'->db->autocommit(
        ->db->
        
             = ->db->prepare('SELECT id, code, unlock_code, uses_remaining FROM rw_promo_code'->->bind_result(, , ,  (-> " has  uses remaining!"->

    A constructor is added to connect the database with the given user name and password.DestructorTo close the database. Now you can test it:

    Ray-Wenderlichs-Mac-mini-2:~ rwenderlich$ curl http:test has 10000 uses remaining!

    Server policy: GET or POST:

    Okay, now is the time to implement the completed function. But first, let's talk about the web Server policy.

    We know that we need to send some data to the server, including the app ID, redeem it, and the device ID to be redeemed.

    How to send it? There are two methods: GET (normal method) and POST (used to send forms)

    • If you choose GET, the parameter is part of the URL, which is to send the parameter to the URL and then send the request to the server.
    • If you choose POST, the parameter is placed in the request body.

    Every one can meet your needs, but it is better to use POST when you try to do something, such as redeem a promotion code. This is what I will do.

    What does this mean? If we want to access these parameters in PHP, we can use the built-in $ _ POST array:

    ["rw_app_id"]

    We will use ASIHTTPRequest to connect to the server and use the ASIFormDataRequest class to send a POST request:

    ASIFormDataRequest *request = forKey:];

    For more information about GET and POST, see Wikipedia entry.

    Update: Please refer to @ smpdawg's wonderful comments forum topic

     

    Web Server policy: Algorithm

    Next, let's look at the algorithm of the web server to be used:

     

     getStatusCodeMessage(
         = 100 => 'Continue',
            101 => 'Switching Protocols',
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Found',
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            306 => '(Unused)',
            307 => 'Temporary Redirect',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported' (([])) ? [] : ''
     sendResponse( = 200,  = '',  = 'text/html' = 'HTTP/1.1 ' .  . ' ' . getStatusCodeMessage((('Content-type: ' . 

    If you don't understand why we don't want this, it's because this is a web server that complies with the HTTP protocol. When you send a response, you can develop a header containing the error code and detailed descriptions. Standard error codes can be used, but these methods are more convenient to use.

    As you can see, I have a line of defense to convert the status into HTML information.

    The next step is the real implementation!

         ((["rw_app_id"]) && (["code"]) && (["device_id"
             = ["rw_app_id" = ["code" = ["device_id"
             = 0 = ->db->prepare('SELECT id, unlock_code, uses_remaining FROM rw_promo_code WHERE rw_app_id=? AND code=?'->bind_param("is", , ->->bind_result(, ,  (->->
             ( <= 0400, 'Invalid code' 
             ( <= 0403, 'Code already used' 
             = ->db->prepare('SELECT id FROM rw_promo_code_redeemed WHERE device_id=? AND rw_promo_code_id=?'->bind_param("si", , ->->bind_result( (->->
             ( > 0403, 'Code already used' 
             = ->db->prepare("INSERT INTO rw_promo_code_redeemed (rw_promo_code_id, device_id) VALUES (?, ?)"->bind_param("is", , ->->
            ->db->query("UPDATE rw_promo_code SET uses_remaining=uses_remaining-1 WHERE id="->db->
             = "unlock_code" => ,200, json_encode( 400, 'Invalid request' 

    You should be able to read this Code; otherwise, please refer to the following tutorial Mysqli reference. Here are some things I need to point out:

    • Isset is a PHP function used to check whether the variable has been set. Here we use it to ensure that all the required POST parameters are sent.
    • Note that the bind_param method is used instead of putting the passed variables into the SQL statement. This is a safer method. Otherwise, you may be vulnerable to SQL injection attacks.
    • Note that unlock_code is returned in JSON format. Of course, we can directly return a string because we only return one message, but use JSON to facilitate future extension.

    Now, your web server is ready to work. You can use the following command to test:

    curl -F "rw_app_id=1" -F "code=test" -F "device_id=test" http:{"unlock_code":"com.razeware.wildfables.unlock.test"}

    Note: If you test it on my server, if you get the "code already used" error, you should change your device_id.

    You may want to go to your database to check whether there is an rw_promo_code_redeemed entry, and whether uses_remaining is reduced by one.

    Next?


    We look forward to PART2.


    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.