web page keep content after refresh server side - html

I would like to create a simple text web page that keeps the content. I want to keep the content saved on the server by what ever means (php or sql is fine).
sessionStorage and localStorage isn't what i'm looking for. Those keep the data on the users computer and doesn't allow other computers to see the same thing.
Thanks

So im kind of confused by your question I assume you mean pull string from mysql and display it on the webpage so here is an example.
<?php
//Connect
$user = 'example';
$password = 'example';
$host = 'example';
$link = mysql_connect($host, $user, $password);
mysql_select_db('example_db');
$handle = mysql_query('SELECT * FROM Example_db');
$row = mysql_fetch_row($handle);
$text = $row[0]; // Retrieve text in database
//Variable name above can be what ever you want it to be.
?>
//Example html
<h1><?php echo $text;></h1>
pard me if i'm wrong if so just tell me and I can see if I can further help you.

Related

unexpected 'if' (T_IF)

I have been getting this T_IF error, but I can't locate any syntax errors. Originally I had the ";" inside of the "" for the sql, but after fixing this the errors continued. I have tried clearing my cache just to be sure that isn't the problem, but no luck.
<?php
require_once 'requires-requires.php';
require 'requires-vars.php';
$mainUser = $row[user];
$coinUser = $mainUser;
$coinExperience = 0;
$coinCoins = 0;
$coinLevels = 0;
$coinUser = mysql_real_escape_string($coinUser);
$coinExperience = mysql_real_escape_string($coinExperience);
$coinCoins = mysql_real_escape_string($coinCoins);
$coinLevels = mysql_real_escape_string($coinLevels);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "localhost";
$user = "username";
$pass = "password";
$dbname = "databasename";
$conn = new mysqli($servername, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$usercheck = $conn->query("SELECT user FROM coinchaser WHERE user = '$coinUser'");
$rows_count_value = mysqli_num_rows($usercheck);
if($rows_count_value != 0){
$usernameMatchErr = "You Have Already Joined This Game";
} else {
$sql = "INSERT INTO coinchaser (user, experience, levels, coins) VALUES ('$coinUser', '$coinExperience', '$coinLevels', '$coinCoins')";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
}
?>
<div class="wrapper">
<h2>GAMES</h2>
<p> Game: Description </p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Coin Chaser">
</div>
</form>
</div>
</body>
</html>
EDIT: Added full code from the page. The $row[user] comes from one of the included files. This was working prior to me attempting to add the code the below it so I know it is fine. The issue remains with the following portion of the code:
$sql = "INSERT INTO coinchaser (user, experience, levels, coins) VALUES ('$coinUser', '$coinExperience', '$coinLevels', '$coinCoins')";
if ($conn->query($sql) === TRUE) {
As far as debugging the php, I was having issues attempting to do so on this laptop. I have been mainly doing javascript/html/css on this laptop and had forgotten that php needed to be installed on it for the debugging to work properly. I am dusting off my older laptop to see if I can get it to boot up to do a quick php debug on it.
I do plan to put the actual backend operations on their own page. For some reason, I find it simpler to see it working all together on a single page atm as I am still learning sql and trying to become more familiar and comfortable with it rather than bouncing between two pages back and forth trying to find any syntax errors I might have made.
EDIT (SOLVED): I solved the issue. I have no idea why, but for some reason it didn't like the database column named "user" being named "user". My spelling was correct, no syntax issue. I simply went into the database, changed the column name to "username", returned to the file and change "user" to "username" and it worked perfectly.
I solved the issue. I have no idea why, but for some reason it didn't like the database column named "user" being named "user". My spelling was correct, no syntax issue. I simply went into the database, changed the column name to "username", returned to the file and change "user" to "username" and it worked perfectly.

Connect to a second database from wordpress

I am trying to connect to my own self created second database using wordpress.
What i am trying to achieve is to extract data from my own database(not wordpress database) on my static wordpress front page.
I use php_everywhere plug in in order for me to write php code in blog post and pages.
I use the following code:
<?php
$servername = "localhost";
$username = "thomas";
$password = "password";
$dbname = "thomas";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from number";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
However i got an error unexpected '"localhost"' (T_CONSTANT_ENCAPSED_STRING).
Not sure why.
See https://stackoverflow.com/search?q=T_CONSTANT_ENCAPSED_STRING
1) When using that plugin, be sure you've used straight quotes and backspace around the php to remove invisible control characters. And be sure the plugin doesn't have limitations on what it can do and ignores paragraph returns in the editor.
2) You're much better off using a page template in your theme and running PHP in a .php file and not in the post/page editor with a plugin. See Page Templates | Theme Developer Handbook | WordPress Developer Resources. Make a page template, add the calls to header, etc., and then work with your PHP in the file itself. Select the page template in the page editor of the page you're publishing in WordPress.
You can create new object for new database connection and use that object to do any operation for external database
$mydb = new wpdb('thomas','password','thomas','localhost');
$rows = $mydb->get_results("select Name from my_table");
You must have to use $mydb in place of $wpdb
Wordpres provide a way to connect the other db.
$mydb = new wpdb('thomas','password','thomas','localhost');
$rows = $mydb->get_results("select Name from number");
foreach ($rows as $row) :
echo "id: " . $row->id. " - Name: " . $row->firstname. " " . $row->lastname. "<br>";
endforeach;

PHP-EWS No Data Received Message

I just downloaded PHP-EWS, installed following the README instructions, and spun up a script to test out its functionalities. When I try running the script in my browser, I get the following message:
I get the same message when I supply a login I know is invalid. It seems I am connecting to my Exchange server, but it's not recognizing the credentials I provide.
Here is the script I am using
<?php
function __autoload($className)
{
$className = str_replace('_','/', $className);
$sFileName = $className . '.php';
if (file_exists($sFileName) && !class_exists($className))
{
require_once $sFileName;
}
// If the above if fails, you're program will terminate, there is no way to catch this.
}
include("ExchangeWebServices.php");
$host = "https://myexchange/EWS/Services.wsdl";
$username = "myusername#mydomain.com";
$password = "mypassword";
$ews = new ExchangeWebServices($host, $username, $password);
$request = new EWSType_FindItemType();
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
// sorts mails so that oldest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Ascending';
$request->SortOrder->FieldOrder[] = $order;
$response = $ews->FindItem($request);
echo '<pre>'.print_r($response, true).'</pre>';
?>
Try testing your access by:
Hitting the server url directly: https://YOUREXCHANGESERVER/EWS/Services.wsdl
You should be prompted for credentials. After you enter your credentials you will be presented with the WSDL definition. If it does not present you a WSDL definition that looks like the example below then check with your administrator on credentials or if there are any firewall blocks put in place.
Example (Partial response):
<wsdl:definitions targetNamespace="http://schemas.microsoft.com/exchange/services /2006/messages"><wsdl:types><xs:schema><xs:import namespace="http://schemas.microsoft.com/exchange/services/2006/messages" schemaLocation="messages.xsd"/></xs:schema></wsdl:types>
A great tool I use in analyzing web services is: SOAP-UI by SmartBear

Ajax POST / GET security

I am building a type of crm using ajax, php and mysql. I am building the solution with GET and POST requests using ajax xhr requests. My question is, what is the best way to make sure these requests are secure from any type of hack or attack. I want to make sure my clients data and this crm is secure.
Right now i am just using long hand ajax/javascript. I don't use much jquery: My request looks something like this:
function getContacts()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","xhr_php/getContacts.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var contact = document.getElementById('contact_id').value;
xmlhttp.send("contact="+contact);
}
my php file looks like this
$contact=$_POST['contact'];
$sql="SELECT *
FROM contacts
WHERE contacts.contact_id = $contact";
So this is the basic method i have used to not only retrieve data but also to insert records and run all other queries. My question is what is the best way to secure these requests and sql queries so that all the data is secure. I want to make sure this is a secure crm solution so that data can't be corrupted, stolen, injected, hacked, etc. Thank you for your help.
This is not secure; it is vulnerable to an SQL injection attack, which has nothing to do with Ajax, POST or GET. You should not be building SQL statements in that way. Your question isn't well suited to Stack Overflow - "How do I make my code secure" is a vast topic that can't be answered in a simple way. If you are building this in a professional capacity, please seek out a more senior developer to help you with this - if you are making basic SQL injection mistakes, then it is very unlikely you will be able to build an entire CRM package on your own while making it secure.
You should use PDO. Following is example code. you can modify it as required.
$host = 'localhost';
$dbname = 'contacts';
$username = 'anyuser';
$password = 'your password';
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//If contact is int value then pass it through intval function
$contact=intval($_POST['contact']);
$sql = 'SELECT * FROM contacts WHERE contacts.contact_id = :contact_id';
$statement = $conn->prepare($sql);
$statement->bindParam(':contact_id', $contact, PDO::PARAM_INT);
$statement->execute();
//Use $result is your page
$result = $statement->fetch(PDO::FETCH_ASSOC);
You can do insert / update with PDO as well
$stmt = $conn->prepare("INSERT INTO Table (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
$stmt->execute();
Hope this helps.
This should be immune to sql injection:
$contact=intval($_POST['contact']);
$sql="SELECT *
FROM contacts
WHERE contacts.contact_id = $contact";
mysql_query($sql);

How come Smart search is so fast in facebook

I am wondering how facebook has implemented the search functinality on the home page. as soon as i type 'a' the dropdown comes with the list of friends and its very very fast..
I saw in firebug that it sends a ajax request to one of its file.
I wanted to implement the same functionality in one of my webapp but even though my table has just 4 records it takes bit time to load the dropdown.
What i have done is
send ajax req with my search parameter
executed sql query
made the html
and returned it so it will
replace the div
Facebook has very expensive servers using a very expensive CDN (Akamai) and uses server-side caching like memcached.
If you can predict with reasonable accuracy the things the user might search for (e.g. a known friends and friends-of-friends list) and pre-cache them on the server you can do this quickly. If you deliver that list with the webpage in the first place and cache it on the client, it will be lightning fast (once the page is loaded anyway).
Try the following PHP code, it will crawl into the Fast Facebook Search site and echo the results. I hope it will be helpful, feel free to tweak it :)
<?php
function facebook_search_api($args, $referer = 'YOUR SITE ADDRESS', $endpoint = 'web')
{
$url = "http://www.FastFacebookSearch.com".$endpoint;
if ( !array_key_exists('v', $args) )
$args['v'] = '1.0';
//$args['key']="ABQIAAAArMTuM-CBxyWL0PYBLc7SuhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxT-uD75NXlWUsDRBw-8aVAlQ29oCg";
//$args['userip']=$_SERVER['REMOTE_ADDR'];
$args['rsz']='8';
$url .= '?'.http_build_query($args, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $referer);
$body = curl_exec($ch);
curl_close($ch);
//decode and return the response
return json_decode($body,true);
}
$query_temp=urldecode(isset($_GET['q'])?$_GET['q']:"none");
$search_type=urldecode(isset($_GET['search_engine'])?$_GET['search_engine']:"");
echo "$search_type Search Results for: $query_temp<br />-----<br />";
$query=$search_type.$query_temp;
$res = google_search_api(array('q' => $query));
$pages=$res['responseData']['cursor']['pages'];
$nres=0;
for($i=0;$i<count($pages);$i++)
{
$res = google_search_api(array('q' => $query,'start'=>$rez['responseData']['cursor']['pages'][$i]['start']));
for($j=0;$j<count($res['responseData']['results']); $j++)
{
$nres++;
echo urldecode("<a href=".$res['responseData']['results'][$j]['url'])."><big>";
echo urldecode($res['responseData']['results'][$j]['title'])."</a></big><br />";
echo urldecode("<font color=green><small>".$res['responseData']['results'][$j]['url'])."</small></font><br>";
echo urldecode("<iiisearch>".$res['responseData']['results'][$j]['content'])."<br><br>";
}
}
echo "<br />---<br />Total number of reuslts: $nres";
?>