I need some help with some php scripting. I wrote a script that parses an xml and reports the error lines in a txt file.
Code is something like this.
<?php
function print_array($aArray)
{
echo '<pre>';
print_r($aArray);
echo '</pre>';
}
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'utf-8');
$xml = file_get_contents('file.xml');
$doc->loadXML($xml);
$errors = libxml_get_errors();
print_array($errors);
$lines = file('file.xml');
$output = fopen('errors.txt', 'w');
$distinctErrors = array();
foreach ($errors as $error)
{
if (!array_key_exists($error->line, $distinctErrors))
{
$distinctErrors[$error->line] = $error->message;
fwrite($output, "Error on line #{$error->line} {$lines[$error->line-1]}\n");
}
}
fclose($output);
?>
The print array is only to see the errors, its only optional.
Now my employer found a piece of code on the net
<?php
// test if the form has been submitted
if(isset($_POST['SubmitCheck'])) {
// The form has been submited
// Check the values!
$directory = $_POST['Path'];
if ( ! is_dir($directory)) {
exit('Invalid diretory path');
}
else
{
echo "The dir is: $directory". '<br />';
chdir($directory);
foreach (glob("*.xml") as $filename) {
echo $filename."<br />";
}
}
}
else {
// The form has not been posted
// Show the form
?>
<form id="Form1" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Path: <input type="text" name="Path"><br>
<input type="hidden" name="SubmitCheck" value="sent">
<input type="Submit" name="Form1_Submit" value="Path">
</form>
<?php
}
?>
That basically finds all xmls in a given directory and told me to combine the 2 scripts.
That i give the input directory, and the script should run on all xmls in that directory and give reports in txt files.
And i don't know how to do that, i'm a beginner in PHP took me about 2-3 days to write the simplest script. Can someone help me with this problem?
Thanks
Make a function aout of your code and replace all 'file.xml' to a parameter e.g. $filename.
In the second script where the "echo $filename" is located, call your function.
Related
im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>
I have a program that is failing because it's not finding the $post in the search of the array, so it's continuing to add each time. I have used the other suggested method of using a foreach loop, with strpos, such as:
if (strpos($data, $posts) !== false), and this will work find the $post, but it will also find the rest and run against everything in the data/array. hence why I would just like it to search the array, if it's not there add it, if it is, just say it's there or checking in... I've spent 3 days using in_array, array_search, etc, now I'm asking for help...
<html>
<body>
<?php
$post = $_POST['name'];
$data = file("data.txt");
if (in_array($post, $data)) {
echo "$post is checking in...";
}
else {
echo "Adding to $data...";
$data = fopen("data.txt", "a+");
fwrite($data, $post.PHP_EOL);
fclose($data);
}
$data = file("data.txt");
foreach ($data as $d) {
echo $d;
}
?>
</body>
</html>
tclient.html
<html>
<body>
<form action="test4.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
data.txt
Names
John
Doe
The value in $post probably doesn't have a new line at the end. You can specify not to include new lines when you use file().
file("data.txt", FILE_IGNORE_NEW_LINES);
My posts from the voicexml below arrives my php script as a
$ _POST['SOURCEADDR'] & $ _POST['recMsg']
Is there something I have to do at my server's configuration to enable $_FILES[]?
I have this same script working properly when I post from a html web page.
<form id="record">
<record name="recMsg" beep="true" maxtime="120s" finalsilence="5000ms" dtmfterm="true" type="audio/basic">
<prompt>
<audio src="sounds/RECORD_AFTER_BEEP.au"/><audio src="sounds/COMEDY_WARRANT.au"/>
</prompt>
<noinput>
<audio src="sounds/NOTHING_RECORDED.au"/>
</noinput>
<filled>
<submit next="saveRecording.php" namelist="SOURCEADDR recMsg" method="post" enctype="multipart/form-data"/>
</filled>
</record>
</form>
====== PHP Script =====
<?
if ($_FILES){
$ftype = $_FILES["recMsg"]["type"];
$fsize = $_FILES["recMsg"]["size"];
$ftemp = $_FILES["recMsg"]["tmp_name"];
$phone = $_REQUEST["SOURCEADDR"];
$fname = "rec_".$phone."_".date("Ymdgis").".au"; //$_FILES['recMsg']['name'];
flog("debug.log", "Got: $ftype | $fsize | $phone | $fname");
}else{
$out = flog("debug.log", "no $ _FILES array");
echo '<?xml version="1.0" encoding="ISO-8859-1"?><vxml version="2.0"><form id="main">
<block>'.'ERROR POST'.'</block></form></vxml>';
exit;
}
?>
You specify in the VoiceXML what type of HTTP request will be used to send the recorded audio to the server.
<submit expr=example.php method="post" namelist="rec" enctype="multipart/form-data"/>
This is the typical method for sending audio files to the server. You do not specify on the server how the audio is sent.
There is an example on how to retrieve the audio in PHP when using this type of submit in this Voxeo article. Look at the bottom of the page for the PHP example. Here is the example code.
<?PHP
header('Cache-Control: no-cache');
error_reporting (0);
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
echo "<vxml version=\"2.0\">";
echo "<form id=\"main\">";
echo "<block>";
if ($HTTP_POST_FILES) {
foreach ($HTTP_POST_FILES as $key => $value) {
foreach ($value as $Filename) {
if (strpos($Filename, "WINNT")) { $ServerSide = $Filename; }
if (strpos($Filename, ".wav")) { $ClientSide = $Filename; }
} // for each statement
$ServerSide = str_replace("\\\\", "/", $ServerSide);
if (!copy($ServerSide, "c:/audio-storage/temp.wav")) {
echo "Could not save filename: " . $ServerSide;
} // if statement
else {
echo "Successfully saved filename: " . $ServerSide;
} // else statement
} // for each statement
} // if statement
echo "</block>";
echo "</form>";
echo "</vxml>";
?>
According to this example from Voxeo it should return a type of HTTP_POST_FILES, not _FILES[]. HTTP_POST_FILES is an associative array of items uploaded to the current script via the HTTP POST method.
I have a folder where I keep my images, named img/. I have a table with all of my images:
<table border="3">
<tr>
<td>
<?php
$files = glob("img/*");
foreach ($files as $file) {
echo "<div class='divimages'>";
echo '<img src="'.$file.'"/>';
echo "<input type='submit' value='Delete image'/><br>";
echo "</div>";
}
?>
</td>
</tr>
</table>
How can I delete the image associated to the button with the value:"Delete image".
There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink
DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.
Each image's display markup would contain a form something like this:
echo '<form method="post">';
echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
echo '</form>';
...and at at the top of that same PHP file:
if (array_key_exists('delete_file', $_POST)) {
$filename = $_POST['delete_file'];
if (file_exists($filename)) {
unlink($filename);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
// existing code continues below...
You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.
Documentation and Related Reading
unlink - http://php.net/manual/en/function.unlink.php
$_POST - http://php.net/manual/en/reserved.variables.post.php
file_exists - http://php.net/manual/en/function.file-exists.php
array_key_exists - http://php.net/manual/en/function.array-key-exists.php
"Using PHP With HTML Forms" - http://www.tizag.com/phpT/forms.php
You can delete files in PHP using the unlink() function.
unlink('path/to/file.jpg');
First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
For deleting use http://www.php.net/manual/en/function.unlink.php
Hope you'll can to write logic?
You can try this code. This is Simple PHP Image Deleting code from the server.
<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>
<?php
if (isset($_POST['submit']))
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
{
echo ("Error deleting $photoname");
}
else
{
echo ("Deleted $photoname");
}
}
?>
<?php
require 'database.php';
$id = $_GET['id'];
$image = "SELECT * FROM slider WHERE id = '$id'";
$query = mysqli_query($connect, $image);
$after = mysqli_fetch_assoc($query);
if ($after['image'] != 'default.png') {
unlink('../slider/'.$after['image']);
}
$delete = "DELETE FROM slider WHERE id = $id";
$query = mysqli_query($connect, $delete);
if ($query) {
header('location: slider.php');
}
?>
<?php
$path = 'img/imageName.jpg';
if (is_file($path)) {
unlink($path);
} else {
die('your image not found');
}
I have a form which takes two values. One takes a .txt file, the file at which some links are hard coded and a text field which takes a url. When I press submit it takes that url and checks on every link that is on *.txt file. Hope you understand what I am saying if not then please comment I will clarify it. Now I have problems. My code does not work until the file at which links are, is not at my server. I don't how to handle this problem. I have done my search, I also try mysql but that is not ok for me. My script is this:
Enter your file :<input type="file" name="ufile" />
Enter your site name :<input type="text" name="utext" />
<input type="submit" value="Check" />
Now, my php script is this:
$needle = $_POST['utext'];
$file = $_FILES['ufile'];
$new = file($file, FILE_IGNORE_EMPTY_LINES | FILE_SKIP_EMPTY_LINES);
$new = array_map('trim', $new);
echo 'Total entries are: '.count($new).'<br />';
$found = array();
$notfound = array();
foreach ($new as $check) {
echo "<table border='1'><tr>";
echo "<td>Processing</td> <td>", $check,"</td></tr>";
$a = file_get_contents($check);
if (strpos($a, $needle)) {
echo "<td><font color='green'>Found:</font></td>";
$found[] = $check;
} else {
echo "<td><font color='red'>Not Found</font></td>";
$notfound[] = $check;
}
echo "</tr></table>";
}
echo "Matches ".count($found)."<br />";
echo "Not Matched ".count($notfound);
Is there any reason you never read the documentation about how PHP handles uploads in first place? That would make clear that $_FILES['ufile'] is array, so your code cannot work. If you really want to continue writing code without understanding it first, then replace:
$file = $_FILES['ufile'];
with
$file = $_FILES['ufile']['tmp_name'];