I'm developing a browser extension (content script) that scans and highlights certain words on a page, and uses AJAX and PHP to echo back content into a tooltip that appears when a user hover over said words. One thing that gets echoed back from the PHP file is an image, but my problem is that I don't have an image for every keyword - what I want is the PHP to only echo back an image when one exists at the given URL. As of now, certain words show images, others show the "image not found" icon. What I want is for no "image not found" icon if the image doesn't exist.
I have the AJAX send the variable ($data) to the PHP files hosted on my website. Maybe have it check the HTTP header of the url before echoing?
Here is my code:
$data = $_POST['id'];
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
Why don't you just check it like this?
$data = $_POST['id'];
if($data !== "") {
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "http://extension.nicholasrub.in/headshots/notFound.png'>";
}
EDIT:
Use file_exists():
$data = $_POST['id'];
$imagePath = "/path/images/" . $data . ".png";
if (file_exists($imagePath)) {
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "http://extension.nicholasrub.in/headshots/notFound.png'>";
}
You can check if a file exists using this function
http://php.net/manual/en/function.file-exists.php
if you want to check image what is not exist on your server then use this code:
$data = $_POST['id'];
$imagePath = "http://extension.nicholasrub.in/headshots/$data.png";
echo "http://extension.nicholasrub.in/headshots/".(file_get_contents(imagePath) ? $data : 'notFound').".png'>"
I ended up solving the problem by checking whether the HTTP headers were 404 or not.
My Code:
$file = "http://extension.nicholasrub.in/headshots/" . $data . ".png";
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
if ($exists == true) {
echo "<div id='my-tooltip-2986234'><div><img src='http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "<div id='my-tooltip-2986234'><div>";
}
Related
does anyone know how to return error array in a javascript alert box? The code below that I have doesn't do the trick right. Browser returns "Cannot use [] for reading". When using $error without the bracket, browser only returns the word "Array" in the alert box but the error message is not showing. Any help?
echo '<script type="text/javascript">alert("Error: '.$errors[].'");</script>';
Updated to include the extent of my code:
$errors = [];
$target_dirRFP = ('accounts/' . $order_list . '/rfp/');
$file_nameRFP = $_FILES['FileToUploadRFP']['name'];
$file_sizeRFP = $_FILES['FileToUploadRFP']['size'];
$extentionRFP = pathinfo($file_nameRFP, PATHINFO_EXTENSION);
$tempRFP = ($_FILES["FileToUploadRFP"]["tmp_name"]);
$target_fileRFP = ($target_dirRFP . $file_nameRFP);
$valid_formatsRFP = array("pdf");
$target_dirPSA = ('accounts/' . $order_list . '/psa/');
$file_namePSA = $_FILES['FileToUploadPSA']['name'];
$file_sizePSA = $_FILES['FileToUploadPSA']['size'];
$extentionPSA = pathinfo($file_namePSA, PATHINFO_EXTENSION);
$tempPSA = ($_FILES["FileToUploadPSA"]["tmp_name"]);
$target_filePSA = ($target_dirPSA . $file_namePSA);
$valid_formatsPSA = array("pdf");
if(!empty($file_nameRFP)) {
if(in_array($extentionRFP, $valid_formatsRFP) === false) {
$errors[] = "The RFP you selected to upload is not allowed. Only PDF file is permitted.";
}
if (file_exists($target_fileRFP)) {
$errors[] = "Attached RFP: \"'.$file_nameRFP.'\" already exists.\nPlease select another file to upload.";
}
}
if(!empty($file_namePSA)) {
if(in_array($extentionPSA, $valid_formatsPSA) === false ) {
$errors[]="The PSA you selected to upload is not allowed. Only PDF file is permitted.";
}
if (file_exists($target_filePSA)) {
$errors[] = "Attached PSA: \"'.$file_namePSA.'\" already exists.\nPlease select another file to upload.";
}
}
if(empty($errors)==true) {
move_uploaded_file($tempRFP, $target_fileRFP);
move_uploaded_file($tempPSA, $target_filePSA);
$stmt = $DB_CON_C->prepare("INSERT INTO `".$order_list."`
SET first_name = '$first_name', last_name = '$last_name'");
$stmt->execute();
echo '<script type="text/javascript">alert("Submitted.");</script>';
} else {
echo '<script type="text/javascript">alert("Error: ' . implode("; ", $errors) . '");</script>';
}
Using implode() and entering new lines is most likely the best way.
Example:
<?php
$errors = [];
if( validateFails() ){
$errors[] = "some error found";
}
if( failAgain() ){
$errors[] = "some other error";
}
echo '<script>alert("'.implode("\\n", $errors).'");</script>';
UPDATE:
Another error lies on your error message string syntax. Take a look at this line:
$errors[] = "Attached PSA: \"'.$file_namePSA.'\" already exists.\nPlease select another file to upload.";
This should be re-written to:
$errors[] = "Attached PSA: $file_namePSA already exists.\\nPlease select another file to upload.";
As any variable inside double quotes "..." will be echoed out correctly. And a new line in the string should be \\n not \n.
You could transform your array in string with implode()
echo '<script type="text/javascript">alert("Error: ' . implode("; ", $errors) . '");</script>';
You'd have to create a single string representation of some sort. For example, you could "implode" the array using a delimiter. Something like:
echo '<script type="text/javascript">alert("Error: ' . implode(', ', $errors) . '");</script>';
This would just be a simple comma+space delimiter between all of the array elements. If you need something more complex or with more styling (in which case you probably don't want an alert() in the first place) then you could manually build any string you like from the contents of the array. You just need to output a string to the page, not an array directly.
Hopefully you will get exact output.Please try
alert(JSON.stringify($errors));
The code is available below.
The issue is explained on the title of this post....
<?php
$filenumber = $_POST['filenumber'];
$file = 'view/$filenumber.txt';
$sharedfile = 'view/$shared.txt';
if(!isset($filenumber) || trim($filenumber) == '')
{
echo "The file number field is empty or #$filenumber does not exist. Redirecting you in 3 seconds.";
header ( "refresh:3;url=https://2.survivaltimepe.com" );
exit;
}
$shared = $_POST['shared'];
if(!isset($shared) || trim($shared) == '')
{
echo "The shared number field is empty or #$shared does not exist. Redirecting you in 3 seconds.";
header ( "refresh:3;url=https://2.survivaltimepe.com" );
exit;
}
$file = view/$filenumber.txt;
if (file_exists($file)) {
echo "";
} else {
echo "The field is empty or the #$filenumber file number does not exist. Redirecting you in 3 seconds.<br>";
}
$sharedfile = view/$shared.txt;
if (file_exists($sharedfile)) {
echo "";
} else {
echo "The field is empty or the #$shared shared number does not exist. Redirecting you in 3 seconds.";
header ( "refresh:3;url=https://2.survivaltimepe.com" );
exit;
}
$file = "view/$filenumber.txt";
unlink($file);
$sharedfile = "view/$shared.txt";
unlink($sharedfile);
echo ("File #$filenumber has been successfully removed.<br>Remember that you can always create a new link on the site.<br><br>Redirecting you in 10 seconds.");
header( "refresh:10;url=https://2.survivaltimepe.com" );
?>
title explains most of all that it displays the variable , instead it should be view/thehtmlformpostnumberhere.txt
Change $file = 'view/$filenumber.txt'; to $file = 'view/'.$filenumber'.'.txt';
Update:
I saw in your script you have more of this cases. When you use a variable in a string use '.$variable.'
I got an error when handling a not seated avatar image, 0.jpg is a default user avatar and every user had an avatar called firstname_lastname.jpg
<?php
$uname_ = 'John_Doe';
$avname = "media/avatars/" . $uname_ . '.jpg';
if(file_exists($avname) {
$avatar = $uname_ ;
} else {
$avatar = "0" ;
}
?>
<img src="media/avatars/<?php echo $avatar ?>.jpg">
This does't work, and is preventing the page to show. I get a blank response.
you got this
if(file_exists($avname) {
need this
if(file_exists($avname)) {
I have used this tutorial to implement the steam login for a website I am creating: https://github.com/SmItH197/SteamAuthentication/blob/f47fc78056081d6a83d277ae447c5386dc0909fc/README.md . Problem is, when I log in, it does not display any info, only a logout button. Here is the code I am dealing with.
if(isset($_SESSION['steamid'])){
include("settings.php");
if (empty($_SESSION['steam_uptodate']) or $_SESSION['steam_uptodate'] == false or empty($_SESSION['steam_personaname'])) {
//We mute alerts from the following line because we do not want to give away our API key in case file_get_contents() throws a warning.
# $url = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$steamauth['apikey']."&steamids=".$_SESSION['steamid']);
if($url === FALSE) { die('Error: failed to fetch content form Steam. It may be down. Please, try again later.'); }
$content = json_decode($url, true);
$_SESSION['steam_steamid'] = $content['response']['players'][0]['steamid'];
$_SESSION['steam_communityvisibilitystate'] = $content['response']['players'][0]['communityvisibilitystate'];
$_SESSION['steam_profilestate'] = $content['response']['players'][0]['profilestate'];
$_SESSION['steam_personaname'] = $content['response']['players'][0]['personaname'];
$_SESSION['steam_lastlogoff'] = $content['response']['players'][0]['lastlogoff'];
$_SESSION['steam_profileurl'] = $content['response']['players'][0]['profileurl'];
$_SESSION['steam_avatar'] = $content['response']['players'][0]['avatar'];
$_SESSION['steam_avatarmedium'] = $content['response']['players'][0]['avatarmedium'];
$_SESSION['steam_avatarfull'] = $content['response']['players'][0]['avatarfull'];
$_SESSION['steam_personastate'] = $content['response']['players'][0]['personastate'];
if (isset($content['response']['players'][0]['realname'])) {
$_SESSION['steam_realname'] = $content['response']['players'][0]['realname'];
} else {
$_SESSION['steam_realname'] = "Real name not given";
}
$_SESSION['steam_primaryclanid'] = $content['response']['players'][0]['primaryclanid'];
$_SESSION['steam_timecreated'] = $content['response']['players'][0]['timecreated'];
$_SESSION['steam_uptodate'] = true;
}
$steamprofile['steamid'] = $_SESSION['steam_steamid'];
$steamprofile['communityvisibilitystate'] = $_SESSION['steam_communityvisibilitystate'];
$steamprofile['profilestate'] = $_SESSION['steam_profilestate'];
$steamprofile['personaname'] = $_SESSION['steam_personaname'];
$steamprofile['lastlogoff'] = $_SESSION['steam_lastlogoff'];
$steamprofile['profileurl'] = $_SESSION['steam_profileurl'];
$steamprofile['avatar'] = $_SESSION['steam_avatar'];
$steamprofile['avatarmedium'] = $_SESSION['steam_avatarmedium'];
$steamprofile['avatarfull'] = $_SESSION['steam_avatarfull'];
$steamprofile['personastate'] = $_SESSION['steam_personastate'];
$steamprofile['realname'] = $_SESSION['steam_realname'];
$steamprofile['primaryclanid'] = $_SESSION['steam_primaryclanid'];
$steamprofile['timecreated'] = $_SESSION['steam_timecreated'];
}
What I want to happen is when someone logs in, where the sign in button was, I want to show the steam name as well as the avatar of whoever signed in.
Did you read the documentation? To show avatar, do the following:
$steamprofile['avatar'] // 32x32 version of avatar
$steamprofile['avatarmedium'] // 64x64 version of avatar
$steamprofile['avatarfull'] // 184x184 version of avatar
To display the Steam username, do the following:
$steamprofile['personaname']
It's all written in the README.md file at the bottom.
EDIT: If you want to show the image, do something like this:
echo '<img src="' . $steamprofile['avatar'] . '" />';
That will put the image URL from $steamprofile['avatar'] into an <img> element.
Here is my code, you can view an example of it by going to:
www.craftquake.com/statusChecker.php?site=MCnet
<?php
$getter = $_GET['site'];
if ($getter == 'ts3')
{ $site = test_port('ts3.craftquake.com',10011,4); }
if ($getter == 'MCquake')
{ $site = test_port('play.craftquake.com',25565,4); }
if ($getter == 'MCnet')
{ $site = test_port('minecraft.net',80,4); }
$teamspeak = test_port('ts3.craftquake.com',10011,4);
$online = '<img src="/online.png">';
$offline = '<img src="/offline.png">';
$unknown = '<span class="status-unknown" id="status-image">Unknown</span>';
function test_port($host,$port=80,$timeout=1)
{
$fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
if ( ! $fsock )
{
return FALSE;
}
else
{
return TRUE;
}
}
?>
##HEADER & CSS, ETC
<?php
if ($site == 1)
{ $status = $online;
} else if ($site == 0) {
$status = $offline;
} else {
$status = $unknown;
}
header('content-type: image/png');
readfile($status);
echo $status;
?>
I want to, in the footer of my page, link to this page to display the status. I was doing this with another site's script by linking their status of Minecraft.net's servers as the and it worked perfectly, however I have no idea how they made that work. The images are PNG's, but if there is only one format that works, I can convert them.
I have tried the header(blablabla) function, but it doesn't seem to work...
Thank you very much!
Your variables contain HTML instead of the path name to the image files:
$online = '<img src="/online.png">';
should be:
$online = 'online.png';
Create a unknown status image and put it in $unknown too.
An image should be a seperate request (so, put an <img src="/yourimagescript.php"> in your html page, and in that seperate script output only the image, no html. You could embed (small) images with the data: protocol, but I strongly advise against it.