PHP - Creating A Rest Api
I want to create a REST API for my website. What I want to do is to display advertisements from my database on websites that I sell to clients. Their website will call my database for advertisements to display on their websites. Also, I am performing a site validity check where the client's site would send the site URL, site name, and site token to my database for validation. If it returns false then the site will not display as it will be invalid according to my database. I've been Googling this topic all day, but cannot seem to get my head around it. I want to set an API key on my website so that not just anybody can be querying my database. For the advertisement query, no parameters need to be sent from the client websites to my database. Can anyone offer some advice on how to do this?
Similar Tutorials<?php $myData = file_get_contents(""); $myObject = json_decode($myData); $myObjectMap = $myObject->result; ?> can i somehow build in that it only request every 5 minutes because if there are many users on the site it request too much? Hi guys. I'm new to php and struggleing with the REST POST for some reason.... I need to insert a contact into this accouting system http://help.saasu.com/api/#toc-http-post search for Example: Insert Contact. the data strcutre looks like: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <tasks> <insertContact> <contact uid="0"> <salutation>Mr.</salutation> <givenName>John</givenName> <familyName>Smith</familyName> <organisationName>Saasy.tv</organisationName> <organisationAbn>777888999</organisationAbn> <organisationPosition>Director</organisationPosition> <email>john.smith@saasy.tv</email> <mainPhone> 02 9999 9999 </mainPhone> <mobilePhone> 0444 444 444 </mobilePhone> <contactID>XYZ123</contactID> <tags>Gold Prospect, Film</tags> <postalAddress> <street>3/33 Victory Av</street> <city>North Sydney</city> <state>NSW</state> <postCode>2000</postCode> <country>Australia</country> </postalAddress> <otherAddress> <street>111 Elizabeth street</street> <city>Sydney</city> <state>NSW</state> <postCode>2000</postCode> <country>Australia</country> </otherAddress> <isActive>true</isActive> <acceptDirectDeposit>false</acceptDirectDeposit> <directDepositAccountName>John Smith</directDepositAccountName> <directDepositBsb>000000</directDepositBsb> <directDepositAccountNumber>12345678</directDepositAccountNumber> <acceptCheque>false</acceptCheque> <customField1>This is custom field 1</customField1> <customField2>This is custom field 2</customField2> <twitterID>Contact twitter id</twitterID> <skypeID>Contact skype id</skypeID> </contact> </insertContact> </tasks> I only have to insert 3 mandatory fields whcih are in the below code snipit im using but nothings working... Code: [Select] //set POST variables $service_url = 'https://secure.saasu.com/webservices/rest/r1/tasks?wsaccesskey=<key removed>'; $curl = curl_init($service_url); $fileds = array( 'insertContact' => array( 'contact' => array( 'givenName' => urlencode('John'), 'familyName' => urlencode('Smith'), 'organisationName' => urlencode('Saasy.tv') ) ) ); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); $curl_response = curl_exec($curl); curl_close($curl); $xml = new SimpleXMLElement($curl_response); Please help, I'm not sure what I'm doing wrong.... Here is the scenario. I created a niche market API which provides environmental data. The data is obtained by industrial controllers which don't monitor anything by default, and the API has additional endpoints which are used to instruct the industrial controllers to start monitoring some parameter so the API can then start storing the trend data. The API primarily responds with JSON, however, a couple of endpoints support CSV data. For humans/webclients to access the data, I also created a webserver application which can be added to a Concrete5 (C5) CMS. I tried to make as many of its endpoints do nothing except receive the webclient's request, add a JSON Web Token to it which contains a unique identifier, forward it to the API using cURL, and return the response as is to the webclient. To limit the scope which needed to be created for the C5 application, the API has endpoints to return JSON which is used by JavaScript on the webclient for client-side validation, endpoints (actually, a different domain) to return static JavaScript/CSS/etc, and endpoints to restructure the JSON data to some more suitable format. I now am looking at creating different applications which does not use C5, but either are 100% custom or use some other CMS such as Drupal, etc. While I tried to limit the scope implemented on the C5 application, I have much more than I desire and will need to duplicate much for any future application. The primary scope I would like to remove from the webserver application relates to the HTML views and consists of templates which create HTML from JSON, the JavaScript which interacts with the HTML, and to a lesser degree controllers to determine the type of view (i.e. a list of records or one specific detail record). While the API will only be managed by myself, the intent is that the C5, 100% custom, etc webserver apps are installed and managed by others. Ideally, there is some existing Composer package for transforming JSON to HTML which is CMS agnostic, however, I don't know whether such exists. Also, while not 100% necessary, ideally this functionality could exist on my server and not the individual web application's server. Whether I build it myself or use some existing package, I expect it will need to do something like the following: The various webserver apps will have some routing table to proxy the request either to my JSON API server (complete) or my new "HTML API Server" (remaining discusses this portion). This HTML API server would generate the content either by making a cURL request to the main JSON API, or better yet since likely located on the same server have routing functional to make direct calls to the JSON API's methods, and return something like the following: { "html": "<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pharetra massa massa ultricies mi quis hendrerit dolor. Leo integer malesuada nunc vel risus commodo viverra.</div>", "javascript_files": [ "https://resources.myserver.com/someFile.js", "https://resources.myserver.com/someOtherFile.js" ], "css_files": [ "https://resources.myserver.com/someFile.css", "https://resources.myserver.com/someOtherFile.css" ] } The various applications would then take the HTML and resource files and insert them using their proprietary methods. EDIT. Also, thinking of using an IFRAME, however, definitely have concerns with doing so. My day job has nothing to do with software, however, am hoping to make it so. Before embarking on this task, I would like to know whether some existing framework exists and if not what general strategy (organization, caching, etc) I should take to develop it. Thanks Edited January 18 by NotionCommotionAdded IFRAME idea Hello, I'm trying to use a rest-based card clearence service, but I don't know how to pass the information through the URL without using the form action attribute. I need to have a URL looking like this: index.php?p=checkout?service=cardAuth&msg_id=3864&num_md5=e2740266aab85558996a9a87fc561c0e&amount=24.99¤cy=GBP&api_key=739a720ade31ad2a14b30aa7b3a6b20e But at the moment, I have a URL looking like this: index.php?cardAuth=&title=Mr&fname=Alderton&sname=Arkie&ctype=mastercard&cnumber=5105105105105100&smonth=01&syear=07&fmonth=01&fyear=10&checkout=Check+Out There's a few more problems; - I can't get the card number to md5 - I don't know how to retreive a variable used in another file, which counts up the total amount due Here's my PHP: Code: [Select] <h2>Please enter your details</h2> <h3>All fields required</h3> <div id="checkout"> <?php if (isset($_GET['checkout'])){ $title = $_GET['title']; $fname = $_GET['fname']; $sname = $_GET['sname']; $ctype = $_GET['ctype']; $cnumber = md5($_GET['cnumber']); $syear = $_GET['smonth'] . $_GET['syear']; $fyear = $_GET['fmonth'] . $_GET['fyear']; $service = $_GET['cardAuth']; $amount = $_REQUEST[$total]; $msg = rand(1000,9999); $api = 'd41d8cd98f00b204e9800998ecf8427e'; } ?> <form method="get" action="index.php?p=checkout?<?php.'service='.$service.'msg_id='.$msg.'num_md5='.$cnumber.'amount='.$amount.'currency=GBP'.'api_key='.$api.?>"> <table> <tr> <td><input type="hidden" name="cardAuth" value="<?php if (!empty($service)) echo $service; ?>" /></td> </tr> <tr> <td> Title: </td> <td> <select name="title" value="<?php if (!empty($title)) echo $title; ?>" > <option></option> <option>Mr</option> <option>Sir</option> <option>Ms</option> <option>Miss</option> <option>Mrs</option> </select> </td> </tr> <tr> <td> First Name: </td> <td> <input type="text" name="fname" value="<?php if (!empty($fname)) echo $fname; ?>"/> </td> </tr> <tr> <td> Surname: </td> <td> <input type="text" name="sname" value="<?php if (!empty($sname)) echo $sname; ?>"/> </td> </tr> <tr> <td> </td> </tr> <tr> <td> Card Type: </td> <td> <select name="ctype" value="<?php if (!empty($ctype)) echo $ctype; ?>"> <option>mastercard</option> <option>visa</option> <option>amex</option> <option>solo</option> <option>maestro</option> <option>jcb</option> <option>diners</option> </select> </td> </tr> <tr> <td> Card Number: </td> <td> <input type="text" name="cnumber" value="<?php if (!empty($cnumber)) echo $cnumber; ?>"/> </td> </tr> <tr> <td> Valid From: </td> <td> <select name="smonth" value="<?php if (!empty($smonth)) echo $smonth; ?>"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> <select name="syear" value="<?php if (!empty($syear)) echo $syear; ?>"> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> </select> </td> </tr> <tr> <td> Expires End: </td> <td> <select name="fmonth" value="<?php if (!empty($fmonth)) echo $fmonth; ?>"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> </select> <select name="fyear" value="<?php if (!empty($fyear)) echo $fyear; ?>"> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> </select> </td> </tr> <tr> <td> </td> </tr> <tr> <td> </td> <td> <input type="submit" name="checkout" value="Check Out"/> </td> </tr> </table> </form> </div> I tried to find working tutorial for REST API and with these two frameworks but nothing what i found worked.Basicly i want to attach REST API
to a simple CRUD application.
So if anyone have links with good explanation that would be good.
Specific question with general application here. i am having some trouble with a loop and am getting some odd timing results specifically this is a WMI query on a hyper-v server retrieving disk information but im not sure the context of the query is relevant here. The main question is how come the first iteration of the loop is so much slower than the other iterations, it just doesnt seem to make sense to me unless ive done something stupid here i cannot see. any ideas ? Code: [Select] <?php $diskstart = microtime(true); // get the hard disk size try { $resultDisk = $wmi->ExecQuery("SELECT BlockSize,NumberOfBlocks FROM msvm_LogicalDisk where systemname like '%" . $guid . "%' and name='Hard Disk Image'"); $ct=0; $start1 = microtime(true); $start = microtime(true); foreach($resultDisk as $itemDisk) { $end = microtime(true); echo "<BR>FOREACH: [" . Round($end-$start,3) . "] seconds"; $vm[$name]['disks'][$ct] = ($itemDisk->BlockSize * $itemDisk->NumberOfBlocks)/1024; // format the disk size into KB $ct++; $start = microtime(true); } $end1 = microtime(true); echo "<br> ALLLOOP: [" . Round($end1-$start1,3) . "] "; } catch(exception $e) { } $diskend = microtime(true); echo "<br>DISK: [" . ($diskend-$diskstart) . "] seconds"; ?> and here are the results Code: [Select] FOREACH: [1.236] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.002] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds FOREACH: [0.001] seconds ALLLOOP: [2] DISK: [2.1837468147278] seconds Hi, I am using the Google map API to display some businesses on a map - the sequence is map and below it a list of the establishments from a DB. Before I put the google map in, the list of establishments in the while table loop worked correctly. Now the map is there - that works, but the looping table doesnt display - I feel that it may be something to do with Code: [Select] <?php while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) { ?> new google.maps.LatLng(<? echo $row['latitude'] ?>, <? echo $row['longitude']?>), <?php ; } ?> and the second fetch array - Code: [Select] while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) Any Advice? Code: [Select] <?php // *******************************below is bit that selects hotels based on outcode of postcode and prints table with links to details pages $sql2 = "SELECT * FROM hotels WHERE (SUBSTRING_INDEX(est_postcode, ' ', 1)) IN ('$matches') "; $result2 = mysql_query($sql2) or die('query failed: ' . mysql_error()); $num_rows = mysql_num_rows($result2); echo "<p> Your search has found ".$num_rows . " establishment(s) </p>"; ?> <script type="text/javascript"> var berlin = new google.maps.LatLng(<? echo $lat2 ?>, <? echo $lng2 ?>); var neighborhoods = [ <?php while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) { ?> new google.maps.LatLng(<? echo $row['latitude'] ?>, <? echo $row['longitude']?>), <?php ; } ?> ]; var markers = []; var iterator = 0; var map; function initialize() { var mapOptions = { zoom: 12, mapTypeId: google.maps.MapTypeId.ROADMAP, center: berlin }; map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); } function drop() { for (var i = 0; i < neighborhoods.length; i++) { setTimeout(function() { addMarker(); }, i * 200); } } function addMarker() { markers.push(new google.maps.Marker({ position: neighborhoods[iterator], map: map, title:"Hello World!", draggable: false, animation: google.maps.Animation.DROP })); iterator++; } </script> <div id="map_canvas" style="width: 614px; height: 400px;">map div</div> <button id="drop" onclick="drop()">Drop Markers</button> <?php echo "<table id ='results' border=0>"; while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) { echo "<tr>"; echo "<td><a class='blueboldtitle' href='bandb.php?id=". $row["id"] . "'>" . ucwords(strtolower($row["est_name"])) ."</a></td><td>" . $row["est_postcode"] ."</td><td> ". $row["est_areacode"]." ". $row["est_landline"] ."</td><td><a href='bandb.php?id=". $row["id"] . "'>[More Info] </a></td>"; echo "</tr>"; } echo "</table>"; ?> Hi, I have used the following script to consume REST webservices provided by Commission Junction. I'm able to get the response but the response is not in xml format. <?php $targeturl="https://support-services.api.cj.com/v2/countries"; $CJ_DevKey= "xxxxxxxxx"; // return xml feed from CJ $ch = curl_init($targeturl); curl_setopt($ch, CURLOPT_POST, FAlSE); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$CJ_DevKey)); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($ch); curl_close($ch); echo $response; // will print in browser all country codes in an xml format /* ADD YOUR OWN CODE HERE TO DO WHAT YOU WANT WITH THE RESPONSE. MAYBE SAVE RESULTS TO A FILE OR THE PARSE THE RESULTS INTO A DATABASE? */ ?> I'm just confused. Isn't that the response when using REST webservices is always in xml format. Please correct me if I'm wrong. Would someone please have a look at this script and suggest me what I need to do in order to get the response in xml ? I want to save the response in xml file and then process it later. please see my current sample output here. www(dot)uedeals(dot)com/cj/cj3.php Do you use the OS userids or do you keep them separate in MYSQL? Must users login to a website and request a token to use for REST API requests? Did you use a framework provided method? I need something ultra-simple I have the following tables: department id course id department_id CASCADE DELETE student id student_courses course_id CASCADE DELETE student_id CASCADE DELETEI also have the following REST API endpoints: DELETE department/123 (deletes targeted department and associated courses as well as the list of students in the course) DELETE course/321 (deletes targeted course as well as the list of students in the course) DELETE student/111 (deletes targeted student as well as the list of students in the course)The user should be informed before deleting a given record if that record will affect other tables. For instance, if deleting a department which has some courses or deleting a student which belows to a course. One option is to respond to DELETE department/123 with 400 {recordUsed: {courses:[bla, bla], student_courses:[bla, bla]}} if used. For this option, the client would then prompt the user of the implications and if desired repeat the request but include a "force" parameter of TRUE in the request which will delete the record regardless of being used. Another option is to add some new endpoints which will return the resources which are associated with the to be deleted entity. If empty, a DELETE request would automatically be made and if not empty the user will first be prompted whether the DELETE request should be made and the server would delete the record(s) regardless of being used. GET department/utilized/123 GET course/utilized/321 GET student/utilized/111Any thoughts on which approach should be used? Or maybe some other strategy? Thanks I implemented an endpoint which receives name/value pairs: PUT someresource/123 {"name": "description", "value": "Some new description"} I think I made a mistake, and should have implemented it as: PUT someresource/123 {"description": "Some new description"} The reason I think so is updating multiple properties is only (easily) possible using the later: PUT someresource/123 {"description": "Some new description", "otherProperty": "bla bla bla"} Assuming I am not using some 3rd party client library which only works with name/value pairs, any compelling reason why one shouldn't default to the later approach with key/values? I actually have two parts to this post. One which describes just my understanding on how a multipart request should look with a REST API and gives a little context, and the second how to actually implement it using Sympony and api-platform. Part 1 Looking to simultaneously upload a file, some file meta data, and identifier of the uploading user to a REST API, and will do so using a multipart request. Based on swagger, looks like the request should look something like the following: POST /upload HTTP/1.1 Content-Length: 428 Content-Type: multipart/form-data; boundary=abcde12345 --abcde12345 Content-Disposition: form-data; name="id" Content-Type: text/plain 123e4567-e89b-12d3-a456-426655440000 --abcde12345 Content-Disposition: form-data; name="address" Content-Type: application/json { "street": "3, Garden St", "city": "Hillsbery, UT" } --abcde12345 Content-Disposition: form-data; name="profileImage "; filename="image1.png" Content-Type: application/octet-stream {…file content…} --abcde12345-- Background noise... The above example shows three parts which include the text ID, JSON address and octet-stream file. Doing so doesn't make sense to me and I will probably just have two parts for the meta data JSON. Note that potentially, I will be removing the user from the JSON payload and including it in some JWT header. Also, showing resources as links such as /api/users/1 in the request and response JSON is new to me, but I guess makes sense. Regardless, my meta data JSON will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "user": "/api/users/1" } and the response will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "uploadAt": "2021-01-27 08:41:17", "fileName": "pressuresensor.pdf". "user": "/api/users/1". "file": "/api/uplodaed_files/1234" } Am I somewhat going down the right path? Part 2 Wow, should have looked into Sympony before now! Entities, validation, the API, etc were a breeze. Still confused with some of the "magic", but understanding what is under the hood more and more. As stated initially, I am utilizing api-platform and am looking at api-platform's file-upload. I guess the first question is whether my POST request with both the file and JSON meta data can be performed in a single request. Per making-a-request-to-the-media_objects-endpoint: QuoteYour /media_objects endpoint is now ready to receive a POST request with a file. This endpoint accepts standard multipart/form-data-encoded data, but not JSON data. What? Am I reading this correct? Do I first need to make a multipart requests using either a standard HTML form or a XMLHttpRequest which just sends the file, receive the document locator, and then send a second request with the location and my meta data? If so, I guess I have enough to go forward. I would rather, however, perform the work in a single request. My previous mentioned swagger multipart-requests shows both in the same request. symfonycasts's api-uploads also describes doing so, but not with api-platform. Is there a way to do so with api-platform? Does it make sense to use api-platform for all other routes but then make a custom route for document with meta data uploads? Any recommendations are much appreciated. Thanks So what i mean is if i set a variable to "[" ($some_variable = "[") the rest of my code is now going to go CRAZY because there is an open [. Is there a way I can just make everything inside the first set of "" not relevant to the code? thanks! Dear Friends. Just now I tried to create PHP to make Rest API for my mobile application and I would like to know that it's good coding and need any improve? it is my first time for Rest API. normally I just connect to PHP file directly on .htaccess RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([0-9A-Za-z_]+)$ function.php?func=$1 [L,QSA] RewriteRule ^([0-9A-Za-z_]+)/$ function.php?func=$1 [L,QSA] on function.php $func = $_GET['func']; switch( $func) { case 'lab_info': //ໜ້າຫຼັກ define( '_FUNC', 'lab_info.php'); break; case 'customer_info': //ຂໍ້ມູນຜູ້ໃຊ້ define( '_FUNC', 'customer_info.php'); break; default: // No function define( '_FUNC', 'functionnotfound.php'); break; } if( defined( '_FUNC') && constant( '_FUNC') !='') require( "func/" . _FUNC); on customer_info.php $error = array(); if(isset($_POST['user']) != 'lung'){ $error['status'] = "422"; $error['title'] = "Authentication Fail"; $error['detail'] = "Invalid user authentication"; echo json_encode($error);die(); } if(!isset($_POST['user'])){ $error['status'] = "401"; $error['title'] = "Invalid Attribute"; $error['detail'] = "Invalid Attribute For Information"; echo json_encode($error);die(); } $result = $conn->query("select Lab_Name,Lab_Username,Lab_Password from tb_labmanagers"); $customer = array(); while($row =mysqli_fetch_assoc($result)) { $customer[] = $row; } echo json_encode($customer); this image attached file is result from postman, client need to send user = 'lung' to get information
This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=350052.0 Ok, I have one database three tables. Table 1 is ncmr the main table where everything is to be entered. Table 2 is companies, where all the companies in pull down menu 1 is located. Table 3 is fabricators, where all the people who have had hands on the product are residing. I want the selected choices of table 2 and 3 to be inputed into table 1. I know this has to be possible, but I don't know how. I thought I wrote the code correctly, but it seems not. Can someone review my code and show me where my mistake is? Here is the page: http://kaboomlabs.com/PDI/post2.php Thanks. Code: [Select] <?php require_once('connectvars.php'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to MySQL server.'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>PDI Non-Conforming Materials Report</title> <link rel="stylesheet" type="text/css" href="CSS/postie.css" /> </head> <body> <div id="logo"> <img src="images/PDI_Logo_2.1.gif" alt="PDI Logo" /> </div> <div id="title"> <h3 id="NCMR2">Non-Conforming Materials Report (NCMR)</h3> </div> <?php //Post Data if (isset($_POST['submit'])) { $ab = mysqli_real_escape_string($dbc,$_POST['ab']); $date = mysqli_real_escape_string($dbc,date('Y-m-d',strtotime ($_POST['date']))); $part = mysqli_real_escape_string($dbc,$_POST['part']); $rev = mysqli_real_escape_string($dbc,$_POST['rev']); $partdesc = mysqli_real_escape_string($dbc,$_POST['partdesc']); $ncmrqty = mysqli_real_escape_string($dbc,$_POST['ncmrqty']); $comp = mysqli_real_escape_string($dbc,$_POST['comp']); $ncmrid = mysqli_real_escape_string($dbc,$_POST['ncmrid']); $rma = mysqli_real_escape_string($dbc,$_POST['rma']); $jno = mysqli_real_escape_string($dbc,$_POST['jno']); $fdt = mysqli_real_escape_string($dbc,$_POST['fdt']); $cof = mysqli_real_escape_string($dbc,$_POST['cof']); $fab1= mysqli_real_escape_string($dbc,$_POST['fab1']); $fab2= mysqli_real_escape_string($dbc,$_POST['fab2']); $fab3= mysqli_real_escape_string($dbc,$_POST['fab3']); $non= mysqli_real_escape_string($dbc,$_POST['non']); $dis= mysqli_real_escape_string($dbc,$_POST['dis']); $comm= mysqli_real_escape_string($dbc,$_POST['comm']); $caad= mysqli_real_escape_string($dbc,$_POST['caad']); $po= mysqli_real_escape_string($dbc,$_POST['po']); $pod = mysqli_real_escape_string($dbc,date('Y-m-d',strtotime($_POST['pod']))); $dri = mysqli_real_escape_string($dbc,date('Y-m-d',strtotime($_POST['dri']))); $output_form = 'no'; if (empty($ab) || empty($date) || empty($part) || empty($partdesc)){ // We know at least one of the input fields is blank echo '<div id="alert">'; echo 'Please fill out all of the required NCMR information.<br />'; echo '</div>'; } $output_form = 'yes'; } //Access the Database if (!empty($ab) && !empty($date) && !empty($pod)) { $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to MySQL server.'); $query = "INSERT INTO ncmr (ab, date, part, rev, partdesc, ncmrqty, comp, ncmrid, rma, jno, fdt, cof, fab1, fab2, fab3, non, dis, comm, caad, po, pod, dri) VALUES ('$ab','$date','$part','$rev','$partdesc','$ncmrqty','$comp','$ncmrid','$rma','$jno','$fdt','$cof','$fab1','$fab2','$fab3','$non','$dis','$comm','$caad','$po','$pod','$dri')"; $data = mysqli_query($dbc, $query) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query"); // Confirm success with the user echo '<tr><td class="thank">'; echo '<p>Thank you for adding the NCRM, the correct person will be informed.</p>'; echo '<p><a href="post.php"><< Back to the form</a></p>'; $output_form = 'no'; echo '</td></tr>'; mysqli_close($dbc); } if ($output_form == 'yes') { echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>"; echo '<fieldset>'; //Part, Rev, Part Description, NCMR Qty echo '<div id="box1">'; echo '<div id="ab"><span class="b">Added By: </span><input type="text" name="ab" value="" /></div>'; echo '<div id="date"><span class="b">Date Filed: </span><input type="text" name="date" value="" /></div>'; echo '<div id="part"><span class="b">Part Number: </span><input type="text" name="part" value="" /></div>'; echo '<div id="rev"><span class="b">Part Revision: </span><input type="text" name="rev" value="" /></div>'; echo '<div id="partdesc"><span class="b">Part Description: </span><textarea name="partdesc" rows="3" cols="22" ></textarea></div>'; echo '<div id="ncmrqty"><span class="b">NCMR Qty: </span><input type="text" name="ncmrqty" value="" /></div>'; echo '</div>'; //Company, Customer NCMR, Internal RMA, and Job Number echo '<div id="box2">'; echo'<div id="comp">'; echo '<span class="b">Company: </span>'; $mysqli->select_db('comp'); $result = $mysqli->query("SELECT * FROM comp"); $i = 0; echo "<SELECT name='comp'>\n"; while($row = $result->fetch_assoc()) { if ($i == 4) echo '<option value="lines">-----</option>'; echo "<option value='{$row['user_id']}'>{$row['name']}</option>\n"; $i++; } echo "</select>\n"; echo '</div>'; echo '<div id="ncmrid"><span class="b">Customer NCMR ID: </span><input type="text" name="ncmrid" value="" /></div>'; echo '<div id="rma"><span class="b">Internal RMA #: </span><input type="text" name="rma" value="" /></div>'; echo '<div id="jno"><span class="b">Job #: </span><input type="text" name="jno" value="" /></div>'; echo '</div>'; //Type of Failure and Class of Failure echo '<div id="box3">'; echo '<h2>Failure</h2>'; echo '<div id="fdt">'; echo '<span class="b">Failure Due To: </span><br />'; echo '<select name="fdt">'; echo '<option value="none">----None----</option>'; echo '<option value="In House">In House</option>'; echo '<option value="Third Party">Third Party</option>'; echo '</select>'; echo '</div>'; echo'<div id="cof">'; echo '<span class="b">Class of Failu </span><br />'; echo '<select name="cof">'; echo '<option value="none">----None----</option>'; echo '<option value="Materials">Materials</option>'; echo '<option value="Fabrication">Fabrication</option>'; echo '<option value="Drawing">Drawing</option>'; echo '<option value="Assembly">Assembly</option>'; echo '<option value="Testing">Testing</option>'; echo '<option value="Electrical">Electrical</option>'; echo '<option value="Programming">Programming</option>'; echo '<option value="Machining">Machining</option>'; echo '<option value="Inspection">Inspection</option>'; echo '<option value="Purchasing">Purchasing</option>'; echo '<option value="Administrator">Administrator</option>'; echo '</select>'; echo '</div>'; echo '</div>'; //Fabricators echo '<div id="box4">'; echo '<h2>Fabricators</h2>'; echo'<div id="fab1">'; $mysqli->select_db('user'); $result = $mysqli->query("SELECT * FROM user"); echo "<SELECT name='fab1'>\n"; while($row = $result->fetch_assoc()) { echo "<option value='{$row['user_id']}'>{$row['user']}</option>\n";} echo "</select>\n"; echo '</div>'; echo'<div id="fab2">'; $mysqli->select_db('user'); $result = $mysqli->query("SELECT * FROM user"); echo "<SELECT name='fab2'>\n"; while($row = $result->fetch_assoc()) { echo "<option value='{$row['user_id']}'>{$row['user']}</option>\n";} echo "</select>\n"; echo '</div>'; echo'<div id="fab3">'; $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $mysqli->select_db('user'); $result = $mysqli->query("SELECT * FROM user"); echo "<SELECT name='fab3'>\n"; while($row = $result->fetch_assoc()) { echo "<option value='{$row['user_id']}'>{$row['user']}</option>\n";} echo "</select>\n"; echo '</div>'; echo '</div>'; //Nonconformity, Disposition, Comments and Comments & Additional Details echo '<div id="box5">'; echo '<div id="non"><span class="b">Nonconformity: </span><br /><textarea name="non" rows="3" cols="110" ></textarea><br /></div>'; echo '<div id="dis"><span class="b">Disposition: </span><br /><textarea name="dis" rows="3" cols="110" ></textarea></div>'; echo '<div id="comm"><span class="b">Comments: </span><br /><textarea name="comm" rows="3" cols="110" ></textarea></div>'; echo '<div id="caad"><span class="b">Comments and/or Additional Details: </span><br /><textarea name="caad" rows="3" cols="110" ></textarea></div>'; //PO, PO Date, and Date Recieved echo '<div id="podr">'; echo '<div id="po"><span class="b">PO: </span><input type="text" name="po" size="7" value="" /></div>'; echo '<div id="pod"><span class="b">PO Date: </span><input type="text" name="pod" size="7" value="" /></div>'; echo '<div id="dri"><span class="b">Date Received: </span><input type="text" name="dri" size="7" value=""'; echo '</div>'; echo '<div id="button"><input type="submit" value="Submit NCMR" name="submit" /></div>'; echo '</div>'; echo '</fieldset>'; echo '</form>'; } ?> </body> </html> Hello everyone, I found a tutorial on creating a pdf with php and I just tried to create a basic pdf to see if it worked and modify it from there. Here is the link to the tutorial: http://www.astahost.com/info/tfclt-create-pdf-php-create-fly-pdf-web-server.html Well, after uploading the following php file to the server and testing it, I got this error: Fatal error: Call to undefined function pdf_new() in /home/caresa6/public_html/BubblyBounce.com/admin/pdftest.php on line 2 Here's the code that produced the error: Code: [Select] <?php $mypdf = PDF_new(); PDF_open_file($mypdf, ""); PDF_begin_page($mypdf, 595, 842); $myfont = PDF_findfont($mypdf, "Times-Roman", "host", 0); PDF_setfont($mypdf, $myfont, 10); PDF_show_xy($mypdf, "Sample PDF, constructed by PHP in real-time.", 50, 750); PDF_show_xy($mypdf, "Made with the PDF libraries for PHP.", 50, 730); PDF_end_page($mypdf); PDF_close($mypdf); $mybuf = PDF_get_buffer($mypdf); $mylen = strlen($mybuf); header("Content-type: application/pdf"); header("Content-Length: $mylen"); header("Content-Disposition: inline; filename=gen01.pdf"); print $mybuf; PDF_delete($mypdf); ?> Can anyone help me figure out what to do from here? I have some PHP knowledge, but I'm treading in uncharted waters with this, so I am totally lost. Thanks in advance. I want to create an image using pre-existing image files. I want to use more than one file, otherwise I would use the imagecreatefromjpg function. What function should I use to create an image using a for statement to determine how many of each image is being displayed in the new image? I need help making the variable $code in sessions.php to work with the email activation. sessions.php Code: [Select] <?php include(MODEL_PATH.'user.php'); switch ($route['view']){ case "register": break; case "signup": $errors = validate($register_validations, $params['register']); if($errors) { //$route['view'] = 'index'; $route['view'] = 'register'; //print_r($errors); flash_warning('Please correct errors!'); } else { $code = I need this variable to included the random number created in user.php so it can be sent in the email; $register = $params['register']; $username = $register['screen_name']; $to = $register['user_email']; $subject = "Activate your account"; $headers = "From: richard@whatsyouraction.com"; $body = "Hello $username,\n\nYou registered and need to activate your account by clicking the link below\n\nhttp://whatsyouraction.com/chatbox/emailactivation/activate?code=$code\n\nThanks!"; if (!mail($to,$subject,$body,$headers)) { flash_warning('We couldn\'t sign you up at this time. Please try again later.'); $route['view'] = 'register'; } else { create_user($params['user']); flash_notice('Successfully registered!'); redirect_to('sessions/login'); } } break; } ?>user.php Code: [Select] <?php function create_user($params) { db_connect_posts(); $code = rand(11111111,99999999); $query = sprintf("INSERT INTO users SET users.screen_name = '%s', users.user_email = '%s', users.user_pwd = '%s', users.image = '%s', created_at = NOW(), users.code = $code, users.active = '0'" , mysql_real_escape_string($params['screen_name']), mysql_real_escape_string($params['user_email']), md5($params['user_pwd']), mysql_real_escape_string($params['image']) ); $result = mysql_query($query); if(!$result) { return false; } else { return true; } } ?>register.php Code: [Select] <form action="<?php echo '/'.APP_ROOT.'/'; ?>sessions/signup" method="post"> <fieldset> <legend>Register</legend> <div> <label>Screen Name</label> <input name="register[screen_name]" size="40" type="text" /> </div> <div> <label>E-mail</label> <input name="register[user_email]" size="40" type="text" /> </div> <div> <label>Password</label> <input name="register[user_pwd]" size="40" type="password" /> </div> <div> <label>Image</label> <input name="register[image]" size="40" type="text" /> </div> <input type="submit" name="submit" value="Register" /> </fieldset> </form> |