Set the argument to a function in order to process it - php

So, I neet to set the argument to a function in order to convert it to a .mp3 file. Using this line : $tts->setText($row['raspuns']); doesn't happen anything but if i write $tts->setText("Hello World!"); it works perfectly, which takes me to the conclusion that i have to find a correct code to make that tts get the text. Can anyone help me please?
<html>
<head>
<title>
Bot
</title>
<link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>
<form action="bot.php "method="post">
<lable>You:<input type="text" name="intrebare"></lable>
<input type="submit" name="introdu" value="Send">
</form>
</body>
</html>
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("robo") or die(mysql_error());
$intrebare=$_POST['intrebare'];
$query = "SELECT * FROM dialog where intrebare = '$intrebare'";
$result = mysql_query($query) or die(mysql_error());
$row = $result;
?>
<?php
require "tts.php";
$tts = new TextToSpeech();
**$tts->setText($row['raspuns']);**
*//$tts->setText("Hello World!");*
$tts->saveToFile("voice.mp3");
$file='voice.mp3';
?>
<div id="history">
<?php
while (true == ($row = mysql_fetch_array($result))) {
echo "<b>The robot says: </b><br />";
echo $row['raspuns'];
echo "<embed src =\"$file\" hidden=\"true\" autostart=\"true\"></embed>";
}
?>
</div>
Here's the tts.php file:
<?php
class TextToSpeech {
public $mp3data;
function __construct($text="") {
$text = trim($text);
if(!empty($text)) {
$text = urlencode($text);
$this->mp3data = file_get_contents("http://translate.google.com/translate_tts?tl=en&q={$text}");
}
}
function setText($text) {
$text = trim($text);
if(!empty($text)) {
$text = urlencode($text);
$this->mp3data = file_get_contents("http://translate.google.com/translate_tts?tl=en&q={$text}");
return $this->mp3data;
} else { return false; }
}
function saveToFile($filename) {
$filename = trim($filename);
if(!empty($filename)) {
return file_put_contents($filename,$this->mp3data);
} else { return false; }
}
}
?>

You need to fetch the row from your result
If you want your code to work where your tts class calls are, change
$row = $result;
To
$row = mysql_fetch_row($result);
Note you have a code block below that redefines the $row array.
Also note mysql_* functions are deprecated, use PDO or mysqli_ functions instead. Your current code is wide open to sql injects!

Related

Leaking information because of URL injection in php

This code leaks information from the login page when a route that does not exist is being tried to navigate at.
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Login</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="uname">
password: <input type="password" name="upass">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$loginusername = $_POST['uname'];
$loginpassword = $_POST['upass'];
if (empty($loginusername) || empty($loginpassword)) {
echo "Please enter username and password";
} else {
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('SONGS');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$query = "SELECT * FROM $table where user_name = :username and password = :loginPassword";
$statement = $db->prepare($query);
$statement->bindParam(":username",$loginusername, PDO::PARAM_STR);
$statement->bindParam(":loginPassword",$loginpassword, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
if(!$result) {
echo "<p>No result!</p>";
exit;
} else {
$userid = $result[0][0];
$username = $result[0][1];
}
}
}
?>
</body>
</html>
This is an indexing page which will index all articles that are in the website.
<html>
<head>
<title>Some title</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Return
<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
$file = file_get_contents($file);
echo "$file";
echo '<br />Index';
}
else {
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('ARTICLES');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt = $db->query($query);
echo "<ul>";
foreach($stmt as $row) {
$href = $row[2];
$title = $row[1];
echo "<li> <a href='/myPage?file=../dir/$href'>$title</a> </li> ";
}
echo "</ul>";
}
?>
</body>
</html>
When this href echo "<li> <a href='/myPage?file=../dir/$href'>$title</a> </li> "; is changed manually at browser at suppose this route /myPage/?file=../login.php it will cause to leak code from the login file, which can uncover to the attack some crucial information about my backend setup. Is there any way how to patch this problem.
Yes, it's easily avoided by sanitizing your input.
Structures such as this
if (isset($_GET['file'])) {
$file = $_GET['file'];
$file = file_get_contents($file);
are highly problematic.
But there isn't a one-size-fits-all solution without knowing what the legit files that you want to allow to be referenced are.
Roughly how many valid files are there ? are they all located in the same directory ? do they follow some sort of specific naming convention ? do they all have the same extension (or lack any at all) ?
Edit: I suspect you'll want something along these lines. I haven't tested it, so it's possible i made a typo somewhere, but it shouldn't suffer from the same vulnerabilities atleast.
<html>
<head>
<title>Some title</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
Return
<?PHP
$user = getEnv('USER');
$password = getEnv('PASSWORD');
$database = getEnv('DATABASE');
$table = getEnv('ARTICLES');
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
$filekey = 'ref';
$dbcolumn = 'href'; // <--- should match the name of the column in mysql
if (isset($_GET[$filekey]) && $request = $_GET[$filekey]) {
$stmt = $db->prepare("SELECT $dbcolumn FROM $table WHERE $dbcolumn = ?");
$stmt->execute([ $request ]);
if ( $records = $stmt->fetchAll(PDO::FETCH_ASSOC)
&& !empty($records)
&& $record = reset($records)
&& isset($record[$dbcolumn])
&& $request = $record[$dbcolumn]
) {
echo file_get_contents("../dir/$request");
echo '<br />Index';
} else {
die('Access denied');
}
} else {
$query = "SELECT * FROM $table";
$stmt = $db->prepare($query);
$stmt = $db->query($query);
echo "<ul>";
foreach($stmt as $row) {
$href = $row[2];
$title = $row[1];
printf('<li><a href='/myPage?%s=%s'>%s</a></li>',
$filekey,
htmlentities($href, ENT_QUOTES),
htmlentities($title, ENT_QUOTES)
);
}
echo "</ul>";
}
?>
</body>
</html>
Make sure you set $dbcolumn correctly (should match the mysql column name), and optionally change $filekey to whatever you want to see in the URL.
This fixes your security problem: it only allows filenames to be specified in the URL, that actually exist in your database table, so it cant be used to pull random files anymore. If someone tries to manually change thevalue in the URL to something not in the database they get the error above.
It also fixes potential problems with the title in the listing, which was being output raw (i added htmlentities). Depending on the type of content inside the files, you may want to wrap a htmlentities call around file_get_contents() aswell, but don't do that if there is actual html inside those files.
I did see some other oddities , such as that you create a prepared statement and then don't use it :) but that has no security implications in this case, i left it as is.

Using a small client to retrieve information using $_GET from database help. PHP and MySQL

I have made a database, it works and values have been entered, I have also made a service page using PHP which also works great thanks to a person on here! So I can query that and it works fine e.g.
http://localhost/NewWebApp/php/databaseRestService.php?episodename=Pilot
//Outputs: "7th October 2014"
Which is correct, however when I use a client (Input field), I get nothing returned. At all. I have gone through all of my code again, and done little if statements to see where the problem could lie, and I have shortlisted it down to my $data variable. The code is as follows for this Client.
<!doctype html>
<html lang="en">
<head>
<?php
if(isset($_GET["submit1"]))
{
$episodeNameForFlash = $_GET["episodename"];
$url = "http://localhost/NewWebApp/php/databaseRestService.php?episodename ='".$episodeNameForFlash."'";
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($client);
echo curl_error($client);
if(!$data)
{
echo "Error on data";
}
}
?>
</head>
<body>
<form action="databaseRestClient.php" method="GET">
<label>Enter Name of Episode</label> <input type="text" name="episodename"/>
<input type="submit" name="submit1"/><br/>
</form>
<?php
if(isset($data))
{
echo ("The date of the Episode is ". $data);
}
?>
</body>
</html>
Thus the output is: Error on data.
Does anyone know what I am doing wrong? Been trying to figure this out for a couple of hours now.
Kieran
UPDATE: databaseRestService.php code
<?php
class FlashEpisodes
{
var $serverName = "localhost";
var $userName = "root";
var $password = "";
var $databaseName = "test";
public function FlashEpDate($name)
{
$databaseConnection = mysqli_connect($this->serverName, $this->userName, $this->password);
if(!$databaseConnection)
{
// echo "Error";
}
if(!mysqli_select_db($databaseConnection, $this->databaseName))
{
//echo "Error";
}
else
{
//echo "Success";
}
$sql = "SELECT theFlashEpsDate FROM superhero WHERE theFlashEps ='".$name."'";
$result = mysqli_query($databaseConnection, $sql);
if(!$result)
{
echo "<br>Error on Query";
}
if ($result)
{
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$getTheFlashEpsDate = $row[0];
}
else
{
$getTheFlashEpsDate = null;
}
return $getTheFlashEpsDate;
}
}
$getEpisodeName = $_GET['episodename'];
$objSuperHero = new FlashEpisodes;
$response = $objSuperHero->FlashEpDate($getEpisodeName);
echo $response;
?>
^ The code here works as it should, I can just put in the query in the string and this page works, just when I want to use a client (input field) it does not :(
when defining $url variable in databaseRestClient.php file, why do you have single quotes for the $episodeNameForFlash parameter?
I think these single quotes are the cause of the problem, remove them and check your code again.
that line should look like this:
$url = "http://localhost/NewWebApp/php/databaseRestService.php?episodename =".$episodeNameForFlash;
it's better for you to use urlencode to encode the $episodeNameForFlash variable before using it in the $url in case of any special characters in the $episodeNameForFlash variable and then use urldecode in the databaseRestService.php file when retrieving the $_GET['episodename']
Here's my working version...
<head>
<?php
if(isset($_GET["submit1"]))
{
$episodeNameForFlash = $_GET["episodename"];
$url = "http://localhost/testserver.php?episodename ='".$episodeNameForFlash."'";
$data = file_get_contents($url);
if(!$data)
{
echo "Error on data";
}
}
?>
</head>
<body>
<form action="testclient.php" method="GET">
<label>Enter Name of Episode</label> <input type="text" name="episodename"/>
<input type="submit" name="submit1"/><br/>
</form>
<?php
if(isset($data))
{
echo ("The date of the Episode is ". $data);
}
?>
</body>
</html>

I can't get the output to show from an array PHP SQL

NOTICE: I know the scroll bar for my code looks insane, if you just scroll to the bottom, you will see where I am trying to output the code.
I am trying to output the results of a select query search.
I have successfully retrieved the results which satisfy the WHERE conditions in a stand alone php file eg. not imbedded with front end code.
In my website design, I have the main <?php ?> section on top of the <!DOCTYPE HTML> section.
Then I echo certain parts from the main <?php ?> section at the top, within the front end code.
I am missing something here because I can't get this to work. I've tried various attempts.
This is the output in a stand alone php file
01-05-2015 sample 3
01-05-2015 sample 2
01-05-2015 sample
I want this in the search result box using isset if it doesn't exist yet.
Here is a photo of the interface if it helps, it is literally a text input field and a "search" post button with a result display below.
http://www.parsemebro.com/search.jpg
ob_start();
session_start();
mysqli_report(MYSQLI_REPORT_OFF);
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
error_reporting(-1);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($_SERVER['REQUEST_METHOD']=='POST'){
$errors = array();
if (empty($_POST['keyphrase'])) {
$errors['keyphrase'] = "Search field is empty";
} else {
$keyphrase = test_input($_POST['keyphrase']);
}
if(empty($errors)){
$userrname = $_SESSION["user"];
$keyphrase = test_input($_POST['keyphrase']);
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$stmt=$link->prepare('SELECT stratoparse,date FROM stock WHERE user=? AND keyphrase=? ORDER BY ID DESC');
$stmt->bind_param('ss',$userrname,$keyphrase);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
global $num_rows;
$stratoparse=null;
$date=null;
$stmt->bind_result($stratoparse,$date);
$rows2 = array();
$rows3 = array();
while($stmt->fetch()){
$rows2[] = $stratoparse;
$rows3[] = $date;
}
$search = array();
for($i=0;$i<=$num_rows;$i++){
$search[]=$rows3[$i].' '.$rows2[$i].'<br>'.'<br>';
}
$_SESSION['status_message'] = "search results displayed below";
$host = $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI']; // the path/file?query string of the page
header("Location: http://$host$uri");
exit;
$link->close();
}
}
?>
<!DOCTYPE HTML>
<head>
<style>
</style>
</head>
<body>
<?php
if(isset($_SESSION['status_message'])){
echo '<font color="white" size="30%">'.htmlspecialchars($_SESSION['status_message']).'</font>'.' ';
unset($_SESSION['status_message']); // clear the message
}
?>
<span><span class="errors"><?php echo isset($errors['keyphrase'])? $errors['keyphrase']:""; ?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="keyphrase" value="<?php echo isset($keyphrase)? $keyphrase:"";?>" placeholder="keyphrase"><input type="submit" value="search"></span>
</form>
<textarea name="result" placeholder="search results">
**THIS IS WHERE I WANT TO OUTPUT THE ARRAY RESULTS**
<?php echo isset($search)?$search:"";?>
<?php
for($i=0;$i<=(isset ($num_rows)?$num_rows:"");$i++){
echo isset($search[$i])?$search[$i]:"".'<br>'.'<br>';
}
for($i=0;$i<=(isset ($num_rows)?$num_rows:"");$i++){
echo (isset($rows3[$i])?$rows3[$i]:"").' '.(isset($rows2[$i])?$rows2[$i]:"").'<br>'.'<br>';
}
?>
</textarea>
</body>
to output type Array, such as your $search[] you need to use var_dump($search). Then you should see some output. but it'll be ugly unless you iterate over it and concatenate a string.
To iterate over the array and concatenate into string using ".="
$output = "";
for( $i = 0; $i < count($search); $i++){
$output .= "Search result: " . $i . "\n";
$output .= $search[$i] . "\n";
};
and then dont echo, just use <?=$string?> inside your HTML element.
<textarea name="result" placeholder="search results">
<?=$output?>
</textarea>
Test if $search is set before beginning to loop over it to get the values out.
side-note:
In your HTML you can use <?=$variableName?> as syntax rather than <?php ... ?>.

php problems in search function

Im trying to add search function.
i want it to work like that: for exmple if i have 5 field, and user wrote only in 2, the search will be based only on 2 field. I mean it not neccesary to write information in all 5 field, i want search will happen only in filled fields.
And now it works only if i will write something in all fields (for now i have 2). And if i will write only in one field it doesnt show anything.
Code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<h1>Поиск</h1>
<form action="search_form.php" method="post">
<p>Направление</p>
<input type="text" name="course" />
<p>Форма обучения</p>
<input type="text" name="form" />
<input type="submit" value="Искать">
</form>
<?php
$db = mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("university", $db) or die(mysql_error());
$w = array('TRUE');
if (isset($_POST['course']))
{
$course = $_POST['course'];
$w[] = "course='$course'";
}
if (isset($_POST['form']))
{
$form = $_POST['form'];
$w[]= "form='$form'";
}
$where = implode($w, ' AND ');
$query = ('SELECT * FROM news WHERE '.$where);
$result = mysql_query($query,$db);
if($result !== false)
{
$news = mysql_fetch_array($result);
while($news = mysql_fetch_assoc($result)) {?>
<tr>
<td><?=$news['id']?></td>
<td><?=$news['program']?></td>
</tr><?
}
}
else
{
echo 'Sorry, we didn't find anything.';
}?>
</div>
</body>
</html>
You are vulnerable to SQL injection attacks. Learn about and fix that before you do ANYTHING else with this code.
Plus your logic is faulty: mysql_query() returns false on errors. A query which has no results is NOT an error, and still returns a valid query handle. It'll simply have 0 rows on it.
$result = mysql_query($query);
if ($result === false) {
die(mysql_error());
} else if (mysql_num_rows($result) == 0) {
die("No results");
} else {
... display results
}

Calling functions which are defined in other php file wont work the way I want

I have followin PHP code, it is where I defined my functions:
<?php
function emaili_pikkus($email){
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
$emaili_pikkus=True;
}
}
function parooli_pikkus($parool)
{
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
$parooli_pikkus=True;
}
}
function varasem_olemasolu($email)
{
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad WHERE e_mail = '$email'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
$varasem_olemasolu=True;
}
else
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
}
}
function paroolide_kattuvus($parool, $parool_uuesti)
{
if($parool==$parool_uuesti)
{
$paroolide_kattuvus=True;
}
else{
echo "Paroolid ei kattu.";
}
}
function NewUser()
{
global $sql;
if (mysql_query( $sql))
{
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Praks/templates/registreeritud.php'>";
}
}
?>
Then I have other PHP code where I call necessary functions(They are seperated, because I want to use my functions in other applications too):
<meta charset="UTF-8">
<?php
include_once 'init/init.funcs.php';
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(10000,99999);
$hashed_pwd = sha1($parool.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi','$perekonnanimi','$hashed_pwd','$salt')";
emaili_pikkus($email);
if ($emaili_pikkus=True){
parooli_pikkus($parool);
}
if ($parooli_pikkus=True){
varasem_olemasolu($email);
}
if ($varasem_olemasolu=True){
paroolide_kattuvus($parool, $parool_uuesti);
}
if ($paroolide_kattuvus=True){
NewUser();
}
?>
And then I have my HTML code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>Registreerimine</title>
</head>
<body>
<strong>Registreerimiseks täida järgnevad väljad: </strong><br>
<br>
<form method="POST" action="registreerimine4.php">
<table>
<tr><td>Sinu Tieto e-maili aadress: </td><td><input type="text" name="email"></td></tr>
<tr><td>Eesnimi: </td><td><input type="text" name="eesnimi"></td></tr>
<tr><td>Perekonnanimi: </td><td><input type="text" name="perekonnanimi"></td></tr>
<tr><td>Parool: </td><td><input type="text" name="parool"></td></tr>
<tr><td>Parool uuesti: </td><td><input type="text" name="parooluuesti"></td></tr>
</table>
<br>
<input type="submit" value="Registreeri" name="Registreeri">
</form>
</body>
</html>
init.funcs.php looks like that:
<?php
session_start ();
$db = mysql_connect ( 'localhost', 'root', 'aaaa' );
if (! $db) {
header ( "location: /" );
die ();
} else {
mysql_select_db ( 'ta2014' );
}
include_once 'functions/user.funcs.php';
include_once 'functions/survey.funcs.php';
?>
It all together should be a registration form and it worked before I made few changes. Before those changes I had my functions defined to work only for this registration form and they had no parameters needed. Also they were nested in each other. My question is how should I write my second PHP code, so it all would work. Right now it creates new user even if some previous condition are not True. It is a long question and I would be very thankful if someone answers me.
You have a lot of errors in your code:
Your functions aren't returning any value. Variables intitalized inside the function will not be available outside it. The best way is to return a boolean value and check that outside
The function definition:
function some_func($param1, $param2) {
if (some_condition) {
// If everything okay, return TRUE
return TRUE;
} else {
// It's not gonna work with this, so return FALSE
return FALSE;
}
}
Checking the return value:
if (some_func($foo, $bar)) {
// some_func returned TRUE, do further processing
}
With if($var = True), you're not actually checking if a variable is true or not. You're assigning it the boolean value True. You need to write if($var == True instead.
You're using the deprecated mysql_* functions. They're deprecated. Use MySQLi or PDO instead.

Categories