Twitter Search API - PHP multiple word search not working - forms

I have a simple search bar, user types in a search terms and tweets that match the search terms should show up. However, it only works for single word searches.
<div id="search">
<form action="" method="get">
<label>
Search:
<input type="text" name="search_box" id="search_box" />
<input type="submit" name="submit" id="submit" value="Search" />
</label>
</form>
</div>
<?php
$q=$_GET['search_box'];
$search = "http://search.twitter.com/search.atom?q=".$q."";
$tw = curl_init();
curl_setopt($tw, CURLOPT_URL, $search);
curl_setopt($tw, CURLOPT_RETURNTRANSFER, TRUE);
$twi = curl_exec($tw);
$search_res = new SimpleXMLElement($twi);
echo "<h3>Twitter search results for '".$q."'</h3>";
foreach ($search_res->entry as $twit1) {
$description = $twit1->content;
$message = $row['content'];
echo "<div class='text'>".$description."</div><br><br>";
}
curl_close($tw);
?>

If you're searching with quotation marks for exact phrase matches then you need to escape these quotes before constructing your query string. With the current code:
$q = $_GET['q']
$search = "http://search.twitter.com/search.atom?q=".$q."";
the input "test phrase" will result in this expression (which will probably cause a parse error):
"http://search.twitter.com/search.atom?q="test phrase"";
Instead, try urlencoding the user input before including it in the search string:
$q = urlencode($_GET['q']);
$search = "http://search.twitter.com/search.atom?q={$q}";
Which should result in the value:
http://search.twitter.com/search.atom?q=%22test%20phrase%22
You can check that this works by entering the URL in your browser.

Edit:
Here's the best resource for the Twitter Search API: https://dev.twitter.com/docs/using-search
For matching exact phrases, simply wrap the query string in qoutes.
--
In the Twitter API, any phrases are logicals ANDs, while comma separated values are logical ORs.
"Comma separated keywords and phrases are logical ORs, phrases are logical ANDs.
Words within phrases are delimited by spaces. A tweet matches if any phrase matches.
A phrase matches if all of the words are present in the tweet. (e.g. the twitter is the
AND twitter, and the,twitter is the OR twitter.). Terms are exact-matched, and also
exact-matched ignoring punctuation."
This is actually from the Streaming API but I believe that it also applied to the search API (somebody please correct me if I'm wrong!).
Let's consider what this means for a trivial example:
Tweet: "This is a tweet about grapefruit"
Will be matched with query:
tweet
grapefruit
tweet grapefruit
but not with:
pineapple
grapefruit pineapple
If you were searching for tweets wither either "pineapple" or "grapefruit" in, then your query parameter would need to be:
"grapefruit,pineapple".

$q = $_GET['search_box']." is";
$search = "http://search.twitter.com/search.atom?q=%22".urlencode( $q )."%22";

Related

Secure SQL update in PHP

As part of a job I want to update a database using a form. Since the database is large and is used by many users, I hope that this manipulation is at least secure for more safety.
HTML script :
<form action="http://localhost/modifier_infos_signaletique.php" method=POST >
<div class="id_sign">
<h5>Id "Signalétique" :</h5>
<input type="text" name="id_sign" id="id_sign"/><br>
</div>
<h5>Infos "Signalétique" : </h5>
<input class="comment" type="text" id="maj_infos" name="maj_infos" required maxlength='140'/><br>
<input type="submit" value="Submit" />
</form>
PHP script:
<?php
$user = 'xxxx';
$pass = 'xxxx';
try{
$dbconn = new PDO('pgsql:host=localhost;port=5432;dbname=xxxx',$user, $pass);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$maj = $_POST['maj_infos'];
$id = $_POST['id_sign'];
$query = $dbconn->prepare("UPDATE signaletique SET infos = ':infos' WHERE id = ':id'");
$query->bindParam(':infos', $maj, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
echo 'Données mises à jour';
}
catch(PDOException $e){
echo "Erreur : " . $e->getMessage();
}
?>
However, when I use this script this error appears:
**Erreur : SQLSTATE[HY093]: Invalid parameter number: :infos **
The error would be due to the parameter used for the bindParam function.
However, I have in the properties of my PostgreSQL database, info in "character varying". I tried to change this parameter to "text", but the error remains the same.
Forgive me for this question but I am new to PHP and my SQL skills are thin since I use pgAdmin and its tools a lot to build and interact with my databases.
Here is a screenshot of my database :
The info parameter is in "text" on the screenshot but basic this property was in "character varying" (140).
Thank you for your help.
In your query string you put single quotes around your placeholders. This makes them strings, not placeholders. You do not need quotes when using placeholders.
This should work:
$query = $dbconn->prepare("UPDATE signaletique SET infos = :infos WHERE id = :id");
See https://stackoverflow.com/questions/10966251/sqlstatehy093-invalid-parameter-number-parameter-was-not-defined for more information.

DOMXPath multiple contain selectors not working

I have the following XPath query that a kind user on SO helped me with:
$xpath->query(".//*[not(self::textarea or self::select or self::input) and contains(., '{{{')]/text()") as $node)
Its purpose is to replace certain placeholders with a value, and correctly catches occurences such as the below that should not be replaced:
<textarea id="testtextarea" name="testtextarea">{{{variable:test}}}</textarea>
And replaces correctly occurrences like this:
<div>{{{variable:test}}}</div>
Now I want to exclude elements that are of type <div> that contain the class name note-editable in that query, e.g., <div class="note-editable mayhaveanotherclasstoo">, in addition to textareas, selects or inputs.
I have tried:
$xpath->query(".//*[not(self::textarea or self::select or self::input) and not(contains(#class, 'note-editable')) and contains(., '{{{')]/text()") as $node)
and:
$xpath->query(".//*[not(self::textarea or self::select or self::input or contains(#class, 'note-editable')) and contains(., '{{{')]/text()") as $node)
I have followed the advice on some questions similar to this: PHP xpath contains class and does not contain class, and I do not get PHP errors, but the note-editable <div> tags are still having their placeholders replaced.
Any idea what's wrong with my attempted queries?
EDIT
Minimum reproducible DOM sample:
<div class="note-editing-area">
<textarea class="note-codable"></textarea>
<div class="note-editable panel-body" contenteditable="true" style="height: 350px;">{{{variable:system_url}}</div>
</div>
Code that does the replacement:
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
foreach ($xpath->query(".//*[not(self::textarea or self::select or self::input or self::div[contains(#class,'note-editable')]) and contains(., '{{{')]/text()") as $node) {
$node->nodeValue = preg_replace_callback('~{{{([^:]+):([^}]+)}}}~', function($m) use ($placeholders) {
return $placeholders[$m[1]][$m[2]] ?? '';
},
$node->nodeValue);
}
$html = $dom->saveHTML();
echo html_entity_decode($html);
Use this below xpath.
.//*[not(self::textarea or self::select or self::input or self::div[contains(#class,'note-editable')]) and contains(., '{{{')]

PHP: If value is empty, to not sumbit target filepath to database

I have a very slight problem where I am not able to figure out how to get my target filepath not submit to the mysql database when the field value is empty. Right now, if I leave the image field empty, it still submits the filepath ($folder) to the database. I would like for when the field is left empty, to not send the filepath to mysql.
Form.php
<form enctype="multipart/form-data" action="add.php" method="POST">
HAZARD: <input name="haz1" value="hazard1" type="text" /><br>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
IMAGE: <input type="file" name="photo"><br>
<input type="submit" name="action" value="Load">
</form>
Add.php
<?php
$folder = "images/";
$target1 = $folder . basename( $_FILES['photo']['name']);
$photo = $target1;
require("../db.php");
$haz1 = $_POST['haz1'];
mysql_query("INSERT INTO testimg VALUES (null,'$haz1','$photo')") ;
move_uploaded_file($_FILES['photo']['tmp_name'], $target1);
?>
I've tried
if (isset($_POST['photo']) ? $_POST['photo'] : null) echo $target1 == null);
I've tried other ways of isset as well but doesn't seem to work. Is there any other way i can accomplish this? Appreciate any help please. Thank you!
(Just a note, I have removed excess code above just to keep it short. I am taking care of SQL injection)
I would strongly suggest JavaScript, then users do not need to reload the page if it is empty. The JavaScript will check if it is empty for you. If it is you can make it so they cannot submit at all.
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
This is an example above, if you would like better walk through go here
JQuery has libraries that you can use to do fancy things if it is left blank, just search for JQuery form validation for more tools.
Hope this helps!
Try using the inbuild HTTP_POST_FILE in PHP:
if (isset($_FILES['photo']) ? $_FILES['photo'] : null)
You could wrap the mysql code inside of an if function too:
if (isset($_FILES['photo']) {
//Do mySQL processing in here
}
A couple of points:
Require is at the top of a PHP script. It's nicer to see all requires
first.
I have used an inline if statement to determine what to set $photo
(elimintating need for $target1)
I have also moved the apostrophes into the assignment of $photo as
returning 'null' comapred to null (without the quotation marks) is
very different in SQL.
If $photo is not null at the end of the script then it moves the
updated file.
Please see the corrected code below:
<?php
require("../db.php");
$folder = "images/";
$photo = (isset($_FILES['photo']) ? "'" . $folder . basename( $_FILES['photo']['name']) . "'" : null);
$haz1 = $_POST['haz1'];
mysql_query("INSERT INTO testimg VALUES (null,'$haz1',$photo)") ;
if ($photo != null) { move_uploaded_file($_FILES['photo']['tmp_name'], $photo); }
?>

create folder using a form with a given name

Im trying to make a html form that can create a folder on the server with a given name in the html form. So fare I have this code:
<?
if (isset($_POST['createDir'])) {
//get value of inputfield
$dir = $_POST['dirname'. var_dump($_POST)];
//set the target path ??
$targetfilename = PATH . '/' . $dir;
if (!file_exists($dir)) {
mkdir($dir, 0777, true); //create the directory
}
}
print_r($_POST); exit;
?>
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>" name="myform" id="myform">
<input name="dirname" id="dirname" >
<input type="submit" name="dirname" value="dirname" title="Continue to the next step">
</form>
The debug say: Array ( )
the script is nothing i have wrote but trying to put thing together to get it working but have not fix this for days now. Please advice.
Don't use PHP short opening tags (<?). Use the long form (<?php). You risk getting tangled up in the wrong language processor.
You're looking for $_POST['createDir'] coming back from the form, but I don't see a form element with name="createDir".
What is $_POST['dirname'. var_dump($_POST)] supposed to do?
What is PATH?
Play it safe by giving a type= for dirname input element.

xpath query to parse html tags

I need to parse the following sample html using xpath query..
<td id="msgcontents">
<div class="user-data">Just seeing if I can post a link... please ignore post
http://finance.yahoo.com
</div>
</td>
<td id="msgcontents">
<div class="user-data">some text2...
http://abc.com
</div>
</td>
<td id="msgcontents">
<div class="user-data">some text3...
</div>
</td>
The above html may repeat n no of times in a page.
Also sometimes the ..... portion may be absent as shown in the above html blocks.
What I need is the xpath syntax so that I can get the parsed strings as
array1[0]= "Just seeing if I can post a link... please ignore post ttp://finance.yahoo.com"
array[1]="some text2 htp://abc.com"
array[2]="sometext3"
Maybe something like the following:
$remote = file_get_contents('http://www.sitename.com');
$dom = new DOMDocument();
//Error suppression unfortunately, as an invalid xhtml document throws up warnings.
$file = #$dom->loadHTML($remote);
$xpath = new DOMXpath($dom);
//Get all data with the user-data class.
$userdata = $xpath->query('//*[contains(#class, \'user-data\')]');
//get links
$links = $xpath->query('//a/#href');
So to access one of these variables, you need to use nodeValue:
$ret = array();
foreach($userdata as $data) {
$ret[] = $data->nodeValue;
}
Edit: I thought I'd mention that this will get all the links on a given page, I assume this is what you wanted?
Use:
concat(/td/div/text[1], ' ', /td/div/a)
You can use instead of the ' ' above, whatever delimiter you'd like to appear between the two strings.