Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new at php and I am not sure what I am doing wrong. I am trying to list all the records from a txt file. However, my code is only displaying the first line. How can I get the code to display all the records from the file?
$count = 0;
$soldOut = 0;
$eventFile = fopen("performances.txt", "r");
$event = fgets($eventFile);
while ( feof($eventFile));
{
list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
if($status == "Yes")
{
$status = "Tickets are still available";
$count = $status +1;
}
else
{
$status = "***SOLD OUT***";
$soldOut = $status +1;
}
print("<tr><td>$dateEvent </td>");
print("<td>$performer </td>");
print("<td>$ticketprice </td>");
print("<td>$status</td></tr>");
$event = fgets($eventFile);
}
Pay attention to the docs, you'll notice that your loop should be:
while( !feof($eventFile)) {
$event = fgets($eventFile); // THIS is where you get the current line
// do stuff here
}
you can read file this way. You can find more on this http://us1.php.net/function.file-get-contents
<?php
$data = file_get_contents("performances.txt",FILE_USE_INCLUDE_PATH); //read the file
$convert = explode(":", $data); //create array separate by new line
for ($i=0;$i<count($convert);$i++)
{
echo $convert[$i].', '; //write value by index
}
?>
Looping as instructed at http://www.php.net/manual/en/function.fgets.php
Basically, keep looping until fgets nolonger returns anything, and then check if pointer matches with end of file.
I also suggest you take a look at http://www.php.net/manual/en/function.stream-get-line.php
the comments make a case for performance gains.
$count = $soldOut = 0;
$eventFile = fopen("performances.txt", "r");
if ($eventFile) {
# Keep reading as long as fgets returns content
while ( ($event = fgets($eventFile)) !== false ) {
list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
if($status == "Yes") {
$status = "Tickets are still available";
++$count; # increase count with one
} else {
$status = "***SOLD OUT***";
++$soldOut; # increase soldout with one
}
echo '<tr>',
'<td>',$dateEvent,'</td>',
'<td>',$performer,'</td>',
'<td>',$ticketprice,'</td>',
'<td>',$status,'</td>',
'</tr>';
}
# something went wrong
if (!feof($eventFile)) {
echo "Error: unexpected fgets() fail\n";
}
# remember to close them files
fclose($eventFile);
} else {
# failed to open
}
Related
This question already has answers here:
getting warning "Header may not contain more than a single header, new line detected"
(9 answers)
Closed 9 months ago.
I managed to get every other error ironed out, but I am stuck with this error! For the life of me, I cannot seem to diagnose where I went wrong. Any help from you brilliant people out there would be amazing!
I made a form editing php where it is supposed to edit a submission made into the system. This is then processed by my processing php but for some reason I am getting a "header may not contain more than a single header" error in my form submission. I changed the header code multiple times but I do not know why I am still getting it: https://imgur.com/reX4Yyb
Edit:
Also wanted to add that this code was working fine for about a month. The only thing I changed was updating the hosting service platform from PHP 7.3 -> PHP 7.4. I tried reverting and it exactly the same error.
if($_POST['form_submitted'] == 'editgroupreferral'){
include("../../inc/inc.con.php");
/* assign values to checkboxes */
if(isset($_POST['OtherServices'])){
$otherservices = 1;
} else {
$otherservices = 0;
}
if(isset($_POST['Medication'])){
$medication = 1;
} else {
$medication = 0;
}
if(isset($_POST['HaveAllergies'])){
$allergies = 1;
} else {
$allergies = 0;
}
if(isset($_POST['Device'])){
$device = 1;
} else {
$device = 0;
}
if(isset($_POST['Share'])){
$share = 1;
} else {
$share = 0;
}
if(isset($_POST['TakeTurns'])){
$taketurns = 1;
} else {
$taketurns = 0;
}
if(isset($_POST['Wait'])){
$wait = 1;
} else {
$wait = 0;
}
if(isset($_POST['MultInstructions'])){
$multinstr = 1;
} else {
$multinstr = 0;
}
if(isset($_POST['SitChair'])){
$sitchair = 1;
} else {
$sitchair = 0;
}
if(isset($_POST['Routine'])){
$routine = 1;
} else {
$routine = 0;
}
/* insert vars from form into ReferralSC table */
$sql = "UPDATE ReferralGR SET
ReferrerName = :refname,
ReferrerRelationship = :refrelationship,
ReferrerPhone = :refphone,
ReferrerEmail = :refemail,
ReferMethod = :refmethod,
RefSupport = :refsupp,
OtherServices = :otherservices,
School = :school,
Diagnosis = :diagnosis,
Medication = :medication,
MedicationList = :medicationlist,
HaveAllergies = :allergies,
AllergiesList = :allergieslist,
Device = :device,
Share = :share,
TakeTurns = :taketurns,
Wait = :wait,
MultInstructions = :multinstr,
SitChair = :sitchair,
Routine = :routine,
ExplainFurther = :explain,
HeardAbout = :heardabout,
RefNotes = :notes
WHERE ref_id = :grid";
$s = $pdo->prepare($sql);
$s->bindvalue(':refname', $_POST['ReferrerName']);
$s->bindvalue(':refrelationship', $_POST['ReferrerRelationship']);
$s->bindvalue(':refphone', $_POST['ReferrerPhone']);
$s->bindvalue(':refemail', $_POST['ReferrerEmail']);
$s->bindvalue(':refmethod', $_POST['ReferMethod']);
$s->bindvalue(':refsupp', $_POST['RefSupport']);
$s->bindvalue(':otherservices', $otherservices);
$s->bindvalue(':school', $_POST['School']);
$s->bindvalue(':diagnosis', $_POST['Diagnosis']);
$s->bindvalue(':medication', $medication);
$s->bindvalue(':medicationlist', $_POST['MedicationList']);
$s->bindvalue(':allergies', $allergies);
$s->bindvalue(':allergieslist', $_POST['AllergiesList']);
$s->bindvalue(':device', $device);
$s->bindvalue(':share', $share);
$s->bindvalue(':taketurns', $taketurns);
$s->bindvalue(':wait', $wait);
$s->bindvalue(':multinstr', $multinstr);
$s->bindvalue(':sitchair', $sitchair);
$s->bindvalue(':routine', $routine);
$s->bindvalue(':explain', $_POST['ExplainFurther']);
$s->bindvalue(':heardabout', $_POST['HeardAbout']);
$s->bindvalue(':notes', $_POST['RefNotes']);
$s->bindvalue(':grid', $_POST['ref_id']);
$s->execute();
header('location:../refer_gr/referral-view.php?rid=' . $_POST['ref_id'] );
}
This warning occurs to indicate that you might have a new line [/n] in the string content of your variables. The solution is to strip out the passable new line contents of the variable Like this
$val=$_POST['ref_id'];
$url="../refer_gr/referral-view.php?rid='$val'";
$url=str_replace(PHP_EOL, '', $url);
header("Location: $url");
Okay, this one was a toughie but I figured it out. Here is my method:
So the clue lies in the error itself. It was pointing me from my processing php. But it was only because the data being asked in the header (requires a reference ID) is wrong.
The problem was in the reference ID (after much debugging). It was taking the wrong value from the wrong variable. This was in the php form page not the php processing page.
So here is the solution:
$s->bindvalue(':refid', $refid);
Rest of the code:
<input type="hidden" name="ref_id" value="<?php echo $rid; ?>" >
The variable $rid is not the same as the variable $refid.
Here is the fix:
<input type="hidden" name="ref_id" value="<?php echo $refid; ?>" >
This means that with this type of error, it might be worth looking at which part of the code it is trying to get the value from and start debugging from there.
Thanks for the help everyone!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to make just simple incrementing with session but the session just stop every time on 2. Can you please help me what I should do?
if (!isset($_SESSION["current"]))
{
$_SESSION["current"] = 1;
}
$_SESSION["current"] = $_SESSION["current"] +1;
echo "SESSION: ".$_SESSION["current"]."<br>CURRENT: ";
I tryed this code and it doesnt work too:
<?php
if (isset($_POST["previous"]))
{
$_SESSION["current"] = $_SESSION["current"] - 1;
}
if (isset($_POST["next"]))
{
$_SESSION["current"] = $_SESSION["current"] + 1;
}
echo "SESSION: ".$_SESSION["current"]."<br>CURRENT: ";
?>
I believe you want to use this "current" value for pagination. If that is the case you are going about it a bit wrong. Remember the session will store the last value set until it is destroy or reset with another value. Here is my take
<?php
session_start(); // according to you, you don't need this so please remove
$current = 0; // lowest value for our pagination
if(isset($_SESSION['current'])){
$current = $_SESSION['current']; // session has an entry
}
if ((isset($_POST["previous"]) || isset($_POST['next'])))
{
if(isset($_POST['previous'])){
$current -= 1; // for previous
}else{
$current += 1; // for next
}
$current = ($current >= 0)?$current: 0; // reset to 0 when we get to negative
}else{
$current = 0; // we maybe back on the "start page"
}
$_SESSION['current'] = $current;
echo "SESSION: ".$_SESSION["current"]."<br>CURRENT: ";
That code should work, maybe your session is not active. try to issue this on top of your script:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}`
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to send a string of numbers to the server and split each number. If the number exists on the database assign a "t" value and if it doesn't then assign "f" value.
But for some reason I get t's only.
<?php
# get phone from uid
include_once 'utils.php';
$phone = $_GET['phone'] or die("isRegistered: missing phone");
$response = "";
$phonearray = explode(":", $phone);
for ($i = 0; $i<sizeof($phonearray); $i++){
$result = findRow("phone", $phonearray[i], "user_device") or "true" ;
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."f".":";
$result = "";
}
}
die($response);
?>
There's actually a couple problems here.
As mentioned in the other answers, you're mistakenly using 't' in both branches of your code.
You appear to be using the string "true" instead of the boolean true. While it may appear to work because of the way PHP converts values between types, you're probably actually intending to use true, and using the string instead can lead to unexpected behavior later.
I don't know what findRow() does, but by adding or true (or even or "true") to the end of it, $result will always be true.
You're using i to reference the $phonearray instead of $i. i will generate a PHP warning, and will be interpreted as "i" - instead of the value of the $i variable.
If you look at this part of your code:
$result = findRow("phone", $phonearray[i], "user_device") or "true" ;
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."t".":";
$result = "";
}
You'll get better results by rewriting it like this:
$result = findRow("phone", $phonearray[$i], "user_device");
$response .= ($result ? 't' : 'f') . ':';
I'm guessing a bit as to what findRow() does since you didn't include anything about it - but I'm assuming it just returns a true/false value.
You'll notice that I've also simplified the entire if/else statement down to a couple lines by using the ternary operator as well.
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."t".":";
$result = "";
}
change this part to
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."f".":";
$result = "";
}
You have set "t" for both if and else condition.
and do check
if(isset($_GET['phone']))
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."t".":";
$result = "";
}
change this part to
if($result == 'true')
{
$response = $response.'t:';
$result = '';
}
else
{
$response = $response.'f:';
$result = '';
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Something I've never been sure about is how many variable checks to do in PHP. For example take the following piece of code. I am not checking any of the variables before I assign them or pass them to a function to see if they contain what I expect
$carId = '12';
$aCar = fetchCar($carId);
$make = $aCar['make'];
$model = $aCar['model'];
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
Now if I add some checks
$carId = '12';
if(is_numeric($carId))
{
$aCar = fetchCar($carId);
if(isset($aCar['make']) && is_string($aCar['make']))
{
$make = $aCar['make'];
}
else
{
//Report error
}
if(isset($aCar['model']) && is_string($aCar['model']))
{
$model = $aCar['model'];
}
else
{
//Report error
}
if(isset($aCar['year']) && is_numeric($aCar['year']))
{
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
}
else
{
//Report error
}
}
else
{
//Report errors
}
The code is now better but is it a bit too excessive and bloated? Should I be doing this many checks?
If I shouldn't be doing this many checks where do you draw the line between what you should and shouldn't check?
This is the dilemma of a dynamic type language.
It depends heavily on what fetchCar() function is doing.
The approach i would take is assume fetchCar is returning a car array or throwing exception.
If you combine this with good exception handling logic you can end up with clean and stable code.
For example:
function fetchCar($id) {
$car = queryDatabaseSomehow();
if (empty($car)) {
throw new ExceptionNotFound();
}
//eventually you can put your type checking here?
if (!isset($car['x']) || !is_string($car['x'])) {
throw new ExceptionDb();
}
}
echo fetchCar(3)['make'];
Also if you would like to do this super-proper and go fully OOP, Car should become a class with make,model and year as its members. fetchCar() would return Car or throw Exception. But this is not always desirable of course.
One issue that some people haven't noticed. Be wary of using is_string:
<?php
$var = "test";
$var['something'] = 2;
if(is_string($var['something'])) {
echo "Hello world!"; // Will echo this because $var is a string!
} else {
echo "Hello hell!";
}
echo "<br/>";
echo $var['something']; // returns 2
?>
PHPFiddle.
Compare it with this:
$var = array('something' => 2);
if(is_string($var['something'])) {
echo "Hello world!"; // $var is now an array
} else if (is_numeric($var['something'])) {
echo "Hello hell!"; // Will echo this because $var is string!
}
echo "<br/>";
echo $var['something'];
You need to check whether $var is an array, as it might give you unexpected results. isset($var['something']) will return true in the first example.
To answer your question, I don't think those are too many checks. It really depends on what fetchCar() does and how it gets the data. If you can't trust it (say, it's based on user data) then you should perform all these checks. If not, then there is no point really.
I rather turn it all into a function that can be reused for these cases.
function check_keys($arr_check, $arr_cond) {
$boo_success = TRUE;
foreach(array_keys($arr_cond) as $h)
if (in_array($arr_cond[$h], array('is_string', 'is_numeric'))) {
if ( ! isset($arr_check[$h]) or ! ($arr_cond[$h]($arr_check[$h]))) {
$boo_success = FALSE;
echo "The key {$h} is missing!";
// If run through a class, $this->errors[] = 'error message';
}
} else {
$boo_success = FALSE;
echo 'Invalid function';
}
return $boo_success;
}
$arr_keys = array('make' => 'is_string',
'model' => 'is_string',
'year' => 'is_numeric');
if (check_keys($aCar, $arr_keys)) {
// Run successful stuff
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have the following PHP code to display my tag cloud. It seems if I don't have at least two tags that are the same, I get a warning message saying Warnng: Division by zero (shown below).
Could some one please help me fix this code? Thank you!
<?php
// define variables
$fontSizeUnit = "px";
$maxFontSize = 40;
$minFontSize = 10;
$tagsToDisplay = 100;
$tagDivider = " ";
// font size range
$fontSizeSpread = $maxFontSize - $minFontSize;
// create blank arrays
$tagArray = array();
$tempTagArray = array();
// DB: get all public tags
$result = mysqli_query($conn, "SELECT Tags FROM blog WHERE Tags != '' AND IsPublic = 1 ORDER BY RAND()")
or die($dataaccess_error);
if(mysqli_num_rows($result) > 0 )
{
// loop through results
while($row = mysqli_fetch_array($result))
{
// split the results
$tempStringArray = preg_split("/,/", $row['Tags']);
// loop through all items of this string array
for ($a = 0; $a < count($tempStringArray); $a++)
{
// convert to lowercase
$tempStringArray[$a] = strtolower($tempStringArray[$a]);
// check if it exists in tag array
if (empty($tagArray[$tempStringArray[$a]]))
{
// if it doesn't exist, create it with value 1
$tagArray[$tempStringArray[$a]] = 1;
}
else
{
// if it does exist, increase the value by 1
$tagArray[$tempStringArray[$a]] += 1;
}
}
}
// store to temporary array and sort descending
arsort($tagArray);
$numberOfTags = 0;
foreach ($tagArray as $key => $val)
{
$numberOfTags++;
if ($numberOfTags > $tagsToDisplay)
{
break;
}
$finalTagArray[$key] = $val;
}
ksort($finalTagArray);
$maxTagCount = max($finalTagArray);
$minTagCount = min($finalTagArray);
$tagCountSpread = $maxTagCount - $minTagCount; // <<== Problem here...
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
// function to calculate the font size
function calcSize($thisTagCount) {
// import necessary global variables
global $minTagCount, $minFontSize, $fontSizeUnit, $unitsPerCount;
// calculate font size
$thisFontSize = $minFontSize+($unitsPerCount*($thisTagCount-$minTagCount));
// round font size and add units
$thisFontSize = round($thisFontSize) . $fontSizeUnit;
// return font size
return $thisFontSize;
}
// echo out the resulting tags
$b = 1;
foreach ($finalTagArray as $key => $val)
{
echo "<a href='snippets-by-tags.php?tag=".urlencode($key)."' style='font-size: ";
echo calcSize($val);
echo "'>" . htmlentities($key) . "</a>";
if($b != count($finalTagArray))
{
echo " " . $tagDivider . " ";
}
$b++;
}
}
else
{
echo 'none found ...';
}
?>
You should check if $tagCountSpread is 0, obviously dividing with 0 = infinite. (Hence you receive an error). This could be an quick fix, but you should really think of the proper solution for your application.
if ($tagCountSpread <= 0) $tagCountSpread = 1;
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
Your problem is actually with this line:
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
If $tagCountSpread is zero, this is a division by zero. That will happen when $maxTagCount and $minTagCount are the same.
You should guard against this:
if ($tagCountSpread != 0)
{
$unitsPerCount = $fontSizeSpread / $tagCountSpread;
}
else
{
// sensible recovery code
}
// ...
$minTagCount = min($finalTagArray);
if(($tagCountSpread = $maxTagCount - $minTagCount) === 0){
// do something else when its zero; throw an exception, throw a party... whatever
}
// otherwise continue
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
// ...
Perhaps your problem is the following line:
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
And not the previous one. You should check if $tagCountSpread is NULL (0) and if not, do the division:
if($tagCountSpread != 0)
{
$unitsPerCount = $fontSizeSpread/$tagCountSpread;
}else{
///something
}
PHP will show what line it happens on, figure out why it's dividing by zero and fix that (Probably using some conditionals).