PHP - Getting Started With Api - How?
I'm trying to learn how to create a simple API, possibly using REST. I found a lot of online tutorials on how to implement API's but how do I create my own for my own website?
The API I want to make is just for querying simple data and inserting data in the DB. From what I learned, REST does HTTP requests from a XML or JSON file but is REST a script I have to download, I can't find a REST site. I'm confused.. Similar TutorialsI'm going to go for broke here as this is the last thing I can think of that is going to help me learn anything... First things first. I have been reading tutorials and guides and all other things about PHP and playing around with all the codes from these tutorials and guides on my localhost. All work well. Yet, they haven't really taught me a great deal since all the code is already written and it's extremely hard to customize with the limited knowledge I currently have. I do not learn very well from sitting down and reading something that someone else has already written and then trying to work out what all the parts are. When I look at some code - I can usually figure out what is happening and what the code is doing. But it doesn't really help me understand how to write the code myself... So I thought if I made a topic where I get people to help ME write out a complete code.. I would actually learn something as I go along.. asking questions where I need to and building it exactly the way I want it. Note the 'ME' is capitalized. I don't expect everyone else to write it all down for me. I want to write it - have you guys give it the ok and we'll move on to the next bit. I know there will be parts where I am completely lost and I will need people to write down something to keep the whole thing moving. I would then ask questions untill I understood what you have provided. The whole idea of this is to build a User Login/Management system. If anyone is up for supporting this idea and helping me start from scratch let me know. Otherwise I'm not sure what else I'm going to have to do. Hello, I've just begun learning PHP and I've gotten a bit into it, but I'm nowhere near a pro. Now, I've decided to start a project that will, in my opinion, help me learn a lot. I'm just having a bit of trouble understanding exactly how to do a few things. My goal is to take the PHP forum base found here and turn it into something similar to this. I've made changes of my own to this forum base and have already finished the news posting section of it on the front page. (almost, one issue with that, more on that in a sec). I've also removed this portion: if(!$action || !in_array($action,$actions_array)){ $sql1 = "SELECT * FROM `forum_cats` WHERE `admin` < ".$row['admin']."+1"; $res1 = mysql_query($sql1) or die(mysql_error()); $i=1; while($row2 = mysql_fetch_assoc($res1)){ echo "<div id=\"fcontent\">\n"; echo " <div class=\"header\" id=\"header_".$i."\" onMouseOver=\"this.className='headerb'\" onMouseOut=\"this.className='header'\">".$row2['name']."</div>\n"; $sql2 = "SELECT * FROM `forum_sub_cats` WHERE `cid`='".$row2['id']."' AND `admin` < ".$row['admin']."+1"; $res2 = mysql_query($sql2) or die(mysql_error()); while($row3 = mysql_fetch_assoc($res2)){ echo " <div id=\"content\">\n"; echo " <a href=\"./index.php?act=forum&id=".$row3['id']."\">".$row3['name']."</a><br>\n"; echo " " . $row3['desc'] . "\n"; echo " </div>\n"; } echo "</div>\n"; $i++; } }else { from index.php so that instead of the links displayed as they would be on a forum, they can be displayed in a navbar off to the side as on the example site (this). That point leads me to my next point: the navigation bar. I'm looking to create the same sort of look (in terms of layout, not the whole.. dark design harry potter thing) as the example site, but I don't really understand how to make navbars on the sides of the whole.. news section. I just need a basic explanation of how these things can be done, but please do not give things away. After all, it is a learning experience. All help is appreciated, though! Also, let me know if you need any more information or if I was unclear. Thanks, Fae Hi guys, I am new to php and mySQL. I am trying to just learn how to input and output data to a mySQL database. What I want to do is have a single page with a text area and button where a user can enter some text and then press a submit button. When the button is pressed I want the text that the user typed to be entered in my database and then displayed below the text area. If you have any questions about what I am trying to do please ask. Thank you for your help in advance! Hi guys, Just starting to play with PHP Domdocument, only to fail at the very first step: <?php $html = 'test/php/somefile.html' ; if(!empty($html)){ $dom_1 = new domDocument ; $dom_1->loadHTML($html) ; $links = $dom_1->getElementsByTagName('li') ; foreach ( $links as $link) { // echo $link ; echo $link->nodeValue, PHP_EOL; } } ?> When I visit it in a browser I get a WSOD, what am I missing? Hey Guys, Im having a really frustrating problem with this set of PHP: writeConversationFunctions.php <?php session_start(); the function writeMessage($message){ $_SESSION['messagetest'] = $message; $chatLogFile = "log.txt"; $openChatLog = fopen($chatLogFile, 'w') or die("Failed to open Log File."); if($message == "resetnow"){ $message = ""; fwrite($openChatLog, $message); fclose($openChatLog); $_SESSION['lastMessageSize'] = 0; } elseif($message == ""){ } else{ $timestamp = date("h:i"); if(isset($_SESSION['username'])){ $username = $_SESSION['username']; } else{ $username = "Anonymous"; } if($message[0] == "/"){ $commandString = stripslashes($commandString); $commandString = htmlentities($commandString, ENT_QUOTES, 'UTF-8'); $commandString = substr($commandString, 1); $command = explode(" ",$commandString); switch ($command[0]){ case "slap": $name = command[1]; $commandResponse = '<p class="commandText">' ."You slap " . $name . "across the face.</p>"; fwrite($openChatLog, $commandResponse); fclose($openChatLog); break; } } else{ $message = stripslashes($message); $message = htmlentities($message, ENT_QUOTES, 'UTF-8'); $message = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $message); $messageString = ' <p class="message"> <span class="timestamp">' .$timestamp . '</span> <span class="username">' . $username . ': </span>' . $message . '</p>'; fwrite($openChatLog, $messageString); fclose($openChatLog); } } } writeMessage($_POST['message']); ?> Simply, the session at the top will not be created for some reason. The post data is sent from: index.php Code: [Select] <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="styles.css" /> <title>Chatulo.us</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> <script> var n = 0; $(document).ready(function () { var focused = true; $(window).focus(function () { focused = true; f(); }); $(window).blur(function () { focused = false; f(); }); var title = document.title; var f = function () { if (focused) { n = 0; document.title = "Chatulo.us / Home"; } else { // none of that else if needed here, you're only checking is focused or not. if (n == 0) { // now you're checking if its zero, so ... document.title = "Chatulo.us / Home"; } else { // you need ELSE here, otherweise you'll always use this next clause document.title = "(" + n + ") " + "Chatulo.us / Home"; } } }; function playSound(soundfile) { document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"; } $.ajax({ type: "POST", url: "loginHandlers.php", data: { required_function: "checkSession" }, success: function (response) { $('#usernameBox').html(response); } }); $("form#sendMessageForm").submit(function () { var message = $('#messageInputField').attr('value'); $('#messageInputField').val(''); $.ajax({ type: "POST", url: "writeConversationFunctions.php", data: { message: message }, success: function () { update(); } }); return false; }); function update() { $.ajax({ type: "POST", dataType: "json", url: "readConversationFunctions.php", data: { required_function: "readConvo" }, success: function (message) { if (message.newmessage == true) { $('#messageBox').html(message.message); playSound('sounds/pop.mp3'); n = n + 1; f(); } else if (message.newmessage === false) { $('#messageBox').html(message.message); } }, complete: function () { setTimeout(update, 1000) $("#messageBox").attr({ scrollTop: $("#messageBox").attr("scrollHeight") }); } }); } $("form#getUsernameForm").live('submit', function () { var username = $('#usernameInputField').attr('value'); $.ajax({ type: "POST", url: "loginHandlers.php", data: { username: username, required_function: "usernameHandler" }, success: function (response) { $('#usernameBox').html("Processing..."); setTimeout(function () { $('#usernameBox').html(response) }, 1000); } }); return false; }); $("span#logoutText").live('click', function () { $.ajax({ type: "POST", url: "loginHandlers.php", data: { required_function: "removeSession" }, success: function (response) { $('#usernameBox').html("Processing..."); setTimeout(function () { $('#usernameBox').html(response) }, 1000); } }); return false; }); update(); }); </script> </head> <body> <form method="post" name="messageInput" id="sendMessageForm"> <input name="message" id="messageInputField" type="text" autocomplete="off"/> <input name="submit" type="submit" value="Send"/> </form> <div id="messageBox"> </div> <div id="usernameBox"> </div> <span id="dummy"></span> <img src="images/logo.png" width="175" height="50" alt="Logo" id="chatulouslogo"/> </body> </html> Any help with this issue would be GREATLY appreciated! Regards, Cody This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=332465.0 hey guys i'am newb in php and i'am doing some algorithm in php, in some codes i need to use session but in that particular page the code does not know if session_start() has been called or not. wonder to if there is anyway that i can get if session is started or not in my code? thanks in advance I am finally getting my blog started. Actually having allot of fun with it to be honest, so far what I have been thinking about is actually working for a change lol. This is more in some ways to show you what I can do actually aswell, all of the below code is obviously in procedural, but would you change anything at all? I mean I know all of the below code is going to be a matter of preference, it works though so far, but I have been reading a few books and sort of memorised allot of it, all of the code below is my own perceptions of course, what do you think? Here's my logic (I have excluded my 'inc.database.php' file, as that's got my mysql database login details), here it is anyways: Code: [Select] <?php ini_set('display_errors', 1); // include the database connection! require_once 'inc.database.php'; function get_category($category_id) { $sql = 'SELECT category FROM blog_categories WHERE category_id = '.$category_id; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); extract($row); return $category; } // function get_responses($category_id, $post_id){ function get_responses($post_id){ $post_id = mysql_real_escape_string($post_id); $sql = 'SELECT post_title, post_text, date FROM blog_posts WHERE isreply = 1 AND parent = '.$post_id; $result = mysql_query($sql); return mysql_num_rows($result); } require_once 'header.html'; // if user has not selected a category in the URL then display the category links! if(!isset($_GET['category'])) { printf("<p>Please select a blog category</p>\n"); $sql = 'SELECT category_id, category FROM blog_categories WHERE avail = \'Y\' ORDER BY category'; $result = mysql_query($sql); // weird but if there's an error show the user firstly! if(!$result) { printf("<p class=\"error\">Could not contact server, please try again later.</p>"); } else { if(mysql_num_rows($result) > 0) { // else loop and output the category as links, so get can be retrieved the find all the posts: while($row = mysql_fetch_assoc($result)) { extract($row); // turns headings of column names into variables, so dont have to use $row['colname'] in database, like so: printf("<p><a href=\"index.php?category=%d\">%s</a><br /></p>\n", $category_id, $category); } } else { printf("<p>No categories available</p>"); } } } else { // trim the category, so someone isnt being stupid and tries to create like a DOS with empty spaces in the category URL trim($_GET['category']); // removes any blank spaces // if category ident is not empty: if($_GET['category'] != ''){ // make input safe: $category_id = mysql_real_escape_string($_GET['category']); // now need to select from which category it is! $sql = "SELECT post_id, post_title, post_text, date, username, category FROM blog_posts LEFT JOIN blog_users ON blog_posts.user_id = blog_users.user_id INNER JOIN blog_categories ON blog_posts.category_id = blog_categories.category_id WHERE blog_posts.category_id = $category_id AND approved = 1 AND isreply != 1"; $result = mysql_query($sql); printf("\n<h2>%s</h2>\n", get_category($category_id)); // calls a function to get the category name! if(mysql_num_rows($result) > 0) { // display the rows of posts: while($row = mysql_fetch_assoc($result)) { extract($row); printf("<h3>%s</h3>\n %s<br />\n By %s %s \n<br />", $post_title, $post_text, $username, $date); // get the no of replies and maybe even at some point show the oldest replies first: // get_responses($category_id, $post_id); printf("No of comments %d</p>",get_responses($post_id)); } } else { printf("<p>No posts exist in this category</p>\n"); } } else { printf("<p class=\"error\">You did not select a blog category, please try again.</p>"); } } require_once 'footer.html'; ?> Of course with the init_set('display_errors', 1) is set to true just for debugging though, when I am happy with it going live I will make this 0, so no errors appear to the user, but what do you think? It is of course entirely reading from the database, no input on this page, as that will be on other scripts. Thanks and I look forward to any replies, Jez. I've inherited a website (www.bonniebakerlaw.com) and have found that the previous web developer had left the contact form in quite a shambles. As you can see it attempts to use a Captcha to validate users, but does not in fact work! I can leave the entire form blank (including the captcha) and still get to the "Thank You" page indicating the form was correctly submitted (This does not, in fact, actually generate an email correctly)! So before I delve into "Head First PHP & MySQL" to debug and correct the error, I was wondering if some kind person(s) would be good enough to point me to the relevant sections / documentation highlighting the fundamentals of building this type of form correctly coupled with the use of a Captcha as noted. Some code has been REDACTED to protect the innocent. I won't post the HTML of the form as it's available from the web site and is a fairly simple HTML construct. Form Code: Code: [Select] <?php require_once('recaptchalib.php'); // Get a key from https://www.google.com/recaptcha/admin/create $publickey = "REDACTED PUBLIC KEY"; $privatekey = "REDACTED PRIVATE KEY"; # the response from reCAPTCHA $resp = null; # the error code from reCAPTCHA, if any $error = null; # was there a reCAPTCHA response? if ($_POST["recaptcha_response_field"]) { $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if ($resp->is_valid) { echo "You got it!"; } else { # set the error code so that we can display it $error = $resp->error; } } echo recaptcha_get_html($publickey, $error); ?> "Thank You" page Code: Code: [Select] <?php $visitor = $_REQUEST['visitor'] ; $visitormail = $_REQUEST['visitormail'] ; $State = $_REQUEST['State:'] ; $Address = $_REQUEST['StreetAddress'] ; $City = $_REQUEST['City:'] ; $Zip = $_REQUEST['Zip:'] ; $Phone = $_REQUEST['Phone:'] ; $Fax = $_REQUEST['Fax:'] ; $Emailed = $_REQUEST['Emailed'] ; $Phoned = $_REQUEST['Phoned'] ; $Faxed = $_REQUEST['Faxed'] ; $Postaled = $_REQUEST['Postaled'] ; $Description = $_REQUEST['IssueDescription'] ; if ($Emailed == "y") { $req1 = " Email \n" ; } if ($Phoned == "y") { $req2 = " Phone \n"; } if ($Faxed == "y") { $req3 = " Fax \n"; } if ($Postaled == "y") { $req4 = " Postal Mail \n"; } $req = $req1 . $req2 . $req3 . $req4 ; $message = "name: $visitor email: $visitormail Address: $Address City: $City State: $State Zip: $Zip Phone: $Phone Fax: $Fax Requested contact by: $req Description: $Description " ; mail("redacted@somedomain.com", "redacted@somedomain.com: contact page", "$message", "From: $visitormail" ) ; ?> |