Updating a File Script Issue - php

I'm using this code to update a given file;
<?php
if($_POST['submit']){
$open = fopen("textfile.php","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
echo "File updated.<br />";
echo "File:<br />";
$file = file("textfile.php");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("textfile.php");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
But somehow its showing this error:
Although the file does updated with this code when I submit my text and no error or submission, however the error its showing on the screenshot bugs me, so any way I could remove those errors?
Thanks!

Change line 2 to this:
if(isset($_POST['submit'])){
Change line 15 to this:
echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">";

Assuming that your submit button is named submit checking for $_POST['submit'] is unreliable (as not all browsers POST the submit button), you should check for another field name that is posted OR better yet, change to if($_SERVER['REQUEST_METHOD'] == 'POST'){.
Also, $PHP_SELF is assuming you have register globals on (which shouldn't be), you should use $_SERVER['PHP_SELF'] instead.

Joe has it. You want isset(). # (error suppression) is the coward's way out. Be a man and use isset() ;-)

Related

How to use strpos() to check a variable's path?

I have a home page that shows some uploaded images.
I take it from the database and I use strpos() to check the URL due to directory problems, and it works fine:
if(strpos($row['cImage'],"http://") === FALSE){
echo "<img src='serintercement/".$row['cImage']."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$row['cImage']."' style='width: 107px; height:102px;' />";
}
I need to use the same logic in a page that shows the clicked image, but it has a variable for it and I'm struggling to fix this since it's a different way to write:
<img src='<?php echo $resultData->cImage; ?>'/>
I can't fix the directory problem. How can I use strpos() similarly for this second code?
You can do it like this.
if(strpos($resultData->cImage,"http://") === FALSE){
echo "<img src='serintercement/".$resultData->cImage."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$resultData->cImage."' style='width: 107px; height:102px;' />";
}
Better option is you can define a function like this and call it
checkImage($row['cImage']);//to be called in your first page
checkImage($resultData->cImage);//to be called in your second page
function checkImage($image)
{
if(strpos($image,"http://") === FALSE){
echo "<img src='serintercement/".$image."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$image."' style='width: 107px; height:102px;' />";
}
}
You should be able to check the path similarly - as long as the property of the object is set and a string, strpos() can be used.
if(strpos($resultData->cImage,"http://") === FALSE){
echo "<img src='serintercement/".$resultData->cImage."' />";
}else{
echo "<img src='".$resultData->cImage."' />";
}
If these cImage strings are coming from your database, you could just correct them in the query call.
For example, if you are using MySQL, you could prepare the data using LOCATE() AND CONCAT() like this:
SELECT
IF(LOCATE('http',`cImage`)!=1,CONCAT('serintercement/',`cImage`),`cImage`) `new_cImage`
FROM ...
Moving the conditional process to your query, will make your "displaying" code read more smoothly because all of the preparations are completed ahead of time.
Outside of that, you can make your code more DRY by not repeating the html parts that come before and after the image variable...
This is an echo with an inline condition (not everyone likes this style):
echo "<img src=\"",(strpos($resultData->cImage,"http")===0?'':'serintercement/'),"{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
This is a separated conditional:
echo "<img src=\"";
if(strpos($resultData->cImage,"http")!==0){
echo 'serintercement/'
}
echo "{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
This is a function call if you have to do this multiple times in the same script:
function fixPath($img){
if(strpos($img,"http")===0){
return $img;
}
return "serintercement/$img";
}
echo "<img src=\"",fixPath($resultData->cImage),"\" style=\"width:107px;height:102px;\" />\n";
Notice that I am only checking for http and that I am very accurately checking that it comes from the first position in the string. Across all these alternatives, the point I am making is DRYness (which is a typical pursuit of all programmers). How you chose to implement it comes down to your personal preference.

HTML file input not working in PHP

I'm making a social media website for a project. I have a PHP function that allows the user to upload an image to a post and inside the function is an html form to allow them to select a form.
echo "<form method='post' enctype='multipart/form-data'>";
echo "<input type='file' name='myFile'/>";
echo "<label for='myFile' id='fileLabel'>File input</label>";
echo "<input type='submit' name='submitFileForm' value='Upload' />";
echo "</form>";
When I process the form with this code and print_r($_FILES) is empty but if I echo $_POST['myFile'] it displays the correct file name.
if (isset($_POST['submitFileForm'])) {
print_r($_FILES);
$my_folder = "img/";
if (move_uploaded_file($_FILES['myFile']['tmp_name'], $my_folder . $_FILES['myFile']['name'])) {
echo 'Received file' . $_FILES['myFile']['name'] . ' with size ' . $_FILES['myFile']['size'];
} else {
echo 'Upload failed!';
var_dump($_FILES['myFile']['error']);
}
}
Thank you for the help , I have been trying to debug this for the last 2 hours. Also I forgot to mention, I already tried increasing upload_max_filesize = 100M and input_max_size = 100M and that is not the problem.
You have to change the if condition as following
if (isset($_POST['submitFileForm'])) {
It will be working

Refresh php script on submit

i have a question on a short php script here. I have created a script to edit a txt file, the script works just fine, no problem with it. Im trying to make the script reload automaticaly on submit and im really stack here.
Here is the script:
<?
if($_POST['Submit']){
$open = fopen("../youtubelink.txt","w+");
$text = $_POST['update'];
fwrite($open, $text);
fclose($open);
$file = file("../youtubelink.txt");
foreach($file as $text) {
echo $text."<br />";
}
}else{
$file = file("../youtubelink.txt");
echo "<form action=\"".$PHP_SELF."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"Submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
?>
Any help please?
use Ajax and query every x Minutes a script that checks the text file for changes. If the Ajax returns "yes, updates available" reload the page with Javascript.

Display previous logged in timestamp from txt file

I was asked to do this by my college staffs so kindly help me out with this! I have a php file with a text box and login id is supposed to be entered in it and login button is to be pressed. Once this button is pressed, the login id and timestamp is stored in a txt file. Next time the same login id is used then the timestamp is to be overwritten. I have done this part successfully. Now, i wanna display the timestamp before overwritting it. This is something similar to last seen of whatsapp. How can i display it?
This is my code:
<html>
<head><title>Login Portal</title></head>
<body><center>
<h1>TPF EMPLOYEE LOGIN</h1><hr><br><br>
<?php
session_start();
if(isset($_POST['submit']))
{
$myfile = file_get_contents('data.txt');
$_SESSION['name']=$_POST['id'];
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d H:i:s');
$txt=$_SESSION['name'].",".$date.",\n";
$name = $_SESSION['name'];
if(preg_match("/$name/", $myfile))
{
$results = preg_replace("/$name.*\,/", $txt, $myfile);
file_put_contents('data.txt', $results);
}
else
{
file_put_contents('data.txt', $txt, FILE_APPEND);
}
}
else
{
echo "<form name='login' method='post'>";
echo "Enter your login id : <input type='text' name='id' id='id' /><br><br>";
echo "<input type='submit' name='submit' value='Login' />";
echo "</form>";
}
?>
</center>
</body>
</html>
This is the contents of my txt file:
a,2014-10-05 19:00:40,
b,2014-10-05 19:00:31,
Using the comma after the name as an identifier how do i display the previous timestamp before overwritting it?
Change:
if(preg_match("/$name/", $myfile))
{
to include $matches and alter the regexp, then work with $matches array:
if(preg_match("/$name\,(.*),/", $myfile, $matches))
{
echo 'Previous Login: ' . $matches[1];
Example: http://ideone.com/1diNNd
Hints: use a db, ensure $name is unique...

PHP File Delete Issue?

I have the following HTML form:
<form action='delete.php' method='POST'>
<table>
<div class = '.table'>
<?php
$dir = '../uploads/store/';
$newdir = ereg_replace('\.','',$dir);
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!preg_match('/^(\.(htaccess|\.)?|index\.html)/',$file)) {
echo "<tr><td><font color = 'white'><a href='$newdir$file'>$file</a></font></td>";
echo "<td><input type='submit' value ='Delete'></td></tr>";
echo "<input align='right' type='hidden' value='$file' name='file'>";
}
}
closedir($dh);
}
}
?>
</div>
</table>
</form>
Which links to the following PHP script:
<?php
session_start();
$file = $_POST['file'];
$dir = '../uploads/store/';
$file = $dir . $file;
opendir($dir);
if(unlink($file)) {
echo "File sucessfully deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
} else {
echo "Error: File could not be deleted";
$_SESSION['username'] = 'guitarman0831';
header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html');
}
?>
However, when the Delete button is pressed in the HTML form, the item above the one intended to delete is deleted.
Hope this makes sense.
NOTE: I'm not going for security with these scripts, I'm going to work on that later. It's only me using this service right now.
Your HTML form needs to have the various submit buttons pass the value for $file instead of using hidden fields.
The problem is that all of the hidden fields are POSTed to delete.php when you submit the form. Then, since you haven't used the PHP-friendly HTML array variable syntax, PHP uses only the last of these to set the value of $_POST['file']. If you do a var_dump of $_POST in delete.php, you will see what the POSTed input is.
The easiest thing to do, with your current markup, is just to have each submit button be named file and pass $file as its value. i.e. you could do:
<button name="file" value="example.txt" type="submit">Delete</button>
Alternately, you could use radio buttons or some other markup.

Categories