PHP - Prevent Unwanted Uses Of Script
Hello all,
A simple question: I have a HTML application from which a php script is executed. 'GET' method is used and no form is submitted. I was wondering if there is a way to prevent users from run this php script directly in the browser. Thank you all for your suggestions, Mamer Similar TutorialsWhen I try to run the code below with Code: [Select] if ( $user->uid ) it works just dandy. But if I use Code: [Select] if ( !$user->uid ) it puts the number one a little bit below my truncated paragraph. It only started doing this after I put the Code: [Select] $login = print("Log in to see full article!");. It worked normally (besides the fact that it didn't say log in to see full article) And for description, I have 400 words of Lorem Ipsum, but you guys dont need to see that so I put elipses. Code: [Select] <head> <?php // this signifies how to truncate function myTruncate($string, $limit, $break=".", $pad="...") { // return with no change if string is shorter than $limit if(strlen($string) <= $limit) return $string; // is $break present between $limit and the end of the string? if(false !== ($breakpoint = strpos($string, $break, $limit))) { if($breakpoint < strlen($string) - 1) { $string = substr($string, 0, $breakpoint) . $pad; } } return $string; } ?> <title>truncate test</title> </head> <body> <?php $description = 'Lorem. ipsum dolor sit amet...'; // This makes it so it only applies to non logged in users if ( !$user->uid ) { //Replace 'XXX' with your number (Probably 500) $description = myTruncate($description, xxx); $login = print("Log in to see full article!"); } echo "<p>$description</p>"; echo "<p>$login</p>"; ?> Hi all, I am trying to make a emailscript with PEAR to send quite some people a personalized messaged. But i thought this could very well cause the script to time out. Now i read http://php.net/manual/en/function.set-time-limit.php, but i thought does maybe someone knows a way to prevent a time out instead of setting the time-limit to a larger amount. Some terms i saw floating around we ob_start, flush, sleep and a few others but i really never worked with these. If someone could point me in the right direction of thinking or maybe knows a tutorial or guide i really would love to hear it. Thank you! Hi guys, For a project I made sort of a custom cron database. Database has 4 columns: ID (auto increment), TaskID, DateTime, Locked. I'm running a 1 minute cron in the form of a php script. The script itself starts with a query that loads a task with 'Locked != 'Y' and DateTime < NOW( ). It then locks the task (by flagging the 'Locked' field in the db) and launches another script that finishes it. That last script deletes the task when finished from the cron database. Problem is, at certain peek hours, the system would get laggy, there'd be a bunch of tasks stacking up and it would get behind on the schedule. In order to combat that, I made an extra 1 minute cron, launching the same script. Now, my problem: mysql is too slow In principle, there shouldn't be any problem: all tasks picked up by either instance of the script would be locked so the other instance wouldn't be able to pick up the same task. The problem occurs when both instances are booted at the same time (well, one after the other but with a minuscule time difference between them) and they both at the same time run the query to get a 'free' task from the database: the system will give them both the same task before either of the script instances has the time to lock it up. I'm trying to think of some solutions but I'd like your feedback on what solution would be best. - Putting an exclusive lock on the php file is not an option for me since I still want to run the script, I just need it to pick up an exclusive task. - Other option: having the script open with a random sleep of (1, 10) seconds, it will have the script instances pick up a task at a different time, giving the other instance time to lock it up. Obvious disadvantage: I'm losing time. - Using a file as a flag. Set a directory and create a file in it. Check if this is the only file in the dir, if yes: start right away. Otherwise: go to sleep for 2 seconds (should be plenty of time to run 2 queries in the other instance). What is the fastest method of doing a directory scan though, glob()? My question: what's the fastest/best way to solve this? Thanks! Here is the code that i am using to accept data and display the data. To accept and add it in database i am using : $comment = $_POST['txtcomment']; $comment = @mysql_real_escape_string($comment); To display the data from DB i am using : $comment = $rowscomment['comment']; <?php echo nl2br($comment); ?> Please help me correct it....... I am still learning PHP. My host has a limit of 100 emails per hour and this is now being reached to many times a day and some emails are not being sent due to this. Does anyone have a script or know of one that can stack emails to be sent in MySql or something and every 5 minutes send one out from the stack and then delete from the stack the ones sent. Hi, I have the following script: <?PHP $match = '/.*?\\d+.*?(\\d+)(\\s+)/is' ; $dbh = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxx') ; $result = $dbh->query("SELECT companyName, invoiceAddress FROM detail_sheets WHERE area = 'Germany'") ; $codes = array() ; $names = array() ; $c0s = array() ; $c1s = array() ; $c2s = array() ; $c3s = array() ; $c4s = array() ; $c5s = array() ; $c6s = array() ; $c7s = array() ; $c8s = array() ; $c9s = array() ; while($row = $result->fetch(PDO::FETCH_ASSOC)) { if(preg_match($match, $row['invoiceAddress'], $matches)) { $codes[] = substr($matches[1], 0, 1) ; $names[] = $row['companyName'] ; //array_push($found, substr($matches[1], 0, 1), $row['companyName']) ; } } $i = 0 ; foreach($codes as $current) { $currentName = $names[$i] ; $result = $dbh->prepare("SELECT (sum(partbaskets.total) - sum(pourbaskets.total)) AS Margin FROM partbaskets, pourbaskets, enquiries, jobs WHERE partbaskets.enquiryRef = enquiries.id AND pourbaskets.enquiryRef = enquiries.id AND jobs.enquiryRef = enquiries.id AND jobs.status != 'Cancelled' AND enquiries.enqState != 'Inert' AND enquiries.companyName = ? ") ; $result->bindParam(1, $currentName, PDO::PARAM_STR) ; $result->execute() ; while($row = $result->fetch(PDO::FETCH_ASSOC)) { if($current == 0 && $row['Margin']) array_push($c0s, $row['Margin']) ; if($current == 1 && $row['Margin']) array_push($c1s, $row['Margin']) ; if($current == 2 && $row['Margin']) array_push($c2s, $row['Margin']) ; if($current == 3 && $row['Margin']) array_push($c3s, $row['Margin']) ; if($current == 4 && $row['Margin']) array_push($c4s, $row['Margin']) ; if($current == 5 && $row['Margin']) array_push($c5s, $row['Margin']) ; if($current == 6 && $row['Margin']) array_push($c6s, $row['Margin']) ; if($current == 7 && $row['Margin']) array_push($c7s, $row['Margin']) ; if($current == 8 && $row['Margin']) array_push($c8s, $row['Margin']) ; if($current == 9 && $row['Margin']) array_push($c9s, $row['Margin']) ; } $result = NULL ; $i++ ; } echo "<table><tr><td>Area</td><td>Margin</td></tr>" ; echo "<tr><td>Area 0</td><td>" . array_sum($c0s) . "</td></tr>" ; echo "<tr><td>Area 1</td><td>" . array_sum($c1s) . "</td></tr>" ; echo "<tr><td>Area 2</td><td>" . array_sum($c2s) . "</td></tr>" ; echo "<tr><td>Area 3</td><td>" . array_sum($c3s) . "</td></tr>" ; echo "<tr><td>Area 4</td><td>" . array_sum($c4s) . "</td></tr>" ; echo "<tr><td>Area 5</td><td>" . array_sum($c5s) . "</td></tr>" ; echo "<tr><td>Area 6</td><td>" . array_sum($c6s) . "</td></tr>" ; echo "<tr><td>Area 7</td><td>" . array_sum($c7s) . "</td></tr>" ; echo "<tr><td>Area 8</td><td>" . array_sum($c8s) . "</td></tr>" ; echo "<tr><td>Area 9</td><td>" . array_sum($c9s) . "</td></tr></table>" ; ?> But what is happening is that the Margin is being multiplied by the number of rows in partbaskets (which is the same amount of rows in pourbaskets). So for instance, if there is one part per job for a companyName, there is no problem and I get the correct margin. But, if there is say 4 parts for one of the jobs, then the margin for that job will be multiplied by 4, which is wrong. I have tried using GROUP but it didn't help. Can someone please give me the missing link in my SQL statement? I am parsing an rss feed from my flickr photostream using this:-
<?php $url = "http://api.flickr.com/services/feeds/photos_public.gne?id=49466419@N05&lang=en-us&format=rss_200"; $rss = simplexml_load_file($url); if($rss) { echo '<h1>'.$rss->channel->title.'</h1>'; echo '<li>'.$rss->channel->pubDate.'</li>'; $items = $rss->channel->item; foreach($items as $item) { $title = $item->title; $link = $item->link; $published_on = $item->pubDate; $description = $item->description; echo '<h3><a href="'.$link.'">'.$title.'</a></h3>'; echo '<span>('.$published_on.')</span>'; echo '<p>'.$description.'</p>'; } } ?>which gives me this as the description for each image:- public 'description' => string ' <p><a href="http://www.flickr.com/people/alfthomas/">Alf Thomas</a> posted a photo:</p> <p><a href="http://www.flickr.com/photos/alfthomas/14064465890/" title="harlaw_12"> <img src="http://farm6.staticflickr.com/5077/14064465890_83c02ecec6_m.jpg" width="240" height="110" alt="harlaw_12" /> </a> </p> <p>A view of Harlaw Reservoir.</p>' (length=338)What I actually want is the photo (linked back) without the "Alf Thomas posted a photo" bit, does anyone have any idea how I would go about cloning that bit out? Edited by foucquet, 31 May 2014 - 08:14 AM. Hi everyone, I don't know whether this is a PHP or MySql problem, but I think it is the former. The following code queries the database correctly, (and before you ask, there are no duplicate database entries), but the output duplicates every row. e.g., hammer (jpg image) hammer hammer (jpg image) hammer saw (jpg image) saw saw (jpg image) saw screwdriver (jpg image) screwdriver screwdriver (jpg image) screwdriver and so on. I cannot see why the code causes the row to repeat. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { // Put stored session variables into local php variable $id = $_SESSION['id']; $userId = $_SESSION['userId']; $userGroup = $_SESSION['userGroup']; $managerId = $_SESSION['managerId']; } include_once("demo_conn.php"); $sql = mysql_query("SELECT * FROM users WHERE id='$id'"); while($row = mysql_fetch_array($sql)) { // Get member data into a session variable $egroup = $row["egroup"]; session_register('egroup'); $_SESSION['egroup'] = $egroup; } $query = mysql_query("SELECT topics.url_big, topics.url_small, topics.title, topics.$egroup, quiz.passState, quiz.userDate FROM topics INNER JOIN quiz ON (topics.managerId = quiz.managerId) WHERE topics.$egroup = 1 ORDER BY title ASC"); while ($row1 = mysql_fetch_array($query)) { echo "<a href='../../wood/wood_tool_images/{$row1['url_big']}' target='_blank'><img src='../../wood/wood_tool_images/{$row1['url_small']}' /><br />\n"; echo "{$row1['title']} <br />\n"; } ?> Hi guys,
I am using this code to open and close a pop up window, but as soon as i click the close button this
http://localhost/popup.php?random=&button=
automatically adds in the url, Please tell me what is wrong with the script
<script type="text/javascript"> $(document).ready(function(){ $('a.popup-window').click(function(){ var popupBox = $(this).attr('href'); $(popupBox).fadeIn(400); var popMargTop = ($(popupBox).height() + 24)/2; var popMargLeft = ($(popupBox).width() + 24)/2; $(popupBox).css({ 'margin-top' : -popMargTop, 'margin-left' : -popMargLeft }); $('body').append('<div id="mask"></div>'); $('#mask').fadeIn(400); return false; }); $('button.close,#mask').live('click', function(){ $('#mask,.popupInfo').fadeOut(400,function(){ $('#mask').remove(); }); return false; }); }); $(document).keyup(function(e){ if(e.keyCode ==27){ $('#mask,.popupInfo, #popup-box').fadeOut(400); return false; } }); </script> </head> <body> <a href="#popup-box" class="popup-window">Click</a> <div id="popup-box" class="popupInfo"> <form> <label>ANYTHING</label></br> <input type="text" name="random"/></br> <button type="submit" name="button" class ="close">close</button> </form> </div> </body> </html> Edited by chauhanRohit, 27 June 2014 - 09:46 AM. I have an exercise for school that I have to work out. My teacher is letting us figure it out ourselves, but I've ran into some troubles: - We have to make 2 files: sescook1.php and sescook2.php. - We have to make a form for the user to fill out their name and favorite color (in sescook1.php). - We have to check the input (whether there is input or no). If there's isn't any input, we have to echo 'Please fill out __' (in sescook1.php) - We have to store the name in a session variable and the color in a cookievariable (in sescook1.php) - If both fields are filled in, we ave to show a link 'go to the next page' (where 'next page' is an URL to sescook2.php). - All info has to be shown in sescook2.php (Entered name: __, Entered color: ___) - You have a link 'Go back to previous page' (where 'previous page' is an URL to sescook1.php) My code: Quote <?php session_start(); function checkContent() { if($_POST["name"] == "") echo "Please enter your name"; elseif($_POST["favcolor"]) echo "Please enter your favorite color"; else echo "Go to <a href='http://localhost/webadv1011/PHPCookiesSessies/sescook2.php'>next page"; } ?> <form name="color" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" onsubmit="<?php checkContent(); ?>"> <p>Name: <input type="text" name="naam" /></p> <p>Favourite color: <input type="text" name="favcolor" /></p> <p><input type="submit" name="submit" value="send" /></p> </form> This is the code I got so far. My problem is that the page refreshes itself after it does the checkContent function. I'm also not sure how I save my name in a session variable and the color in a cookie variable (and pass them to the next page as well!). We haven't learned anything on cookies and sessions except our own trial and error and things I found on the internet. Unfortunately, I can't really find lots of useful info (most people refer to Ajax, but we can only use php), or I'm looking in the wrong place. Thanks for your help in advance! Hi Everyone, I am writing a PHP script to allow some of my site members to add links to their site. The script is setup to use a supplied link to an image, then make that image a clickable link which in turns opens that webpage. Here is my code: Code: [Select] <?php if($_POST['formsubmit'] == "Submit") { $varLink = $_POST['Link']; $varImage = $_POST['Image']; $varDescription = $_POST['Description']; } $filea = "temp.tmp"; $fileb = "original.txt"; $filec = "newfile.txt"; $fa=fopen($filea,'w'); /* Open Temp File and Write $_POST data */ if($fa) { fwrite($fa,"<a href='$varLink'><img src='$varImage'></a><br>$varDescription<br><br>\n"); fclose($fa); } $fa=fopen($filea,'r'); /* Open Temp File and Read Contents */ if($fa) { $bufa=fgets($fa); fclose($fa); } $fc=fopen($filec,'w'); /* Open New File to merge new and old Links */ if($fc) { fwrite($fc, $bufa); /* Write Newest Link First */ } $fb=fopen($fileb,'r'); /* Open Original file and Read it */ if($fb) { while(!feof($fb)) { /* Loop through complete old file and write to new file */ $bufb=fgets($fb); fwrite($fc, $bufb); } } fclose($fb); fclose($fc); unlink('original.txt'); /* Delete Original File */ unlink('temp.tmp'); /* Delete Temp File */ rename('newfile.txt', 'original.txt'); /* Rename New File to the Old Filename */ ?> NOTE The above code has been 'expanded' in my troubleshooting efforts... (i.e. I wrote the first write to file code, executed it and checked the file contents manually, then the 2nd step, etc....) so my final code will be shorter. The problem I am having,.... when i write the 1st file 'temp.tmp', I get the expected data in the file (below). <a href='http://www.somesite.com'><img src='http://www.somesite.com/pic.jpg'></a><br>Description of site<br><br> However, when I read the temp.tmp and original.txt files and write it to the newfile.txt (to merge it all together) the expected data is there but with an extra entry after each 'good' entry (below): <a href='http://www.somesite.com'><img src='http://www.somesite.com/pic.jpg'></a><br>Description of site<br><br> <a href=''><img src=''></a><br><br><br> I don't understand why i am getting the extra entry '<a href=''><img src=''></a><br><br><br>' in the file. Can anyone shed some light on this? My head is sore from banging it on the wall! Code: [Select] <?php # This script does get included into the document create_new_tag_from.php if(isset($_POST['tag_name_submit'])){ $tag_name_submit = $_POST['tag_name_submit']; } if(!empty($_POST['tag_name'])){ $tag_name = strip_tags($_POST['tag_name']); } if(!empty($_POST['tag_description'])){ $tag_description = strip_tags($_POST['tag_description']); } if(isset($tag_name_submit)){ # The Validation of User Entered Data # Do validate for solely alphabetic characters with ctype_alpha # ctype_alpha($tag_name) && if(ctype_alpha($tag_description)){ $tag_name = strtolower($tag_name); $tag_description = strtolower($tag_description); # The Insertion Into the Database $db_connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); # Do research if SQL query has to be modified into a PHP comform query $sql_query = sprintf( "set @newid = convert( ( select max(convert( (substring(tag_id, 2)) , unsigned integer))+1 from tags), char(10) ); set @newid = if(length(@newid) = 1, concat('0', @newid), @newid); set @newid = concat('c', @newid); INSERT INTO tags (tag_id, tag_name, tag_description, added_by_user_id, creation_date, last_edited) VALUES (@newid, '%s', '%s', 7, now(), '0')", mysqli_real_escape_string($db_connect, $tag_name), mysqli_real_escape_string($db_connect, $tag_description) ); $sql_query_run = mysqli_multi_query($db_connect, $sql_query); # Print Test to See If It Works echo "works_ "; echo $tag_name . "_ "; echo $tag_description . "_ "; } else { # End of the Validation echo "The entered data must be in alphabetic characters."; } } ?> Here is the form: Code: [Select] <?php include_once('../../header.php'); include_once('../../model/contribution/create_new_tag_script.php'); ?> <form action="" method="post"> <input type="text" name="tag_name" value="" /> <textarea maxlength="60" type="text" name="tag_description" value=""></textarea> <input type="submit" name="tag_name_submit" value="Submit the New Tag" /> </form> <?php include_once('../../footer.php'); ?> By the script as given above the conditional check will skip to the error message. Though I have to say that ctype_alpha does return TRUE when I do try it with "tag_name" which is entered data from the input field, while the other is from the textarea. I simply cannot see the reason for the returned FALSE. I have 2 files; Newfault.php and thankyou.php 1) Data is entered into a form in Newfault.php 2) The data from this form is retieved in thankyou.php and is then inserted into a table called "Calls" Problem: My entered record is being added to my database OK, but it is also adding a blank record for some reason and I can't work out why. Can anyone help? This is for my uni assignment. Thanks, Ladykudos This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=328141.0 I'm having a problem with some php code that allows you to edit a text file. No matter what file it loads, it always adds four horizontal tabs and two spaces to the end of the text. I've attached the code to this post. If anyone can help me with this, it would be greatly appreciated. Cindy Hello Guys, Iam making a new ad serving script. In that site every publisher can register & they will get a url to serve ads. When a user click on that url the publisher will get earnings. But my problem is someone using something like this <iframe src="http://my-site.com/adserve.php" width = "100" height = "100"></iframe> & it will helps to get earnings without clicking on that url. I want to prevent this type of cheating & how it can be possible ?? I hope a expert will replay for me. I am loading a link with ajax. When the link pops on the screen and I click it, I get redirected to my 404 page and my lightbox doesn't load. If the link pops in and I refresh my browser, then I click the link my lightbox will show up. How can I do a prevent default on the <a href> in pure JS? No frameworks please. Hi is there any way we can prevent suppose <textarea></textarea> when page reload it refresh and set default text i wanted to know is there any way to prevent certain things not to get refreshed is there any method in php which prevent to reload this ! <?php echo "<textarea > Enter your favorite quote!</textarea> \n" ; Code: [Select] if (isset($_GET['edit']) && $_GET['edit'] == 'textupdate'){ } <a href= \"{$_SERVER['PHP_SELF']}?page=1&edit=textupdate \" >Click</a>?> Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE);  if(isset($_POST['submit']))  {     $username = $_POST['username']; $password =  ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count =  $result->num_rows;   if($count == 1)              { while ($row = $result->fetch_assoc())  {   if ($row['status'] == 'blocked')  {  echo'your account is suspended'   session_destroy();   exit();  }  else if($row['status'] == 'active') { if($username !== $row['username'])  { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) {  echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>';     } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>  Is this a correct approach to prevent email injection? $to: me@mydomain.com, myPartner@mydomain.com, $emailer; //then the rest of the stuff. $emailCheck = $_POST["emailer"]; if (eregi("(\r|\n)", $emailCheck)) { die("Why ?? "); } mail($to, $subject, "", $headers); |