I'm new to PHP and I have this homework to do. The teacher asked us to display a greeting message to the user which should look like:
Good(Morning/Evening/Night), username, actual date(taken from the system).
PHP:
$username = "Foo";
if (date("H") > 0 && date("H") < 12) {
$msg = "Good day";
$image = "r_sun";
}
else if (date("H") >= 12 && date("H") < 18) {
$msg = "Good evening";
$image = "sun";
}
else {
$msg = "Good Night";
$image = "moon";
}
if (date("d") == 1) {
$c = "st";
}
else if (date("d") == 2) {
$c = "nd";
}
else if (date("d") == 3) {
$c = "rd";
}
else {
$c = "th";
}
echo $msg . "<img src='images/" . $image . ".png' border='0' />, " . $username . "! Today is " . date("F") . " " . date("d") . $c . ", " . date("Y");
My problem is with the image. I have to show 3 different images depending on which message is being displayed (Good morning, evening or night). For some reason the image won't load on the page.
You have to add ../ before the images path on your src attribute like this:
<img src='../images/" . $image . ".png' border='0' />
This means that your image path is not on the same directory as your script, like you doing.
Plus, just a tip, place the date values on an variable:
$h = date("H");
$d = date("d");
if ($h > 0 && $h < 12) {
$msg = "Good day";
$image = "r_sun";
}
if ($d== 1) {
$c = "st";
}
Will clear your code ;)
Based on your comment above:
my code is on the path www/admin and the images are in www/images
It sounds like the img tag just needs a slight adjustment. Try this:
echo $msg . "<img src='../images/" . $image . ".png' border='0' />, " . $username . "! Today is " . date("F") . " " . date("d") . $c . ", " . date("Y");
The key difference is adding the ../ to the start of the path. This is a relative path designation which tells the browser to go up one directory before looking for the path/file specified.
Note that this isn't an issue with the PHP code specifically. The code was correctly emitting a valid img tag. The problem was that the path was pointing to a file that doesn't exist (www/admin/images/filename) instead of one that does (www/images/filename).
The way you've specified your img src, the images must exist in the same directory as your script (or your basehref if you've set that in the html head). Check that first.
Secondly, check the permissions of the images directory. It must be at least world-executable (0711).
Thirdly, check the permissions of the image files. They must be at least world-readable (0644).
Related
I'm stupid, please help me.
I'm not sure why this wouldn't work
I want it to check if a file exists. If it does, then add a count thing.
Something like, if "file" exists. add (2).
Output: file (2). and if "file (2)" exists, change the 2 to a 3, and so on and so forth.
if (file_exists($receverfs)) {
$dupe = "2";
$dupesubject = "$subject ($dupe)";
while (file_exists($dupesubject)) {
$dupesum = $dupe + 1;
$dupesubject = "$subject ($dupesum)";
echo $dupesubject;
}
} else {
$dupesubject = $subject;
echo $dupesubject;
}
I've had to do work with making unique filenames in the past and found using a do/while to be the easiest way to approach this problem:
<?php
$original_file = 'test.txt';
$original_subject = 'test';
$file = $original_file;
$subject = $original_subject;
$pathinfo = pathinfo($original_file);
$dupe = 1;
do {
if ($dupe > 1) {
$file = $pathinfo['filename'] . ' (' . $dupe . ').' . $pathinfo['extension'];
$subject = $original_subject . ' (' . $dupe . ')';
}
++$dupe;
} while (file_exists($file));
echo $subject . PHP_EOL;
In my directory, I have test.txt and test (2).txt. After the loop, the output of $subject will be "test (3)"
I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link display on top of the image?
Display random image from folder using PHP:
function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);
if($leading == '/')
{
$directory = substr($directory, 1);
}
if($trailing != '/')
{
$directory = $directory . '/';
}
if(empty($directory) or !is_dir($directory))
{
die('Directory: ' . $directory . ' not found.');
}
$files = scandir($directory, 1);
$make_array = array();
foreach($files AS $id => $file)
{
$info = pathinfo($dir . $file);
$image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
if(!in_array($info['extension'], $image_extensions))
{
unset($file);
}
else
{
$file = str_replace(' ', '%20', $file);
$temp = array($id => $file);
array_push($make_array, $temp);
}
}
if(sizeof($make_array) == 0)
{
die('No images in ' . $directory . ' Directory');
}
$total = count($make_array) - 1;
$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];
}
Markup:
echo "<img src=" . random_image('css/images/avatars') . " />";
I've tried looking around google for an answer but I can't find anything, any help would be appreciated
You should save the image location in a variable then use it to create a link, plus display it.
$imageUrl = random_image('css/images/avatars');
echo "<a href=" . $imageUrl . ">";
echo "<img src=" . $imageUrl . " />";
echo "</a>";
or if you want to show the text link above, seperately then
$imageUrl = random_image('css/images/avatars');
echo "Click Here<br />";
echo "<img src=" . $imageUrl . " />";
you could use simple javascript to do so, like onclick event for example :
just add this to img tag onclick='window.open('". random_image('css/images/avatars') ."')'
echo "<img onclick='window.open('". random_image('css/images/avatars') ."')' src='" . random_image('css/images/avatars') . "' />";
If you look at many of my questions, you will see that sometimes I don't ask the best questions or I am in such a rush that I don't see the answer that is right in front of me the whole time. If this is another one of those questions, please be kind as some other people haven't been the nicest. Now onto the question.
I have been in the process of creating a file listing viewer type thing for the past week or so. At this point, its all great but I needed to add a search function. I did so by using array_search(). The only problem is that this function requires you to put in the EXACT name of the file rather than part of it.
Here is the problem. I have tried numerous solutions, and to be frank, my PHP skills aren't the most professional. I have tried for array_filters and for loops with strpos. Nothing at this point works. My code is below:
<?php
//error_reporting(0);
//ini_set('display_errors', 0);
//$dir = $_SERVER["DOCUMENT_ROOT"] . '/';
$dir = getcwd();
$files = $files = array_slice(scandir($dir), 2);
$number = count($files);
sort($files);
$images = array();
$an = count($images);
$query = $_GET['q'];
$searchimages = array();
$san = count($searchimages);
$r = array();
if ($query) {
for ($w = 0; $w <= $number; $w++){
$rnum = count($r);
if (strpos($files[$w], $query) !== false) {
$r[$rnum++] = $files[$w];
}
}
if ($r != null) {
if (substr($files[$r], -5) == ".jpeg" || substr($files[$r], -4) == ".png" || substr($files[$r], -4) == ".jpg" || substr($files[$r], -4) == ".gif") {
$searchimages[$san++] = $files[$r];
echo "<a href='#" . $files[$r] . "'>" . $files[$r] . "</a><br>";
} else {
echo "<a href='" . $files[$r] . "'>" . $files[$r] . "</a><br>";
}
for ($z = 0; $z <= $san; $z++)
echo "<a name='" . $searchimages[$z] . "'>" . "<a href='" . $searchimages[$z] . "' target='_blank'>" . "<img src='" . $searchimages[$z] . "'>" . "</img></a>";
} else {
echo "No results found. Please try a different search" . "<br>";
}
} else {
for ($x = 0; $x <= $number; $x++) {
if (substr($files[$x], -5) == ".jpeg" || substr($files[$x], -4) == ".png" || substr($files[$x], -4) == ".jpg" || substr($files[$x], -4) == ".gif") {
$images[$an++] = $files[$x];
echo "<a href='#" . $files[$x] . "'>" . $files[$x] . "</a><br>";
} else {
echo "<a href='" . $files[$x] . "'>" . $files[$x] . "</a><br>";
}
}
for ($y = 0; $y <= $an; $y++) {
echo "<a name='" . $images[$y] . "'>" . "<a href='" . $images[$y] . "' target='_blank'>" . "<img src='" . $images[$y] . "'>" . "</img></a>";
}
}
?>
Currently there are over 2,000 files and they have all sorts of random characters in them. These characters range from dashes to exclamation marks to letters and numbers as well as periods and many more. I don't have control over these file names and they have to stay exactly the same.
If you look at the code, I first get all the file names and store them in an array,
$files
Then I check if the search parameter is supplied in the url,
?q=insert-search-terms-here
After that, if it is supplied, I will search for it (this is where the problem is). If it isn't supplied, I simply get the file names from the array and check if they are an image. If they are, I print them all out at the bottom of the page in the form of thumbnails and make their link at the top a page link that scrolls you down to the location of the image. If it isn't an image, it takes you directly to the file. Note that the thumbnails are links to the actual image.
What is supposed to happen when it searches is that basically does what it would do if it weren't searching, but it limits itself to files that contain the string "foobar" for example.
When it searches but doesn't find anything, it prints out that it didn't find anything and that the user should search again.
If anyone could help with this, it would be greatly appreciated. Like I said at the beginning, please be kind if its a dumb mistake.
Best Regards,
Emanuel
EDIT:
This article now obviously has an answer and for those finding this article on Google or what have you, I want you to read the comments in the answer post as well as the answer as they provide KEY information!!
You may want to use preg_grep. Replace this:
for ($w = 0; $w <= $number; $w++){
$rnum = count($r);
if (strpos($files[$w], $query) !== false) {
$r[$rnum++] = $files[$w];
}
}
with this:
$r = preg_grep('/\Q' . $query . '\E/', $files);
Example:
$files = array(
'foo.bar',
'barfoo.baz',
'baz.fez',
'quantum-physics.ftw',
);
$query = 'foo';
$r = preg_grep('/\Q' . $query . '\E/', $files);
print_r($r);
Output:
Array
(
[0] => foo.bar
[1] => barfoo.baz
)
The preg_match below can be read "match any string ending with a dot followed by jpeg, png, jpg or gif" (the dollar sign can be translated into "end of the string").
if ($query) {
$r = preg_grep('/\Q' . $query . '\E/', $files);
if ($r != null) {
foreach($r as $filename) {
if (preg_match('/\.(jpeg|png|jpg|gif)$/', $filename)) {
// File is an image
echo "$filename is an image<br/>";
// Do stuff ...
} else {
// File is not an image
echo "$filename is NOT an image<br/>";
// Do stuff ...
}
}
// ... Do more
} else {
echo "No results found. Please try a different search" . "<br>";
}
}
http://www.wordinn.com/solution/108/php-getting-part-string-after-and-given-sub-string-or-character
this might be help ful..
function strafter($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false)
return $string;
else
return(substr($string, $pos+strlen($substring)));
}
Something like this will work even for associative array.
foreach ($members as $user){
$Match = substr($user['column'][0], strpos($user['column'][0], "#") + 1);
$final_Array[$i]=$Match;
$i++;
}
print_r($final_Array)
While making a photo gallery I encountered a problem. With every photo I try to show how many comments it has, however if a photo has 0 comments it will give me an 'undefined offset' error. I have no idea what I am doing wrong because it does show that there are 0 comments.
This is the code of what is relevant to the problem:
(The problem occurres in the line: if($reacties[$i]==0){)
if((isset($_GET['vanafFoto'])) AND (intval($_GET['vanafFoto']>=0)) AND (intval($_GET['vanafFoto'] < $countFotos))){
$begin = intval($_GET['vanafFoto']);
if(($begin + $aantalFotos) <= $countFotos){
$eind = ($begin + $aantalFotos);
} // end if
else {
$eind = $countFotos;
} // end else
} // end if
else {
$begin = 0;
$eind = $aantalFotos;
} // end else
$countFotos = count($fotoArray);
// path naar echte foto
} // end else
echo "<table border='0' cellpadding='0' cellspacing='2'><tr><td ><b>" . $pathspatie . "</b> <small>(" . $count . ")</small>
<br><br><center><small>Pictures " . ($begin + 1) . " - " . $eind . "</small></center></td></tr></table>";
if(($begin - $aantalFotos) >= 0){
$navigation = "<a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin - $aantalFotos) . "'><</a> " . $navigation;
} // end if
if(($begin + $aantalFotos) < $count){
$navigation .= " <a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin + $aantalFotos) . "'>></a>";
} // end if
echo $navigation . "<br><br>";
echo "</td></tr><tr>";
$fotonr = 1;
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){ // error occurres here.
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
} // end for
If anyone can see what the problem is it would be great!
I did not understand you exact goal but maybe it is better to write one more check:
if(!isset($reacties[$i]) || $reacties[$i]==0){
echo "0";
}
Please see code snippet at the end of this post...
I consistently get back an error code of 0 when attempting to use move_uploaded_file to move a tmp file into another directory. I've confirmed that the directory exists and the permissions are set to 775 on it. I've also checked with the server admin and he says he's not seeing any errors in the error log that would explain the issue I'm having.
How do I get around an error code of 0 when using move_uploaded_file?
$audio_dir = "/mbc/data/audio/";
if (isset($_POST['upload_audio'])) {
$title = mysql_real_escape_string($_POST['audio_title']);
$category = mysql_real_escape_string($_POST['audio_category']);
$audio_name = basename($_FILES['audio_file']['name']);
$uploadfile = $audio_dir.$audio_name;
$query = mysql_query("SELECT COUNT(*) FROM media where path = '" . $audio_name . "'");
$result = mysql_result($query, 0, 0);
if (($title == '') || ($title == NULL) ||
($category == '') || ($category == NULL) ||
($audio_name == '') || ($audio_name == NULL)) {
echo "<span class='error'>Title, Category and Audio file are required fields</span>";
} else if ($result > 0) {
echo "<span class='error'>Media $audio_name already exists - please upload with a different name</span>";
} else if (ctype_alpha($category) === false) {
echo "<span class='error'>Category can only have letters (no spaces, commas, numbers, etc...)</span>";
} else if (ctype_alnum(substr($audio_name, 0, strpos($audio_name, '.'))) === false) {
echo "<span class='error'>Bad filename - $audio_name - can only contain letters and numbers (i.e. 'HowGreatThouArt.mp3')</span>";
} else {
if (move_uploaded_file($_FILES['audio_file']['tmp_name'], $uploadfile)) {
$queryInsertAudio = "insert into media (title, path, category ) values ('{$title}','{$audio_name}','{$category}')";
$result = mysql_query($queryInsertAudio);
if ($result) {
echo "<span class='success'>AUDIO $audio_name UPLOADED SUCCESSFULLY</span>";
} else {
echo "<span class='error'>FAILED TO INSERT RECORD FOR $audio_name - PLEASE CONTACT ADMINISTRATOR</span>";
}
} else {
echo "<span class='error'>FAILED TO UPLOAD AUDIO $audio_name - PLEASE CONTACT ADMINISTRATOR<br />" .
"ERROR CODE = " . $_FILES['audio_file']['error'] . "<br />" .
"Temp filename=" . $_FILES['audio_file']['tmp_name'] . "<br />" .
"Uploadfile=" . $uploadfile . "<br />" .
print_r($_FILES) .
"</span>";
}
}
}
OOPS...it was my $audio_dir file path that was off...fixed that up and now I'm able to upload no problem...